text:
Arduino hardwareSerial Bluetooth.println not sending string over 310 chars
Hey all I am wondering if my code below can be modified in order for the Arduino to send more than 300 chars to a HM-10 bluetooth 4.0 le module?
#include <SoftwareSerial.h>
#define SERIAL_BUFFER_SIZE 512

SoftwareSerial bluetooth(8,9); // RX, TX
String btString;
String comString;
int isVS;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {;}

  Serial.println("PC Side Connected");

  bluetooth.begin(115200);
  while (!bluetooth) {;}

  bluetooth.println("Bluetooth Side Connected");
}

void loop() {
  if (Serial.available() > 0) {
    //The IDE Sends and the phone receives
    comString = Serial.readString();

    //Check to see if this request is coming from Visual Studio
    isVS = comString.indexOf("_VS");

    if (isVS > -1) {
      //Is coming from Visual Studio so display it over serial port
    } else {
      //Not coming from VS so send it to the bluetooth phone
      //bluetooth.write(comString);
      bluetooth.println(comString);
    }
  }

  if (bluetooth.available() > 0) {
    //The phone sends and the IDE receives
    btString = bluetooth.readStringUntil('\n');
    Serial.println(btString);
  }
}

As in my code above, I've already tried to add the #define SERIAL_BUFFER_SIZE 512 to the top to give the software serial more buffers but that does not allow me to send more than ~310 chars.
So sending this string:

{MAC:'00-14-22-01-23-45',settings:{rgb:true,quotes:true,sleep:false,timeFrame:{on:'05:30:00',off:'22:30:00'},reset:false,weatherZip:'57104',userInfo:{left:'John
  Rambo',right:'T100'}},wifiInfo:{Name:'ItBurnsWhenIP',Pwd:'AwHk6gKnsMdxw3boWWAhus5NNCV304YQb/2287QqzH0WnS5W59vCzzW2pR8kgHI79hAUglQOCcBiEKiNWRBQ3oyvyJ0/fDfM1aKa9gfoy3kGHA=='}}

works just fine but if i send out a little more information:

{MAC:'00-14-22-01-23-45',settings:{rgb:true,quotes:true,sleep:false,timeFrame:{on:'05:30:00',off:'22:30:00'},reset:false,weatherZip:'57104',userInfo:{left:'JohnRambo',right:'T100'}},wifiInfo:{Name:'ItBurnsWhenIP',Pwd:'AwHk6gKnsMdxw3boWWAhus5NNCV304YQb/2287QqzH0WnS5W59vCzzW2pR8kgHI79hAUglQOCcBiEKiNWRBQ3oyvyJ0/fDfM1aKa9gfoy3kGHA==','testing
  out some more strings'}}

It shows everything but the gs'}} at the end on the iphone.
How would i go about fixing this so i can send much more than this?

Re work it to not use String. The problem isn't serial, it's how you're storing the data.

Alright mind showing me an example?

You need to understand both these blog posts: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/ and https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/


text:
How to write makefile-compatible sketches?
I'd like to write my sketches so that I can either build/upload them using the Arduino IDE, or optionally using GCC and a makefile.
I know about including the function declarations at the top, but is there anything else to do in order for my sketch to be considered valid C++ by my compiler?
Update 1
Understanding what the Arduino IDE does to .ino and .pde files is fine, but extraneous to my question, so this is not a duplicate. What I want to know is "how do I write a program such that it is considered valid both by the Arduino IDE and g++.
The official(?) makefile available here explains what to do if using the makefile instead of the IDE:
# The Arduino environment does preliminary processing on a sketch before
# compiling it.  If you're using this makefile instead, you'll need to do
# a few things differently:
#
#   - Give your program's file a .cpp extension (e.g. foo.cpp).
#
#   - Put this line at top of your code: #include <WProgram.h>
#
#   - Write prototypes for all your functions (or define them before you
#     call them).  A prototype declares the types of parameters a
#     function will take and what type of value it will return.  This
#     means that you can have a call to a function before the definition
#     of the function.  A function prototype looks like the first line of
#     the function, with a semi-colon at the end.  For example:
#     int digitalRead(int pin);

...but this doesn't explain how use both the IDE and a makefile.
Update 2
I recently found PlatformIO which doesn't answer this question directly, but does automate a lot of the process (generates Scons files for you) and so far I prefer the workflow over both the Arduino IDE and the source+makefile approach.  Good support from the authors as well.

Thus question is way beyond my knowledge, but some things you'd have to consider is the include of the Arduino.h file. Incorporating the bootloader; and whatever else. I'll be following this question :)

I'd suggest you take a look at Arduino-CMake (https://github.com/queezythegreat/arduino-cmake).

http://inotool.org/

You can't write a "program" that is considered valid by both the IDE and G++ directly unless you're willing to make a number of sacrifices. Deal with Ino.

Found my answer here, in the comments of the attached makefile.

By gcc/g++ I think you're referring specifically to avr-gcc/avr-g++.  Your arduino code probably won't be considered valid C/C++ code because gcc will try to compile with your PC as the target system. Many of the Macros in "WProgram.h" will refer to inaccessible memory on your target system.
Providing you include the header file "WProgram.h" and you build your code with the Arduino Makefile above (which uses avr-g++ not g++), your cpp files should compile and link correctly.  Likewise, you will be able to open your Arduino code within the IDE and Verify your code there.  The IDE puts in the "WProgram.h" file for you, so technically it would be included twice.  However, the include guards will prevent any duplicate code from being compiled.

What I want to know is "how do I write a program such that it is considered valid both by the Arduino IDE and g++.

See: How to avoid the quirks of the IDE sketch file pre-preprocessing.
Disregarding for the moment what the Makefile will look like, the simple answer to your question, as discussed in the above link, is to put everything into .cpp and .h tabs in the IDE, and leave the main "sketch" (.ino file) blank. That will still compile under the IDE, and will also therefore be normal C++.
Make sure you start your .cpp files with:
#include <Arduino.h>

If you use libraries (eg, SPI) you must include them in the main sketch file, which triggers the IDE to copy them into the temporary project build file. The Makefile won't care about that, as you will make sure your Makefile includes all the necessary library files.
Also see my answer here: Classes and objects: how many and which file types do I actually need to use them?

source: Stack Exchange

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

sort: votes


text:
Bitmap only displays correctly with PROGMEM keyword
I have a bitmap to draw defined as below.

PROGMEM const unsigned char ship1 [] = {0x18, 0x3C, 0x7E, 0xFF, 0x81, 0xC3};

It is then used by the arduboy library's draw slow bitmap function like so:
arduboy.drawSlowXYBitmap(5,5, ship1, 8 , 6, WHITE);

Can anyone explain to me why the bitmap only draws correctly with the PROGMEM keyword? I omitted it at first and it causes the bitmap to look completely different.
I see that this keyword makes the data get written to flash instead of SRAM.
The hardware I am using is the Arduboy.
The arduboy.drawSlowXYBitmap() function is from https://github.com/Arduboy/Arduboy
void Arduboy::drawSlowXYBitmap
(int16_t x, int16_t y, const uint8_t *bitmap, uint8_t w, uint8_t h, uint8_t color)
{
  // no need to dar at all of we're offscreen
  if (x+w < 0 || x > WIDTH-1 || y+h < 0 || y > HEIGHT-1)
    return;

  int16_t xi, yi, byteWidth = (w + 7) / 8;
  for(yi = 0; yi < h; yi++) {
    for(xi = 0; xi < w; xi++ ) {
      if(pgm_read_byte(bitmap + yi * byteWidth + xi / 8) & (128 >> (xi & 7))) {
        drawPixel(x + xi, y + yi, color);
      }
    }
  }
}

Imagine two programs identical apart from the PROGMEM keyword. The program only contains the lines mentioned above and the relevant calls to refresh the display. What I want an explanation of is why I get a garbled image without it and a fine image with it.

It depends on the application code (which you didn't give us!). If the code uses pgm_read_byte to read from the pointer, it will read from program memory (flash). Else, from RAM. If you change a variable's storage from PROGMEM to RAM but don't adapt the code, errors like yours happen (reading from the wrong mem addr).

@MaximilianGerhardt I have added the only other relevant line in the code but this is a library call so I will have to find the source code. In both cases the variable is a const the only difference was the Progmem keyword.

I was right on the money: https://github.com/Arduboy/Arduboy/blob/master/src/Arduboy.cpp#L630

@MaximilianGerhardt Ok that makes sense and it clearly works fine with the progmem keyword but could you explain why this happens then when the only change is whether the code is built with the keyword or not.

Because without the PROGMEM keyword your doesn't put the data in the same place that the library is going to look for it.  You put it in SRAM and the library is looking at the same address in flash.  Imagine sending a letter to the right street address but with the wrong city and zip.

@Delta_G Perfect that answers it. The function looks in flash and not SRAM. Max said it looked in flash first before looking in SRAM which confused me.

The point I wanted to make was that if it does pgm_read_byte( somePointer ) then it will read from flash, else, meaning "direct dereference" using *somePointer or somePointer[i] will load from RAM.

@MaximilianGerhardt Ok that makes sense.If you put your comments in an answer I will mark it as the answer. Thanks.

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


text:
AnalogWrite problem
I have connected DRV8835 with 2 DC motors with 11 power supply. Arduino nano.
When I for loop like i from 0 to 1024 for analogWrite(i,Motor1) for the DC Motor1 it's accelerating from 0 to 200 and it's stopping. When I becomes 250 it's starting at higher speed. When it becomes 500 it's stopping again. And 550 we have our power again.
Now I tried to run analogWrite(1000, ***) but it's not working. When I change the value from 1000 to 1005 it's not working again. But at 1024 we have the maximum speed and it is working?

 #define LEFT_PWM 9
 #define RIGHT_PWM 10
 #define LEFT_DIR 5
 #define RIGHT_DIR 6

void setup() {
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
}

void loop() {
  digitalWrite(LEFT_DIR, HIGH);
  analogWrite(LEFT_PWM, 1000);
}

analogWrite has the following prototype
void analogWrite(uint8_t, int);

which means that its first parameter has [0, 256) range and follows the rules of modulo arithmetic, with 256 as the modulo. If you supply arguments outside of [0, 256) range, they will be interpreted % 256. 1000 is the same as 232 (1000 % 256 == 232), 500 is the same as 244, 550 is the same as 38 and so on.
This is not fully consistent with the symptoms you describe (if your description is accurate), which might imply that something else is a factor here. Are sure you are using your DRV8835 in PHASE/ENABLE mode (pin 11 pulled high)?

The pin MOD was the real problem. Soldered it to VCC with a wire and problem is solved. Before that the motors behavior was very random.

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


text:
Arduino UNO(master read) + NANO(slave write) i2c buttons+stepper
First of all, I'm new to arduino. Check the EDIT line below the two codes.
I have connected motor shield to arduino uno. Connection between the two arduinos are A5 to A5, A4 to A4, 5V to 5V and GND to GND. I have a stepper connected to UNO, and a button connected to nano.
EDIT5: I deleted the messy previous codes, the question was answered.
However, I cant get the steppers to rotate(they only vibrate). Any advice is appreciated. The code right now is:
Master
#include <Wire.h>
#include <AFMotor.h>
//define steppers
AF_Stepper motor1(48, 1);
AF_Stepper motor2(48, 2);

//define variables
int x = 0;
int y = 0;

void setup()
{
  Wire.begin(5); //begin i2c communication
  Wire.onReceive(receiveEvent);
  motor1.setSpeed(10);  // 10 rpm
  motor2.setSpeed(10);  // 10 rpm

  motor1.release();
  motor2.release();
  delay(1000);
}

void loop()
{
  delay(500); // wait 0.5 second
}

void receiveEvent(int howMany)
{
    //read x,y from slave
    x = Wire.read();
    y = Wire.read();

    if (x == 1) //stepper1 rotate forward
    {
      motor1.step(100, FORWARD, SINGLE);
    }
    else if (x == 2) //stepper1 rotate backward
    {
      motor1.step(100, BACKWARD, SINGLE);
    }
     else if (y == 1) //stepper2 rotate forward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
     else if (y == 2) //stepper2 rotate backward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
}

Slave
#include <Wire.h>

//define buttons
const int button1 = 2;
const int button2 = 3;
const int button3 = 4;
const int button4 = 5;

//define state of buttons
int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;

//define variables
int x = 0;
int y = 0;

void setup()
{
   //start i2c communication
   Wire.begin();
}

void loop()
{
  //read state of buttons
  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  buttonState3 = digitalRead(button3);
  buttonState4 = digitalRead(button4);

    //if button1 is pressed,send x to master
    if(buttonState1 == HIGH){
      x = 1;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button2 is pressed,send x to master
    else if(buttonState2 == HIGH)
    {
      x = 2;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button3 is pressed,send y to master
    if(buttonState3 == HIGH){
      y = 1;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
    //if button4 is pressed,send y to master
    else if(buttonState4 == HIGH)
    {
      y = 2;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
}

slave uses onReceive. your "Slave" code is master code

@Juraj Yeah, I realised it. Don't you know how is it possible to make it work ?

@RóbertPollák What did you realise? If you realised, can't you fix it? In any case Arduino has a tutorial for when you want to transfer data from the slave to the master

@frarugi87 That tutorial is great, I followed the steps and worked. However, the problem was when I wanted to create what I wrote above. Button to control the stepper.

Well, instead of sending "hello" you have to send the button status. From the other part, instead of printing it you have to use it properly. Try modifying first the servo to send you '0' or '1' and the master prints it on the serial, then when it works modify the master to interprete it as a command. If you have problems (but I think you won't, since you already did it) you can ask showing what you did in the meantime

I see a lot of bugs everywhere, but I am totally confused which code that you are going to use. First decide which Arduino board should be the master and which one the slave. A master can send data to a slave or request data from a slave.

@Jot I was told not to delete the previous codes, so I just make an edit. My uno is the master reader, nano is the slave writer. I think I almost figured it out, I'm just stuck at a point, where if I write a char I predefined, the stepper turns on, but I can't make it run with the button.

About "edit 3", the slave at address 8 and the master polls the slave via i2c. That is okay. The master can request two bytes and read two bytes (for example as HIGH or LOW) and omit the Wire.available. The slave should always write two bytes, just write 'buttonState1' and 'buttonState2'. No if-statement needed.

I have an important question: are you using an extra Arduino board because there are not enough pins available for two buttons? Please don't do that. First of all, you should buy a better driver board. Second, all the analog pins of the Arduino board are digital pins as well. If you have no servo motor connected to the shield, pin 9 and 10 can be used as well. There is also pin 2 and 13 which are not used. That means with that shield you have still 10 pins for buttons! (or 8 when using  two servo motors).

@Jot is there a way we can send DMs instead of commenting? It would make this thing faster.
Anyways, yes I use another board because not only there are not enough pins for the buttons, but I want to add bluetooth module.

There is a chat (never used it), but so far this is all about Arduino and meaningful.

Could we somehow set up that chat?
I couldn't figure it out how to set up the buttons with analog pins. My code is there, I updated my code, could you help me with that, so I wouldn't need to use I2C so far.

To use an analog pin as a digital pin, use the name of the pin: pinMode(A0, INPUT), digitalRead(A0), and so on. Or in your sketch, for example: const int button4 = A0; You are receiving two bytes via i2c, so you must send two bytes. If that is not what you want, then you have to forgot about programming code and first define the data that will be transmitted via i2c. Describe the protocol of the data. I'm kind of lost, since you are trying many things without a direction to go to. Don't forget to use @Jot, or else I won't be notified.

By the way, how you know which motor shield do I have? I use two steppers so I might be able to do that without i2c, but I want to use bluetooth module to control the steppers wirelessly. @Jot

A little guessing and the "AFMotor.h" give it away. The newer Adafruit Motor Shield uses a different name, so this must be the old one. If you are planning to use SoftwareSerial together with i2c, then you get into new problems. The i2c needs interrupts to run smooth, and the SoftwareSerial takes over the Arduino to do its work.

Well, I've got this one. Could I use any newer library? I just want to connect a bluetooth module(dont know which one yet) to nano(slave) to control the steppers. By the way, the 9V battery wasn't new, I'm going to buy one right now, I'll be back soon and tell you if that was the problem. @Jot

@Jot The new battery still won't rotate just vibrate. I guess the problem would be somewhere else I can't locate.

The thing is, its rotating without i2c, but only vibrates with. @Jot

A 9V battery is for smoke detectors, you can not use it with an Arduino board and certainly not for motors. That old motor driver needs that old library, and the new motor driver module has its own library. The bluetooth works best with a hardware serial port. You are running so fast into every possible problem, is there someone who can help you at your place?

@Jot not really that's the problem. Why is this a thing that without i2c its working correctly, with i2c, its not. That's why I wanted to get into chat with you somehow if you have time for that.

You might request to delete this question and start a new one. Tell what your goal is and ask how to achieve that, and tell what hardware you already have. This website is for questions and answers, perhaps forum.arduino.cc is a better place.

That's what I'm going to do! @Jot thanks everything once again!

There are many ways to do this. The master could be the central unit which makes all the decisions, or the slave could preprocess the information.
It is best to start with a single byte to make it work. But I have made examples for two bytes anyway.
The next examples requests two buttons via i2c. You can change the HIGH and LOW into an integer value, but this is a start to make it work.
Master (without checking)
void loop()
{
  Wire.requestFrom(8,2);    // request 2 bytes from slave device #8
  int button1 = Wire.read();
  int button2 = Wire.read();

  Serial.print("button1=");
  Serial.println(button1 == HIGH ? "HIGH" : "LOW");

  Serial.print("button2=");
  Serial.println(button2 == HIGH ? "HIGH" : "LOW");

  // Some delay is needed, to prevent a 100% i2c bus load.
  // Perhaps 1 ms is enough, now 500 ms for testing.
  delay(500);
}

Master (with checking)
void loop()
{
  Wire.requestFrom(8,2);    // request 2 bytes from slave device #8
  if(Wire.available() == 2)   // are 2 bytes received ?
  {
    int button1 = Wire.read();
    int button2 = Wire.read();

    Serial.print("button1=");
    Serial.println(button1 == HIGH ? "HIGH" : "LOW");

    Serial.print("button2=");
    Serial.println(button2 == HIGH ? "HIGH" : "LOW");
  }
  else
  {
    Serial.println("The slave was not found");
  }

  // Some delay is needed, to prevent a 100% i2c bus load.
  // Perhaps 1 ms is enough, now 500 ms for testing.
  delay(500);
}

Slave (very simple)
void requestEvent()
{
  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  Wire.write( (byte) buttonState1);
  Wire.write( (byte) buttonState2);
}

Slave (advanced, update button state in the loop)
#include <Wire.h>

const int button1Pin = 2;
const int button2Pin = 3;

// Variables that are used in a interrupt and also outside
// that interrupt must be declared as volatile.
// Then the compiler knows that they can change at any moment.
volatile byte buttonState1;
volatile byte buttonState2;

void setup()
{
  pinMode(button1Pin,INPUT);
  pinMode(button2Pin,INPUT);
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
}

void loop()
{
  // keep the variables updated with the latest information.
  buttonState1 = (byte) digitalRead(button1Pin);
  buttonState2 = (byte) digitalRead(button2Pin);
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent()
{
  // send the two bytes.
  Wire.write(buttonState1);
  Wire.write(buttonState2);
}

Avoid comments like "+1" or "thanks", but still, thank you @Jot.
Anyways, I managed to write a code that's running, but the steppers are just vibrating, not rotating. Any solution for it?

That is an other problem. Try to make a small test sketch (without using the i2c bus and the other board) to test it. It means there not enough power or the wrong driver or electrical noise that backfires into the arduino board. You know that the motor shield that you are using is the worst, cheapest, weakest motor shield there is? It can drive only a very, very, very small toy motor. Maybe not even that.

When I used it without i2c bus, only with the shield and one button(because only pin D2 is free on that shield and analog pins) it was working okay, but now, with this setup, its not working.

You could add a check in the receiveEvent if the howMany == 1. Since a single byte is expected it should be 1. Calling the motor.step from an interrupt function might cause problems. If possible, you should do such things in the Arduino loop(). Don't fill the i2c bus with 100% load. Add a delay in the master Arduino. Start at least with 100 ms. Work cleaner! with the code and explanation. You have now called the master the slave and the other way around.

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


text:
How to show one thing in the serial monitor?
I am trying to make a device which has two push buttons and one analog input. At first the serial monitor will show INITIALIZING, then it will show ready to begin if the measured pin is pressed. Then only it will start to measure if again pressed, then it will show ****************************** and if the reset pin is pressed, it will show reset. If again pressed then ------------------------
but the problem is, it is showing
*************
(analog value) at the same time.
This is my code.
int sensor = A0;
int A = 0;
int resetPin = 3;
int measurePin = 2;
int resetstatus = 0;
int measurestatus = 0;
boolean flag1 = true;
boolean flag2 = true;
long current = 0;

void setup() {
    Serial.begin (9600);
    pinMode (sensor, INPUT);
    pinMode (resetPin, INPUT_PULLUP);
    pinMode (measurePin, INPUT_PULLUP);
    current = millis ();
}

void loop() {
    while (current < 3000) {
        Serial.println ("INITIALIZING");
        current = millis ();
        delay (200);
    }
    Serial.println ("Ready to begin");
    delay (200);
    resetstatus = digitalRead (resetPin);
    measurestatus = digitalRead (measurePin);
    if (resetstatus == LOW) {
        flag1 = !flag1;
        delay (50);
    }
    if (flag1 == HIGH)  {
        delay (50);
        reset ();
    }
    if (flag1 == LOW) {
        Serial.println ("------------------------------------");
    }
    delay (100);
    if (measurestatus == LOW) {
        flag2 = !flag2;
        delay (50);
    }
    if (flag2 == HIGH) {
        delay (50);
        measure ();
    }
    if (flag2 == LOW) {
        Serial.println ("***********************************");
        digitalWrite (13, LOW);
    }
    delay (100);
}

void measure() {
    A = analogRead (sensor);
    Serial.println (A);
    digitalWrite (13, HIGH);
}

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

The while statement with millis() is used uncorrectly here. 'current < 3000can only be true within the first 3s after the power up, (and also everytime 'millis()' overflows). If you only want to have it executed one time you should write itsetup(). Also: What do you mean by at the same time`?

change your pin declarations to #define sensor A0  ect....   there is no reason to have them be variables.  the variable current should be an unsigned long, not just a long.   Also no need to use millis() for your init portion.   In your setup loop you can just do Serial.println("Init"); delay(3000);

Still not sure what your problem is.   Can you post the output

@chrisl i wanted the INITIALIZATION to be showed only for 3secs when the power is turned on

@ChadG i want to observe only analog value when the measured button is pressed and reset to be shown when the reset button is pressed

Then, as Chad and me said, it's better to move this to setup() (as this function is made for one-time initialization) and use a simple delay(). When you are not doing anything during that time (as your sketch already does) this is better to understand

and what is it doing? Please give a little better description of user action and output

You have declare flag1 and flag2 as Boolean values but then you are looking to see if they are HIGH or LOW.  Bools are either true or false.  However because of the quirks of C++ this will probably work, if High and low are 1 and 0, its just bad style.
When you have this bit of code:
if (flag2 == HIGH)
{
    delay (50);
    measure ();
}
if (flag2 == LOW)
{
    Serial.println ("***********************************");
    digitalWrite (13, LOW);
}

You could use an else statement instead, i.e.
if (flag2 == true) // Corrected to true
{
    delay (50);
    measure ();
}
else
{
    Serial.println ("***********************************");
    digitalWrite (13, LOW);
}


text:
Give zero volt to specific servo motors in a certain time
I have a robot that uses 4 mechanical arms. Each mechanical arm has 4 "READYTOSKY 30kg" servo motors on them.
At some point, I need to use the absolute maximum force of only two mechanical arms (while the other two will stay still). Even though I do not change the coordinates of the other two mechanical arms (which I am not using),they consume voltage and "take away" the full potential of force from the other two.
Is there a way to stop the voltage consumed by the two other arms just for a brief moment using Arduino code? Shortly afterwards they will get back the voltage they need.
    if(level==25)
      {
        pwm.setPWM(12, 0, 200);
        pwm.setPWM(13, 0, 255);
        pwm.setPWM(14, 0, 430);
        delay(100);
        pwm.setPWM(1, 0, 380);
        pwm.setPWM(2, 0, 520);
        delay(500);
        pwm.setPWM(0, 0, 170);
        delay(600);
        stepperten.setCurrentPosition(0);
        while (stepperten.currentPosition() != (-3*200))
        {
        stepperten.setSpeed(-600);
        stepperten.runSpeed();
        }
        steppertwist.setCurrentPosition(0);
        while (steppertwist.currentPosition() != (100))
        {
          steppertwist.setSpeed(200);
          steppertwist.run();
        }
        stepper1.setCurrentPosition(0);
        while(stepper1.currentPosition() != (30))
        {
          stepper1.setSpeed(200);
          stepper1.run();
        }

        pwm.setPWM(1, 0, 295); //THIS IS THE MOMENT I NEED TO STOP VOLTAGE FOR OTHER ARMS
        pwm.setPWM(2, 0, 400); //AND GET THE MAXIMUM VOLTAGE POSSIBLE ON THESE TWO ARMS
        delay(1500);
        pwm.setPWM(12, 0, 125);

        array1[25][0] = 170;
        array1[25][1] = 295;
        array1[25][2] = 400;
        array1[25][3] = 153;
        array4[25][0] = 125;
        array4[25][1] = 255;
        array4[25][2] = 395;
      }

You mean they consume current? Cutting the other servos power would also mean, that they are not able to hold their position against outside forces (like gravity). Would that be a problem? You can control the power lines of a servo with a p-channel MOSFET

Did you try to detach() the servo, then attach() it again later?

chatgpt told me to use detach and attach. I thought it might not work during a code

I thought about getting a bigger trasformatore. The one I am currently using is 6.5[v] w/ 2.5[A]. The servo can get 4.8-7.2[V]. What is the optimal current I need for better results? The model is "readytosky td-8130mg". Thanks!

If you want to keep the maximum flexibility, then add together all the stall currents of your servos. If you google for the TD-8130mg datasheet 2.1A for 4.8V and 2.7A for 7.2V. So you will have stall current of about 2.6A. Make sure, that your power source can accommodate your maximum current.

If you want to turn off power for some external parts you could try to power them via the digital pins. See this example code:
void setup(){
   pinMode(YOUR_ARM_POWER_SUPPLY_PIN, OUTPUT);

   // switch arm on
   digitalWrite(YOUR_ARM_POWER_SUPPLY_PIN, ON);
}

void loop(){
  if(armMustNotUseAnyPower()){
      // switch arm off
      digitalWrite(YOUR_ARM_POWER_SUPPLY_PIN, OFF);
  }

}

Keep in mind that the digital Pins cannot output as much power as VCC. But since you drive some servo motors over it I assume they get their power externally anyway. You might need to add some transistor or another way on how to switch the power on and off from the big power source. Hope this helps you in some way.


text:
Code for two bulb fading alternatively
I have written this code
const int A = 3;
const int B = 5;
void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);

}

void loop() {
  for(int i=1;i<=255;i++)
  {
    int j =255-i;
    analogWrite(A,i);
    analogWrite(B,j);
    delay(100);
  }
  for(int i=255;i>0;i--)
  {
    int j =255-i;
    analogWrite(B,j);
    analogWrite(A,i);
    delay(100);
  }
}

Is  this code correct? If yes then can it be modified in any way to make it better?

Other than a little asymmetry, I don't think I see a problem (i goes from 1 to 255 while j goes from 0 to 254).  Why?  Is it not working?

The pins you picked should work on most Arduino boards.  But when asking these types of question you should list what Arduino board type you are using.

Define "better". Your code uses delay, which is OK if your code has nothing else to do, but completely unacceptable if your code will be used in context of other code. Is this something that you want/need to make "better" or not?

Depending on what effect you want to achieve, you might want to add gamma-correction.

To keep the two loops more symmetrical, let the first loop go from 0 until 254: [0 .. 255) and the second loop from 255 to 1: [255 .. 0), so both iterations have 255 values each.
Also, it is quite common in programming to include the start element, and not include the end element (as in the values above: [start_element .. end_element).
Also, for the simple formula (255 - i), I would leave out the formula. And to make things more clear define constants for the min/max values (0,255) and the delay.
Than you get:
const int A = 3;
const int B = 5;

const int MIN_INTENSITY = 0;
const int MAX_INTENSITY = 255;
const int DELAY_TIME    = 100;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
}

void loop()
{
  for(int i = MIN_INTENSITY; i < MAX_INTENSITY ; i++)
  {
    analogWrite(A, i);
    analogWrite(B, MAX_INTENSITY - i);
    delay(DELAY_TIME);
  }

  for(int i = MAX_INTENSITY ; i > MIN_INTENSITY; i--)
  {
    analogWrite(B, MAX_INTENSITY - i);
    analogWrite(A, i);
    delay(DELAY_TIME);
  }
}

By making a function and use arguments for the variable values, and create some better names for constants and variables you get this:
const int LED_1_PIN     =   3;
const int LED_2_PIN     =   5;

const int MIN_INTENSITY =   0;
const int MAX_INTENSITY = 255;
const int DELAY_TIME    = 100;

void setup()
{
  pinMode(LED_1_PIN, OUTPUT);
  pinMode(LED_2_PIN, OUTPUT);
}

void loop()
{
  fade(MIN_INTENSITY, MAX_INTENSITY,  1);
  fade(MAX_INTENSITY, MIN_INTENSITY, -1);
}

void fade(int startIntensity, int endIntensity, int stepValue)
{
  for(int intensity = startIntensity; intensity < endIntensity; intensity += stepValue)
  {
    analogWrite(LED_1_PIN, intensity);
    analogWrite(LED_2_PIN, MAX_INTENSITY - intensity);
    delay(DELAY_TIME);
  }
}


text:
Print the response from GSM shield
I have a GSM shield connected with my Intel Galileo board.
I intend to connect the board with serial communication at a baud rate of 115200 instead of the GSM library. I want to print the results of "at" commands in my serial window, how should I do it?

Send the commands, read the responses, print the responses. What's so tricky about that?

well can u kindly give the syntax for printing those responses ?? plzz

https://www.arduino.cc/en/Reference/Serial

I have only worked with the SIMCOM series of GSM modules like the SIM900 and the SIM808. Here is a sample of the kind of code you should be looking at using.
It will send one "AT" to the GSM module and then it will spit out the result in the serial monitor.
void setup()
{
  Serial.begin(115200);
  int bytesSent = Serial.write(“AT\r\n”); //send "AT" and send the end of line characters to signify end of the command
 }

 void loop()
{
   if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();
    }
}

This seems a bit confused and probably unworkable - the Serial Monitor and the GSM module are both serial-interfaced devices (or at least appear to be so in the Arduino world), but you only use a single serial interface and seem to somehow imagine that it is independently connected to both of them.

I copied the normal serial command and left in the echo by mistake. Thanks for pointing that out.

Now it produces no output and so does not achieve the goal of the question.  The question requires two serial ports.


text:
Interfacing MPU6050 with Arduino through Simulink S-function
I am interfacing MPU6050 with Arduino using Simulink S-function builder.
I'm implementing MPU6050_DMP6 code in Simulink s-function builder by following this video. By following this tutorial I implemented the S-function as:
I set sample time 0.05 in s-function builder block and number of discrete state=1 and sample mode = 1.
in the libraries tab I put the following code:

#include <math.h>
#ifndef MATLAB_MEX_FILE
int counter=0;
#include <Arduino.h>
#include "I2Cdev.h"
#include "I2Cdev.cpp"

#include "helper_3dmath.h"
#include "MPU6050_6Axis_MotionApps20.h"
#include "MPU6050.h" // not necessary if using MotionApps include file
#include "MPU6050.cpp" // not necessary if using MotionApps include file
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
    #include "Wire.cpp"
    #include "utility/twi.h"
    #include "utility/twi.c"
#endif
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;

#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT

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

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

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

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

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}
#endif

in the discrete update tab I have implemented following code:
if (xD[0]!=1){
#ifndef MATLAB_MEX_FILE
       // join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial2.begin(115200);
//     while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
    // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

    // initialize device
    Serial2.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);
    // verify connection
    Serial2.println(F("Testing device connections..."));
    Serial2.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
   // Serial2.println(F("\nSend any character to begin DMP programming and demo: "));
   // while (Serial2.available() && Serial2.read()); // empty buffer
   // while (!Serial2.available());                 // wait for data
   // while (Serial2.available() && Serial2.read()); // empty buffer again

    // load and configure the DMP
    Serial2.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial2.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);
        // enable Arduino interrupt detection
        Serial2.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial2.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

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

  xD[0]=1;
 }

and in output tab I have implemented this code:
if (xD[0]==1){
    #ifndef MATLAB_MEX_FILE
// if programming failed, don't try to do anything
    if (!dmpReady) {
        return;
    }

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
        // .
        // .
        // .
        // if you are really paranoid you can frequently test in between other
        // stuff to see if mpuInterrupt is true, and if so, "break;" from the
        // while() loop to immediately process the MPU data
        // .
        // .
        // .
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();
    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

#ifdef OUTPUT_READABLE_QUATERNION
        // display quaternion values in easy matrix form: w x y z
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        // Serial.print("quat\t");
        // Serial.print(q.w);
        // Serial.print("\t");
        // Serial.print(q.x);
        // Serial.print("\t");
        // Serial.print(q.y);
        // Serial.print("\t");
        // Serial.println(q.z);
#endif

#ifdef OUTPUT_READABLE_EULER
        // display Euler angles in degrees
//         mpu.dmpGetQuaternion(&q, fifoBuffer);
//         mpu.dmpGetEuler(euler, &q);
//         Serial.print("euler\t");
//         Serial.print(euler[0] * 180/M_PI);
//         Serial.print("\t");
//         Serial.print(euler[1] * 180/M_PI);
//         Serial.print("\t");
//         Serial.println(euler[2] * 180/M_PI);
#endif

#ifdef OUTPUT_READABLE_YAWPITCHROLL
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        *roll = ypr[0] * 180/M_PI;
        *pitch = ypr[1] * 180/M_PI;
        *yaw = ypr[2] * 180/M_PI;
        Serial2.print("ypr\t");
        Serial2.print(ypr[0] * 180/M_PI);
        Serial2.print("\t");
        Serial2.print(ypr[1] * 180/M_PI);
        Serial2.print("\t");
        Serial2.println(ypr[2] * 180/M_PI);
#endif

#ifdef OUTPUT_READABLE_REALACCEL
        // display real acceleration, adjusted to remove gravity
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetAccel(&aa, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
        // Serial.print("areal\t");
        // Serial.print(aaReal.x);
        // Serial.print("\t");
        // Serial.print(aaReal.y);
        // Serial.print("\t");
        // Serial.println(aaReal.z);
#endif

#ifdef OUTPUT_READABLE_WORLDACCEL
        // display initial world-frame acceleration, adjusted to remove gravity
        // and rotated based on known orientation from quaternion
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetAccel(&aa, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
        mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
        // Serial.print("aworld\t");
        // Serial.print(aaWorld.x);
        // Serial.print("\t");
        // Serial.print(aaWorld.y);
        // Serial.print("\t");
        // Serial.println(aaWorld.z);
#endif

#ifdef OUTPUT_TEAPOT
        // display quaternion values in InvenSense Teapot demo format:
        teapotPacket[2] = fifoBuffer[0];
        teapotPacket[3] = fifoBuffer[1];
        teapotPacket[4] = fifoBuffer[4];
        teapotPacket[5] = fifoBuffer[5];
        teapotPacket[6] = fifoBuffer[8];
        teapotPacket[7] = fifoBuffer[9];
        teapotPacket[8] = fifoBuffer[12];
        teapotPacket[9] = fifoBuffer[13];
        Serial.write(teapotPacket, 14);
        teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
#endif

        // blink LED to indicate activity
        // blinkState = !blinkState;
        // digitalWrite(LED_PIN, blinkState);
    }

#endif
}

The solver I'm using is fixed-step discrete solver.
I build the S-function and then the model successfully. When I run the simulation in the external mode using Arduino mega there are jump and glitches in the output raw, pitch and roll angles as shown in the
However, when I plotted the same code through Arduino IDE and monitor data on serial plotter there is no glitches and jumps in angles.
I have also change the baud rate to 115200, solver to auto and sample time of s-function but the problem remain to persist.
Any help would be appreciated!
Thanks in advance!

Measurement sometime lost due to serial communications between Arduino and Simulink. So raw data have some glitches in output values. In order to solve the issue, we have to use state estimation to solve this problem.

Could you please expand on your answer as it does not meet the quality standards for this site. Please see How to write a good answer for Arduino Stack Exchange

To add to the answer above, you are limited by the serial speed of the USB, i.e. USB 2.0 is around 12 Mbps, as well as what your hardware can manage. Also, Simulink uses about 25% of each time step simply for maintaining communication and it is unclear how bandwidth is used by this.
A simple rule of thumb is to work out how much data you are trying to log and at what frequency as this should give you an idea if you are trying to log too much and hence Simulink won't catch all the data and you end up with the blip you have in the scope.
For context, I have been making a wheel speed calculation algorithm and was losing data simply because it wasn't possible to log the volume of data I wanted at high frequency (i.e. 5000 Hz). If you think about logging 3 int8 values at 5000 Hz you are talking 120 kkps, this should give some idea as to how this can get out of control with more signals or larger data types like double.

Yes, this problem exists and may be in even higher data rate. I think the efficient way is to tackle this problem in the Simulink model as I mentioned using state estimation may using Kalman filter in that way we got very reliable results.


text:
Arduino GY273 HMC5883L Constant Value
I have a GY-273 which has HMC5883L chip (I guess). I am trying to get data. I find a few codes and library (I don't have enough information about HMC5883L) but always all serial port screen there are only one value.
Here is my sketch:

#include <Wire.h>
#include "compass.h"

#define Task_t 10          // Task Time in milli seconds

int dt=0;
unsigned long t;
// Main code -----------------------------------------------------------------
void setup(){
  Serial.begin(9600);
  // Serial.print("Setting up I2C ........\n");
  Wire.begin();
  compass_x_offset = -48.23;  //122.17;
  compass_y_offset = 284.69;  //230.08;
  compass_z_offset = 59.87;  //389.85;
  compass_x_gainError = 1.07;  //1.12;
  compass_y_gainError = 1.09;  //1.13;
  compass_z_gainError = 1.01;  //1.03;

  compass_init(2);
  //compass_debug = 1;
  //compass_offset_calibration(3);

}

void loop(){

  t = millis();

  float load;

  compass_scalled_reading();

  Serial.print("x = ");
  Serial.println(compass_x_scalled);
  Serial.print("y = ");
  Serial.println(compass_y_scalled);
  Serial.print("z = ");
  Serial.println(compass_z_scalled);

  compass_heading();
  Serial.print ("Heading angle = ");
  Serial.print (bearing);
  Serial.println(" Degree");

  dt = millis()-t;
  load = (float)dt/(Task_t/100);
  Serial.print ("Load on processor = ");
  Serial.print(load);
  Serial.println("%");

  delay(100);
}

And Serial port screen is:
Gain updated to  = 1.22 mG/bit
x = -48.23
y = 284.69
z = 59.87
Heading angle = 99.62 Degree
Load on processor = inf%
x = -48.23
y = 284.69
z = 59.87
Heading angle = 99.62 Degree
Load on processor = inf%
x = -48.23
y = 284.69
z = 59.87
Heading angle = 99.62 Degree
Load on processor = inf%
x = -48.23
y = 284.69
z = 59.87

simulate this circuit – Schematic created using CircuitLab

@LookAlterno This value is always the same. No change.

@LookAlterno Actually I didn't understand what is the problem. It is my first test. I'm not sure problem is code or module (or as I have just learned, continuous mode etc.). I'm asking what the problem is.

Those values are written in the setup function to the variables. You never get anything from the sensor. Run the i2c scanner to find the i2c address https://playground.arduino.cc/Main/I2cScanner . There are also clone sensors (QMC5883). What is "compass.h" ? Is that a library ? Did you write "compass.h" yourself ? The Arduino Nano runs at 5V, but the HMC5883L is a 3.3V sensor. It can get damaged when you connect sda and scl to the Arduino Nano without i2c level shifter.

@Jot Yes, compass.h is a library which is I find on the net. I have tried i2cscanner. It said I2C device found at address 0x0D. GY-271 3.3V but GY-273 3.3-5V as I saw on the net. compass.h is here

I think there are 4k7 pullup resistors on the module from sda to 3.3V and from scl to 3.3V. Therefor you can connect the module to an Arduino Uno without i2c level shifter. The address 0x0D is the QMC5883 (fake HMC5883L). There is a library for it: https://github.com/mechasolution/Mecha_QMC5883L but please don't use it. Get a real HMC5883L. Perhaps if you change the library (the compass_address to 0x0D in compass.cpp) and perhaps some of the fake sensor will work, although I read that the QMC5883 is not compatible with the HMC5883L.

@Jot I supposed it's HMC5883l. It works with the library which you gived thank you. I have changed the address but it didn't work.


text:
DFPlayer Noise: Researched, Tried, and Bep Bep Bep Bep Bep
Spent an entire day researching and attempting to fix the DFPlayer noise problem. The amp works as expected, so it is not the problem. I have made a video to help you better understand the sound produced: https://www.youtube.com/watch?v=uK2kkR0XjFs&feature=youtu.be
This is the amp/speaker used: https://sites.google.com/site/wayneholder/chiptunes

The amp with speaker works as expected using another similar mp3 player like from a computer or possibly a phone.

Here we get the bep bep bep bep bep... as the amp/speaker has its own battery power.

Here I made everything as one power source. Bep bep bep bep bep...
I think I exhausted my research and made the following attempts:
> -Electrolytic Capacitor at the power terminals
> -Electrolytic Capacitor parallel with ceramic capacitor from negative terminal to VCC in DFPlayer
> -Diode from positive terminal to VCC in DFPlayer
> -Battery Power source; USB power source; Power Supply power source; 5V USB plug regulator power source
> -1k Resistor from TX RX; Rx Tx
> -1-10k resistor from Rx Tx
> -1k between channel to GND
> -Separate power source for each the Arduino, amp, and DFPlayer
> -Tried multiple DFPlayers

Keep note that the amp/speaker works well. The files are the same both on the computer and in the SD card.
Here is my code:

#include <DFRobotDFPlayerMini.h>

/***************************************************
DFPlayer - A Mini MP3 Player For Arduino
 <https://www.dfrobot.com/index.php?route=product/product&product_id=1121>

 ***************************************************
 This example shows the basic function of library for DFPlayer.

 Created 2016-12-07
 By [Angelo qiao](Angelo.qiao@dfrobot.com)

 GNU Lesser General Public License.
 See <http://www.gnu.org/licenses/> for details.
 All above must be included in any redistribution
 ****************************************************/

/***********Notice and Trouble shooting***************
 1.Connection and Diagram can be found here
 <https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299#Connection_Diagram>
 2.This code is tested on Arduino Uno, Leonardo, Mega boards.
 ****************************************************/

#include <Arduino.h>
#include <SoftwareSerial.h>
#include <DFRobotDFPlayerMini.h>
int counter = 0;
SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

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

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(15);  //Set volume value. From 0 to 30
  delay(1000);
myDFPlayer.enableDAC();  //Enable On-chip DAC
}

void loop()
{
  static unsigned long timer = millis();
  if(millis() - timer > 1000 && counter == 0)
  {
   myDFPlayer.play(1);
   Serial.println(F("Music Started"));
   delay(1000);
   Serial.println(F("1 second later..."));
   delay(6000);
   Serial.println(F("7 seconds later..."));
   delay(1000);
   counter =1;
  }

delay(7000);

  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }
}

void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
}

Comments are not for extended discussion; this conversation has been moved to chat.

The "bep bep bep" you are hearing is power supply noise introduced by the SD card. Every time the SD card reads the power supply dips and the ground raises.  This is because these boards have really terrible grounding in their design. There is no coherent ground plane, and the analog audio sections and noisy digital sections both share the same ground with no isolation or filtering between them.
To reduce the impedance of the ground plane you must connect both the GND pins together, and do it with a short wire.  Better would be to modify the board itself and solder a wire directly between the two ground pins.
There are also strategic ground points around the place you could also solder directly to one of those ground pins - such as the ground side of the SD card's decoupling capacitors, and the GND pin of the SD card itself (if your soldering skills are up to it - those pins are pretty fine pitch).
The whole issue stems from trying to fit too much into too small a space. The board really should have been made as a 4-layer board with a (near) solid ground and power plane to reduce the power impedance. Better decoupling and filtering on the SD card's power pin (such as a "PI" filter with two capacitors and a ferrite bead, or two capacitors and a small resistor) would have been a big benefit as well.

Today I had similar issues. Sometimes it used to play correctly for around 10 seconds and then noise used to come. Finally reduced the length of the Rx wire and it worked. How communication wire length can cause this noise? Communication may not happen if at all there are such problems I thought. But communication does happen correctly, but after that the problem starts.

Thanks for all the investigative work.
Throwing in my 2 cents :
I was also experiencing random cutoffs and wierd noises.
I was using the Servo class in combination with the DFPlayer on an Arduino UNO board.
It turns our that the Servo class uses the timers that are related to pin 9 and 10. When attaching a servo, signals will be outputted on those ports.
So don't hook up your DFPlayer or anything else on those ports.
Probably because the Servo class was sending all kinds of data over the serial connection to the DFPlayer, the module would stop playing and start making a lot of random noise for the remaining duration of the mp3.
Other things that I came across and might help other people :
The DFPlayer needs MP3's of a certain length. MP3's of just 1~2 seconds don't play. +5 seconds seems to be fine.
Any fancy MP3 encoding also prevents the MP3s from playing.
The led will light up but no sound will be outputted.
Depending on the library used for the DFPlayer, the filenames and folder names do matter. The mp3's have to be in the MP3 folder and be named like 0001.mp3, 0002.mp3
According to 1 of the many datasheets out there, the DFPlayer requires 3.3v levels for the RX and TX port, regardless of the operating voltage.
So do put those 1K resistors there. It won't hurt the module.
Motors and servo's do cause a lot of noise on the power source if you run the board off the 5v USB port.
Even small motors can generate spikes of +2A when turned on.
Signals from other cables and devices can also interfere with the serial connection so ideally use shielded wires for the TX/RX cables.
According to the SD card specs of some manufacturers, power usage for an SD card can go up to 100mA.
The module itself can produce 3W output so that would also add up to 600mA @ 5V. And add something like 150mA for the microcontroller onboard.
So even a standard 5v@500mA USB port won't have enough power to drive just the Arduino and DFPlayer in some cases.
Someone took a look at the clicks and plops on pause or power on/off :
http://work-now-dammit.blogspot.com/2016/08/dfplayer-mp3-module-power-onoff-clicks.html
Remove the 0-ohm resistor next to the 8002 amp. Connect pin 1 of the 8002 amp to the BUSY pin (16) of the module.

this is so helpful! thank you

My Problem & Solution:  I recently attempted to control the DFPlayer with an Arduino Pro Mini and also experienced loud pulsing noises during playback (along with the music file). The pulsing could be seen on a scope on one of the speaker leads. Unloading the speaker did not help, using different power supplies did not help. Also, with regard to tying the two DFPlayer GND pins together, that's not necessary on my board since they are already connected together via the metal shell of the micro SD connector.
However, I noticed that when I attempted to re-program the Mini (or even when I pressed the reset button), there was a short period of time when the pulsing stopped and the music file played as it should. In my case the problem was the data line from the Mini to the Rx pin on the DFPlayer (there was no connection to the Tx pin). I verified this by starting playback (with the pulsing noise) and then disconnecting the Rx connection. That stopped the pulsing and the music file played as expected.
The software solution was to force the transmit pin on the Mini (I'm using soft serial) to a LOW state immediately after sending the Play command. Works fine now.
Update: I had previously connected the Mini serial output directly to the DFPlayer Rx pin without a 1K limiting resistor. Now, with the resistor in place I no longer get the pulsing noise during playback and there is no longer a need to pull the control line low.

Thanks Bob.  I just ran into this same problem and adding a 1k limiting resistor in series worked a treat!

I found that noise was due to three issues,

Forgetting to ground BOTH GND pins on the DFPlayer chip
Forgetting to put 1k resistors in the Tx and Rx lines
Power fluctuations

Power is the big issue. When I powered my Arduino with a 9v 2A supply all the noise went away. Switching to USB power (5v) caused the noise to return.

I've had loads of crazy little issues like this with the dfplayer and tried lots of solutions with very inconsistent results. Sometimes a technique like extra grounding or a resistor to the tx/rx pins will work the magic and then on making another copy of the circuit, the problem is inexplicably back! Here's a important clue that I haven't seen anywhere on forums yet, so I wanted to add it into the mix. Though the dfplayer is claimed to work from 3.3V to 5V, I've found it is much better behaved at 3.3V! Running it at 5V gives me odd noise and stability problems that vanish at 3.3V. You can get very cheap and efficient 3.3V regulators that are no bother to use. Try running it at the lower voltage and see if those issues clear up!

I had the same problem. It was solved with a separate power supply to the DFPlayer. I also grounded both sides of the player but that alone was insufficient.


text:
Cannot upload to otherwise working bootloaded ATmega328P via RS232: "programmer is not responding"
I have an ATmega328P on a breadboard with the following circuitry around it:

The ISP is a Tiny AVR Programmer. The RS232 to USB converter is this thing.
Following is the test program I use:

void setup() {
    Serial.begin(28800);
    DDRC  = 0b00000001;
    PORTC = 0b00000000;
}

void loop() {
    PORTC = 0b00000001;
    delay(300);
    PORTC = 0b00000000;
    delay(300);

    int Data;
    char Text[2] = {0};
    while (true)
    {
        Data = Serial.read();
        if (Data == -1) break;
        Text[0] = 0xFF - Data;
        Serial.write(Text);
    }
}

Almost everything is working fine:

I can upload the program via ISP by holding the shift-key while pressing the upload-button in Arduino IDE.
The LED on Pin 23 (PC0) blinks.
When I press the reset button the LED stops blinking and when I release the button it starts blinking again, so resetting the chip works.
When I open a serial monitor (at 28800 baud and not the one integrated in Arduino IDE) I can send 00, 01, 02, 03, ... and I receive FF, FE, FD, FC, ... back, so the serial communication works.
I can burn the bootloader from Arduino IDE. Every time I reset the chip the LED on pin 19 blinks three times in rapid succession and then stays off.

But I can't upload the program through the serial connection once the bootloader is burned.
Arduino IDE shows the following output:
C:\Portable Program Files\arduino-1.8.5\hardware\tools\avr/bin/avrdude -CC:\Portable Program Files\arduino-1.8.5\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM6 -b115200 -D -Uflash:w:C:\Users\Niko\AppData\Local\Temp\arduino_build_706815/BlinkTest.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Portable Program Files\arduino-1.8.5\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0

(And of course the 9 other attempts follow.)
I am not sure what to do here. Maybe the baudrate is incorrect? The Arduino website says that Arduino bootloaders use 19200 baud. But executing the same command in a console but changing the -b115200 to -b19200 yields the same result. I also tried 9600.
I make sure to to reset the chip before trying to upload, though I can't really say whether I get the timing right.
Something I noticed is that The Arduino website says that "Burning the bootloader may take 15 seconds or more", but burning the bootloader takes less than a second for me. Seems unusually fast but I can't see any errors in the output.
I also find it very weird that the command executed when trying to upload via serial connection contains -carduino, which would imply that it's trying to use a programmer to upload the program. The bootloader should make that unnecessary.
Any ideas?

Your schematic does not seem to show a proper auto reset connection; manual reset is a bit tricky, though for some reason seems to work a lot better if you have verbose upload mode selected.  Also we don't know what bootloader speed you need - 38400 and 57600 are definite possibilities you don't seem to have tried.

Can you show your fuse settings please? If you have a spare Uno or similar you can use my board detector sketch to verify that.

As for the -carduino I think that just tells avrdude to use the STK500 protocol. See http://www.nongnu.org/avrdude/user-manual/avrdude_1.html

The bootloader should make that unnecessary. - not really. The bootloader is a programmer type. :) It has to use some protocol to upload the program.

really RS232? Atmega TX/RX is TTL, not RS232. https://www.sparkfun.com/tutorials/215

@ChrisStratton The automatic reset did the trick! Now it uploads fine with the 115200 baud Arduino IDE uses. Thank you very much! I'd upvote your comment, but I don't have the reputation for that. Feel free to add a full answer and I'll accept that. For completeness' sake: @NickGammon Fuse bytes are FD DE FF. And thanks for the explanation about -cardino. @Juraj Yep, that's what I meant. The name "RS232" seem to be used interchangeably most of the time anyways.


text:
Creating a webserver on a Wemos D1 mini pro
I am trying to put a web server on my Wemos D1 mini pro. I am using this example for the Arduino code:
https://github.com/wemos/Arduino_D1/blob/master/doc/esp8266wifi/server-examples.rst

#include <ESP8266WiFi.h>

const char* ssid = "GL-AR300M-ceb";
const char* password = "********";

WiFiServer server(80);

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

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");

  server.begin();
  Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());
}

// prepare a web page to be send to a client (web browser)
String prepareHtmlPage()
{
  String htmlPage =
     String("HTTP/1.1 200 OK\r\n") +
            "Content-Type: text/html\r\n" +
            "Connection: close\r\n" +  // the connection will be closed after completion of the response
            "Refresh: 5\r\n" +  // refresh the page automatically every 5 sec
            "\r\n" +
            "<!DOCTYPE HTML>" +
            "<html>" +
            "Analog input:  " + String(analogRead(A0)) +
            "</html>" +
            "\r\n";
  return htmlPage;
}

void loop()
{
  WiFiClient client = server.available();
  // wait for a client (web browser) to connect
  if (client)
  {
    Serial.println("\n[Client connected]");
    while (client.connected())
    {
      // read line by line what the client (web browser) is requesting
      if (client.available())
      {
        String line = client.readStringUntil('\r');
        Serial.print(line);
        // wait for end of client's request, that is marked with an empty line
        if (line.length() == 1 && line[0] == '\n')
        {
          client.println(prepareHtmlPage());
          break;
        }
      }
    }
    delay(1); // give the web browser time to receive the data

    // close the connection:
    client.stop();
    Serial.println("[Client disonnected]");
  }
}

It uploads fine and when I open the serial monitor get this:
Connecting to GL-AR300M-ceb . connected
Web server started, open 192.168.8.119 in a web browser
When I go to the IP address that it gives in the monitor, I only see a blank page. I also can't inspect element, so it doesn't load the HTML part I guess.
When I change the code like this:
if (client.available())
{
//        String line = client.readStringUntil('\r');
//        Serial.print(line);
//        // wait for end of client's request, that is marked with an empty line
//        if (line.length() == 1 && line[0] == '\n')
//        {
//          client.println(prepareHtmlPage());
//          break;
//        }
          client.println(prepareHtmlPage());
      }

then i see this

And when i add the break in the code like so:
client.println(prepareHtmlPage());
break;

in the code, i get the blank page again.
Does someone have an idea what the problem might be?

Why not use the far simpler ESP8266WebServer examples that come with the core?

Oh, thank you. Honestly, I didn't know about them yet! Let me try the HelloServer.

It's a far simpler interface than trying to implement HTTP from the ground up.

Yes! I got it to work! Thank you for this tip!

I'm no master. I don't believe there is ever a carriage return while requesting a web page.

you should go for the "Advanced Webserver" example provided by the ESP8266 libraries in your Arduino IDE.
The webserver is using callbacks like
server.on ( "/", handleRoot );
server.on ( "/test.svg", drawGraph );

and so on.
Then you can use these handles to give back a html page to your browser like
server.send(200, "text/plain", message);       //Response to the HTTP request

Note how the function returns an 200 http code to your browser, which is mandatory for showing up your web page!


text:
We have Arduino IDE code that needs to stop after a set number of "revolutions"
We have Arduino IDE code that oscillates a plate on a lead screw powered by stepper motor to move back and forth.
We have the lead screw move 8 mm in one direction, then 8 mm in the opposite direction, for a total displacement of 16 mm. After this movement we have a counter that will then count as 1 "revolution" essentially. After reaching a specified count that program will stop.
Currently the program continues to run indefinitely. Any help/suggestions would be appreciated.
// Include the AccelStepper library:
#include <AccelStepper.h>

// Define stepper motor connections and motor interface type.
// Motor interface type must be set to 1 when using a driver:
#define dirPin 2
#define stepPin 3
#define motorInterfaceType 1

// Create a new instance of the AccelStepper class:
AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);

void setup() {
  // Set the maximum speed and acceleration:
  stepper.setMaxSpeed(40000);
  stepper.setAcceleration(20000);
}

void loop() {
  static int counter = 0; // Initialize a counter variable and start at 0

  // Set the target position:
  stepper.moveTo(400); // is in steps. setting to default

  // Run to target position with set speed and acceleration/deceleration:
  stepper.runToPosition();

  delay(0);

  // Move back to zero:
  stepper.moveTo(0);
  stepper.runToPosition();

  delay(0); //microseconds
  counter++; //adds 1 to the counter

  if (counter >= 2) {
    return; //exit the loop
  }
}

IED means "improvised explosive device"

IED disambiguation

What is "IED"? Do you mean IDE? Or intelligent electronic device? Or Industrial Emissions Directive? Or something else?

if (counter >= 2) {
    return; //exit the loop
  }

The return statement will end the loop, but the loop function is called over and over repeatedly.  So it will just start over again.
There are a few possibilities here.  You can replace the return statement with while(1); which will lock up execution there until the board is reset.
If you don't need the loop function to repeat ever then you can simply move all of your code into the setup function as it will only run once.  Then the loop function can just be empty.
And lastly, you could add a boolean variable and put the code you want to run only sometimes under an if statement that checks that variable.  At the end of the process you set the variable to false to stop the other code from running.  This would allow you to add code later to set it back at the press of a button or something in case you wanted the option to start the process again.
bool running = true;
void loop(){
  if(running){
      // do things
  }
  if (counter >= 2){
    running = false;
  }
}

exit(0) and abort() should also work. On AVR at least they are equivalent to while(1);, while more explicit about the intent.

I thought exit(0) was broken?  Why did I think that?  Was it ever?


text:
Use attiny85 reset pin as analog pin
I want to use the reset pin of the attiny85 as an analog pin to read the battery voltage, to be used as low level battery indicator.
So there is a lipo battery that will always be connected to this pin.
I need a high-voltage programmer to do so but I read that the reset pin can be simply an analog pin if the voltage to it is above 2.5v . Is it true?
If so, I can program it with Arduino SPI normally as the battery will never go below 2.5v.
Edit
Thanks @timemage for your answer, it really has good info.
But I can verify that if you give 5v to the Vcc of the attiny and connect a lipo (above 2.5v) to the reset pin, it will work as an analog pin.
I used a potentiometer and yes it is working, you can see more info about this as well in this post.
The real info starts from Post#10.
It is really a complex situation here as what I did was using the reset pin as reset and as an analog pin at the same time. It is not recommended but it works!
Please if you can review the post in the Arduino forums and rewrite your thoughts here it will be useful for more people to get useful info.

See http://www.technoblogy.com/show?LSE

The following was in answer to the question in its original form.
This is kind of more on an electronics question. But it may be of some interest people here, mostly because of Digispark clones that still have their reset functionality.
It's easier to answer these in a different order.

I read that pin reset can be simply analog pin of the voltage to it is above 2.5v Is it true?
If so, i can program it with arduino spi normally as the battery will never go below 2.5v

Practically speaking the answer is best summarized as "no".
It took me a while to realize what you were talking about, mostly because of
this 2.5V number, which I still don't completely understand. Originally I thought you talking about the internal 2.56V reference.  The way I'm interpreting this is "As long as I don't actually cause a reset, is it true that I can use the ADC0 channel that is on the ATtiny85 RESET pin."
Practically, I think no. But, this idea is amusing and also more than a little disturbing.  It seemed that the answer could be a qualified yes only because it seemed ATMEL would need to have done extra work to make this not possible, even if trying to do it is a bit nuts. Naturally, I had to try it.
In testing I found that yes, the RESET pin still seems to function as an ADC channel.  I was able to hook the division point of 2/3rds (ish) voltage divider to the reset and got a reading of 0xAD (as an 8-bit measurement) which is indeed about 2/3rds of 0xFF. At least this is the case with my particular chip under whatever operating conditions.
According to the datasheet the V_RST (nRESET pin voltage threshold)
is specified at 3V to be between 0.2 VCC and 0.9 VCC.  It doesn't seem like you would have good reason to think the chip is certain to stay out of reset below 0.9 VCC which at 5V is 4.5V. I did not experiment with mine to find out where the threshold happened to be except that 1/3 VCC did trigger a reset.
So, I don't know where your 2.5V comes from except to say it's a number near the middle of the possible V_RST range for an AVR at 5V. Even if you find this is where the threshold is for your chip, it isn't specified to be exactly there. The fact that I got a reading at 2/3rds instead of a reset does not seem specified to happen that way according to the datasheet.
Another thing about this is when the pin is used as RESET has its internal pullup is enabled, which is listed between 30K and 60K.  So whatever you connect to your reset pin (your battery) is connected to the AVR VCC through a pullup.
Anyway, it's interesting but is ultimately probably a bad idea.

So there is a lipo battery will be always connected to this pin

If you want to play with this using-RESET-pin-for-ADC-channel thing anyway,
definitely don't have your battery connected to reset when you program, at least not without reasonable series resistance.  Otherwise when your programmer goes to reset your ATtiny85 it will short your battery to GND through the programmer.

I want to use reset pin of attiny85 as analog pin to read the battery voltage to be used as low level battery indicator

Voltage isn't a great indication of the state of charge of batteries generally. Under some conditions you can get a rough idea with it. The flatter the discharge voltage curve is the less useful voltage is as an indication of charge state. Lithium chemistries are sort of prized for producing fairly flat discharge curves at a voltage level high enough to do useful work. Typically a "coulomb counting" method is used instead. Basically you sample current over time and integrate (sum) this, not reading instantaneous (or short term averaged) battery voltage. And that has its own intricacies with not drifting from true value. Getting a reasonable sense of lipo's state of charge is enough of a pain to do well that there exist metering chips specifically designed to do this.  I don't have good recommendations for them, but MAX17043 and MAX17048 are among the first part numbers for this sort of chip found on modules from suppliers of Arduino-related stuff.

I want to use reset pin of attiny85 as analog

For most Arduino users it's really best to leave the reset pin alone. The ATtiny84 is not much larger than an ATtiny85 and gives you an few extra pins and is otherwise very similar. The ATtiny84 also supported by attinycore. If you are hard set on using the ATtiny85 make sure you've exhausted all your options for using your other pins. There are ways to connect multiple switches to a single analogRead() capable pin. There are ways to put LEDs and switches on the same pin if you don't mind the light coming on when you push button, etc.

I need high voltage programmer to do so but

Right, so back onto using non-RESET functionality of the RESET pin the normal way.
Sort of. You don't need high voltage serial programming mode to program your code that use the reset pin onto the chip and then to disable the reset pin and use it via digitalRead()/digitalWrite()/analogRead()/etc.. But you do need high voltage mode to program again after that, either by programming code via high voltage mode or programming (unprogramming really) the RSTDISBL fuse to re-enable RESET functionality that ISP/SPI mode requires. In other words: if you're treating the parts as one-time-programmable then you need only an ISP programmer. But, during development you're probably not going to want to just toss out piles of otherwise perfectly good chips.
If you're determined to use the ADC channel that's on the reset pin, programming RSTDISBL fuse is the thing you want to do. Then you get useful range out of the ADC channel and the ability to disable the pullup, and maybe even fewer random resets.
And yeah, you need a high-voltage mode programmer to recover from that, and you need to be either able to remove the chip from the board or design the board to handle HVSP signals coming to it; in particular to handle 12V that will be applied to reset.  Which is also something that should not make its way to your lipo.

could you see the edit?

I am not chasing down a moving target. If you want to know where the forum poster got their 2.5V figure from ask them, I can't get inside their head. If you'd already taken the time to do what I'd dove in verifying that the reset pin behaves the way it manifestly does, then you should have put that in your original question.


text:
Why is my variable giving the wrong value?
I'm making a program to show numbers in a WS2812 LED and TM1637. I'm also using a common 4x4 keypad.
The WS2812 LED is just DIY with 25 x 10. Only two values can be displayed in a LED matrix just now. Without the LED part of the program, just the TM1637 and keypad connected to the Arduino, everything is fine. But adding the LED part of the program, I found out that entering 2 on keypad puts  an erroneous value in my variable (-256 to exact). I tried debugging my code and found out that replacing the last iteration
for (int i = 225; i <= 231; i++) {
with this line
for (int i = 225; i <= 230; i++) {
mysteriously solved my problem. Any thoughts why this is happening?
#include <Keypad.h>
#include <Arduino.h>
#include <TM1637Display.h>
#include <Wire.h>
#include <FastLED.h>
// Module connection pins (Digital Pins)
#define CLK 2
#define DIO 3
#define NUM_LEDS  225
#define LED_PIN   12
CRGB leds[NUM_LEDS];
TM1637Display display(CLK, DIO);
int DisplayNos=0;
int KeyNum;
char key;
boolean NewKey = false;
boolean DeleteAll=false;
int SavedNum;
// for 3 digits
int ExtractDigit[3] = {0, 0, 0};
byte DigitPoint= 1;
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {11, 10, 9, 8}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {7, 6, 5, 4}; //connect to the column pinouts of the keypad
//Create an object of keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup(){
  Serial.begin(9600);
  FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(250);
}
void loop(){
int k;
//  uint8_t data[] = { 0x0, 0x0, 0x0, 0x0 };
//  uint8_t blank[] = { 0x00, 0x00, 0x00, 0x00 };
  display.setBrightness(0x0f);
  key = keypad.getKey();// Read the key
  // Print if key pressed
  if (key){
    Serial.print("Key Pressed : ");
    Serial.println(key);
    if (isDigit(key)){
      KeyNum = key-48;
      Serial.println(key);
      Serial.println(DisplayNos);
      if (DigitPoint==1){
        DisplayNos = 0;
        DisplayNos = KeyNum;
      }
      if (DigitPoint==2){
        DisplayNos = KeyNum + (DisplayNos*10);
      }
      if (DigitPoint==3){
        DisplayNos = KeyNum + (DisplayNos*10);
      }
      DigitPoint= DigitPoint+1;
      if (DigitPoint==4){
        DigitPoint=1;
      }
    }
      if (key=='*'){   // asterist key cancels all char
      DisplayNos = 0;
      DigitPoint = 1;
    }
    if (key=='#'){   // asterisk key cancels all chars

    }
    NewKey = true;
  }
  display.showNumberDec(DisplayNos,false,3,0);
  if (NewKey == true){
    DisplayLED();
    FastLED.show();
  }
}
void DisplayLED(){
int LedNum;
byte digitnos;
NewKey = false;
  ExtractDigit[3] = (DisplayNos/100)%10;
  ExtractDigit[2] = (DisplayNos/10)%10;
  ExtractDigit[1] = (DisplayNos)%10;
  for (int digitnos= 1; digitnos <= 3; digitnos++) {
    LedNum = (digitnos-1)*9;
    if (ExtractDigit[digitnos] == 1){
      leds[21-LedNum]= CRGB::Blue;
      leds[28+LedNum]= CRGB::Blue;
      leds[29+LedNum]= CRGB::Blue;
      leds[71-LedNum]= CRGB::Blue;
      leds[78+LedNum]= CRGB::Blue;
      leds[121-LedNum]= CRGB::Blue;
      leds[128+LedNum]= CRGB::Blue;
      leds[171-LedNum]= CRGB::Blue;
      leds[178+LedNum]= CRGB::Blue;
      leds[221-LedNum]= CRGB::Blue;
      leds[229+LedNum]= CRGB::Blue;
      leds[228+LedNum]= CRGB::Blue;
      leds[227+LedNum]= CRGB::Blue;
    }
    if (ExtractDigit[digitnos] == 2){
      for (int i = 20; i <= 22; i++) {
        leds[i-LedNum] = CRGB::Blue;
      }
      leds[26+LedNum]= CRGB::Blue;
      leds[30+LedNum]= CRGB::Blue;
      leds[68-LedNum]= CRGB::Blue;
      leds[74-LedNum]= CRGB::Blue;
      leds[76+LedNum]= CRGB::Blue;
      leds[122-LedNum]= CRGB::Blue;
      leds[128+LedNum]= CRGB::Blue;
      leds[170-LedNum]= CRGB::Blue;
      leds[180+LedNum]= CRGB::Blue;
      leds[218-LedNum]= CRGB::Blue;
      leds[225+LedNum]= CRGB::Blue;
      leds[226+LedNum]= CRGB::Blue;
      leds[227+LedNum]= CRGB::Blue;
      leds[228+LedNum]= CRGB::Blue;
      leds[229+LedNum]= CRGB::Blue;
      for (int i = 225; i <= 231; i++) {
        leds[i-LedNum] = CRGB::Blue;
      }
    }
  }
  }


text:
L298n driver with Arduino with 2 motors won't work
I connected the 12v power supply with 9v battery. The problem is that when i run 1 motor at time from any side (out 1, 2 out 3, 4) it works perfectly, but when I try to run both of them, only one will run and the other won't. They work if I run one motor at a time.
Is this a problem with not enough power? The motors are DC gear motors. This is the code:
int in1 = 12;
int in2 = 13;
int in3 = 8;
int in4 = 9;
int en1 = 11;
int en2 = 10;
void setup() {
   pinMode(in3, OUTPUT);
   pinMode(in4, OUTPUT);
   pinMode(en1, OUTPUT);
   pinMode(in1, OUTPUT);
   pinMode(in2, OUTPUT);
   pinMode(en2, OUTPUT);
}

void loop() {
   analogWrite(en1, 255);
   digitalWrite(in1, LOW);
   digitalWrite(in2, HIGH);
   analogWrite(en2, 255);
   digitalWrite(in3, LOW);
   digitalWrite(in4, HIGH);
}

Yes, most likely. Motors can draw a lot of power and your 9v battery is probably struggling to output enough voltage. 50-100 mA is about the max current you want to draw from a 9v. 9v batteries have a high internal resistance and the voltage will drop potentially well below 9v when you draw a lot of current from them. Used to make Altoids tin USB chargers back in the day with a 9v but cellphones now need multiple Amps of power and so do motors.
Here's a couple things you can do to check:
Set up your code to run both motors. Connect a motor to one side and see if it works. Then connect it to the other side (without changing the program or other wiring.) If that motor runs on both sides, check the other motor. This will make sure both motors are good and that both channels on the driver are good. Check the voltage on the battery and the motor and write down the values each time.
If the current you measure with a single motor is much higher than 25-50 mA, 2 motors will exceed the limit. Note the motor (label them) and the channel it is connected to.
If that seems to check out, connect both motors. We know they don't both spin, but take this time and measure battery voltage and motor voltage. Measure the current if possible too. If you are getting greater than 50-100mA from the battery, you are likely going to have issues.

In the code, you have set the enable pins (en1 and en2) for both motors to the maximum value (255), which means they will run at full speed. If one of the motors cannot start under high load, you can try reducing the PWM value, for example, setting it to 200 or lower, to see if it is possible to start both motors simultaneously.


text:
Find Elapsed Time on Serial Plotter
How do I find out the elapsed time from the serial Plotter graph? I am plotting sensor values from the Arduino Nano and would like to know the time scale on the x-axis in order to calculate settling time of oscillations.
I have tried the suggestions here but they do not seem to work in my case.
For example, in the graph below I would like to find out the time it took for the sensors to record their first movement at around point 190.

I am doing the following to print two values:
   //printData1();
   Serial.print(roll_err);
   Serial.print(" ");
   Serial.println(pitch_err);
   Serial.print(" ");

Baud Rate: 9600
Loop Time: 40ms
If my loop time is 40ms then I was thinking that the total time would be 180*40ms. Is this reasoning correct?
Is there a better way to read the time elapsed in the serial plotter?
EDIT: Trying to get a 10ms 'grid'
As per the suggestion in the answer below I have tried running something similar to the following but the loop does not run at a constant time.

I tried to add Serial.print(((millis()/10)%2)*50); but as can be seen, the loop time is not constant.

The serial plotter in the IDE is pretty basic. The x axis is just the number of y values, and 1 pixel in the x direction. You could try adding Serial.print(((millis()/10)%2)*50);  to fake a 10 ms "grid".
Serial.print(" ");

If my current loop time is 40ms shouldn't I be dividing that by 40 to get a 10ms 'grid' ?

Sorry, I kind of missed that part. I’d probably go with 1000ms. But note that a line could end up being at for example 2038ms instead of 2000ms due to the around 40ms it takes per loop.

Alternative would be to also print the millis value an copy the data to excel. And use that to plot a graph.

It depends on how precise you want your time-base to be. The plotter's x-axis is in sample-count, not time, so you have to emit samples at a fixed rate for it to have time-significance.
Your
loop(){
   yadda();
   zadda();
}

may or may not run at a constant rate, depending on what takes place in each iteration of the loop, as well as on your definition of "constant" (I don't believe I just said that...)
Even if none of your code is conditional, binary to ASCII conversion, clock and Serial interrupts, and other low-level code we don't see, may run slightly differently from iteration to iteration; e.g. the number of interrupts during any given iteration may well vary.
If you need to hold a tighter timebase, stalling at the bottom of the loop until millis() reaches (the previous millis() + an interval constant) will at least get you to within a millisecond of a fixed loop-rate. You could, of course, do the same thing with micros(), as long as you know for a fact that the loop can never take longer to execute than 1/frequency you need it to run at, and even then, it should take a fair slop-factor (that's a technical term! :) less than that, "just in case".
Update:
Though I wrote "stalling" at the end of the loop, a better technique is to call every job (in your case, 1 of them - for now ? ) as frequently as possible and let each job decide whether it needs to execute. So in your case:
loop {
  maybeSampleAndPlot();
  // maybeDoSomeOtherThing();  // not implemented yet...
}

maybeSampleAndPlot(){
  time = millis();
  if time - previousSampleTime >= MSEC_040
    save (time + MSEC_040) as nextSampleTime;
    sample the data;
    plot the data;
  endif
}

Thanks for your answer. I will try to implement this. Is the interval constant used to allow for additions in computational time within the main loop? Updated my question. Would you be kind enough to provide some short pseudo-code on how I should go about implementing the millis() computation? Much appreciated.

Look at the BlinkWithoutDelay example of the Arduino IDE and replace the LED blink code with your measurement code. Then change the interval variable to the value you need.

if time >= nextSampleTime should be replaced by if time - previousSampleTime >= MSEC_040. Otherwise the timing will fail when millis() rolls over. The “Blink without delay” tutorial does it the right way.

Absolutely correct - fixed. Thanks, @EdgarBonet. [face-palm]


text:
Is there a way to send data from Tensorflow to Arduino via Bluetooth?
I am not sure if such a question is accepted here. If not please direct me to a more suitable Exchange.
I am planning a small project involving Machine Learning using TensorFlow and Python, which involves GAIT learning of a quadrupedal robotic system. The robotic system will be controlled by a simple Arduino. This will send data to the 8 servo motors located in the 4 legs of the robot. (2 on each leg) The robot is similar to this.
My question is if there a way to transfer data to and from Tensorflow via Bluetooth to the Arduino.
The Arduino will not be connected serially to my PC, so serial communication is not an option. Bluetooth and Wireless remain, of which, Bluetooth is generally easier.
I have done several projects involving HC-05 modules to transfer data from different systems to an Arduino so that part is not an issue. What I am interested in is if Tensorflow offers this kind of support, or if there is an easier way to do this. Searching online did not yield any results related to what I am after.
Any tips or suggestions would be appreciated.

"What I am interested in is if Tensorflow offers this kind of support, or if there is an easier way to do this." That's not an Arduino question.

Any advice on a better exchange to ask this? I thought that there was quite a possibility that someone from this community would have done something similar.

Robotics Stack Exchange might be a better fit. I can migrate your question there if you want.

The question is more "Is there a way to send data from Python ?" than "Is there a way to send them from Tensorflow to an Arduino ?" and the Answer is yes.
In Tensorflow your can recover your result in a tensor (which you can easily transform in a Python array) and then send it with Python through whatever support you want to the Arduino.