text:
Random number/sequence output
The program I'm trying to build is:

Type in 1st name, hit enter, type in 2nd name and then hit enter again.
Register those names from string input to char naming in student struct.
Print out the names in serial monitor.
Use those names in the main program.

The problem is I got randomize results whenever I typed in the names.
My target output:
Program Starts
Insert 2 students name:

First student: Adam     //When input -> Adam
Second student: Eve     //When input -> Eve
First student: John    //When input -> John
Second student: Amy    //When input -> Amy
//the sequences should repeat

...but what happened is the sequences of the names randomized. For example:
Program Starts
Insert 2 students name:

First student: Adam
First student: Eve
Second student: John
First student: Amy
//the sequences will keep randomizing

Can anyone point out what I've missed out?
The program:
typedef struct
    {
        char naming[20];
    }student;

    student record[]{
      {""},
      {""},
    };

    String readString;
    String str="";

    // the setup routine runs once when you press reset:
    void setup() {
      Serial.begin(9600);    // initialize serial communication at 9600 bits per second
      while (!Serial);              // wait for Serial Monitor to open
      SerialUSB.println("Program Starts \n Insert 2 students name:");  // Title of sketch
    }

    void loop() {
        namedata();
        mainprg();
    }

    void namedata()
    {
    for(uint8_t i = 0; i < sizeof(record)/sizeof(student); i++){
          while (Serial.available()) {
            char c = Serial.read();
            readString += c;
            readString.trim();
          }

          if (readString.length() >0) {
            str = readString;
            str.toCharArray(record[i].naming,20);
            if(i==0){
               Serial.print("First student: ");
            }else if(i==1){
               Serial.print("Second student: ");
            }
            Serial.println(record[i].naming);
          }
            readString="";
        }
    }

    void mainprg()
    {
      //main program using student`s name
    }

Additional infos:
1.Why use struct? Because I've more data to process/store for one "student" in my main program.
2.Currently using Arduino Yun Mini, Arduino 1.8.7
Thanks in advance!

change ++i to i++

@Juraj Nope still the same, though I also tried if(int i; i<2; i++) to no avail...

your algorithm for reading the names is based on misunderstanding how Serial input works

@Juraj I would appreciate it if you can point me to any info on the topic

The problem, that Juraj mentioned, is that you seem to think, that all the data from one name input will arrive as a big chunk, so that the while loop will only exit, when a full name has been read. That is not the case. There might be pauses between arbitrary bytes in the stream, for example introduced from the OS of the PC. The while loop will often exit, before a full name is read. You can use the something like the readline function here: https://majenko.co.uk/blog/reading-serial-arduino

@chrisl Thank you for the link. I (somewhat) understand now how Serial.read works, but I still cannot pause the loop until the second name input and register it into record[i].naming, thus the random sequences caused by random loop exits.

Why do you use SerialUSB in your setup function, but Serial in the rest of the code? I'm not sure, what happens on an Arduino with only one serial interface, when using SerialUSB, but on other boards (as I recall the Due for example) These two are complete different interfaces. Though I don't see, how you can get this randomized order due to this.

@chrisl About the SerialUSB, you are right; its the same thing as Serial.  As for the randomized order, I wonder that myself  ¯_(ツ)_/¯

Even though this is not elegant by any means, for now this is what I've came out with:
typedef struct
{
  char naming[20];
} student;

student record[] {
  {""},
  {""},
};

int a = 0;

char buf[20];

// the setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);    // initialize serial communication at 9600 bits per second
  while (!Serial);              // wait for Serial Monitor to open
  Serial.println("Program Starts \n Insert 2 students name:");  // Title of sketch
}

void loop() {
  if (readline(Serial.read(), buf, 20) > 0) {
    if (a == 0) {
      Serial.print("First student: ");
      strncpy(record[a].naming, buf, 20);
      Serial.println(record[a].naming);
      a = 1;
    }
    else if ( a == 1) {
      Serial.print("Second student: ");
      strncpy(record[a].naming, buf, 20);
      Serial.println(record[a].naming);
    }

  }
}

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len - 1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  return 0;
}

Basically by using int a, the program decides the sequences of the name. Although it will not repeat the sequence after the 2nd input (ie 1st>2nd>1st>2nd), at least the sequence is not randomize anymore.
Btw thanks for the tips @chrisl!


text:
AVR-GCC can't call function located on fixed address
I wrote the following code:
#include <avr/io.h>

__attribute__((noinline, section(".app_start"))) void app_start() //app_start section starts at 0xFA0
{
    //register_packet_dispatch(packet_received);
    PORTB = 0xFF;
}

__attribute__ ((noinline)) void call_app()
{
    asm ("call 0xFA0\nret");
    //app_start();
}

int main()
{
    DDRB = 0xFF;
    //call_app();
    app_start();
    while(1){}
}

What I compiled with:
avr-gcc -Wl,--section-start=.reg_dispatch=0xdac -Wl,--section-start=.app_start=0xFA0 -mmcu=atmega328p -Os -o ubb.o ub_bootloader.cpp -DF_CPU=16000000

Which tries to simulate a host application that tries to call a relocated client application, begins from the 4000 address (0xFA0). If it would work, it's light up the LED wired to the arduino's 13. pin. But why app_start won't be called?
I've also inspected the output assemlby:
avr-objcopy -j .text -j .data -O ihex ubb.o ubb.hex

00000fa0 <_Z9app_startv>:
 fa0:   8f ef           ldi r24, 0xFF   ; 255
 fa2:   85 b9           out 0x05, r24   ; 5
 fa4:   08 95           ret

00000080 <main>:
  80:   8f ef           ldi r24, 0xFF   ; 255
  82:   84 b9           out 0x04, r24   ; 4
  84:   0e 94 d0 07     call    0xfa0   ; 0xfa0 <_Z9app_startv>
  88:   ff cf           rjmp    .-2         ; 0x88 <main+0x8>

Everything seems correct, why it isn't working at all?
Of course, if i remove the "noinline" attribute, it works. But that's a mirage, the compiler inlines the content of the function, but when I build this into an application, the code after the 0xFA0 address will be rewritten by the host application.

Note: app_start won't be called even if i call directly (calling app_start() shown in comment, instead of asm "call 0xFA0")

You mean -o ubb.elf?

but the version in question with app_start called from main works?

No, calling app_start directly from the main also doesn't work.

ubb.o: .elf and .o are just file endings file ubb.o says: ubb.o: ELF 32-bit LSB executable, Atmel AVR 8-bit, version 1 (SYSV), statically linked, not stripped.

Your program works fine on my Uno.

I've tried this code with arduino and it worked (i taught, of course, i can't add the "-Wl,--section-start=.app_start=0xFA0" flag to the compilation process so the function not gonna be moved to other section)
So i set the arudino IDE to show every command from the compilation to the end of the upload process.
The problem lies in the usage of avr-objdump, whose i found somewhere and used witouth overview the CLI switches.
I've also made a mistake when i wrote the question. To disassemble the object file, the right command is:
avr-objdump -S --disassemble  ubb.o > ubb.asm

THe command i've used to create hex file:
avr-objcopy -j .text -j .data -O ihex ubb.o ubb.hex

The working one (extracted from arduino):
avr-objcopy -O ihex -R .eeprom ubb.o ubb.hex

-j means keep only the given section(s)
while
-R means, remove only the given section(s)

source: Stack Exchange

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

sort: votes


text:
RGB LED lights and Arduino
I am doing my thesis project which is a kinetic light/sound sculpture. My first step is to learn how to work with RGB LED lights and how to choose them and what other kinds of equipment I need.
I started to learn Arduino uno and learned how to light an LED, now I need to expand it much bigger.
I want to be able to control each LEDs.
I want 30 meters LED light divided to 7 channels, in which each channel have a unique function that will trigger 7 channels of sound.
I hope I could use your help and thanks in advance for your time :)

I suggest you to use RGB Led Driver like: WS2812.
You can build led strip as long as you want.
There are a lot of example/tutorial using Arduino and Strip Led composed by WS2812 Led Driver (For example, here there is a tutorial).
NB: You pay attention that using 30 meters strip led, you need an external power supply and you can't use 5V pin of Arduino, because Arduino doesn't supply sufficient power for supply a strip led too long.

Thank you so much. do I also need these? I found it on 1 tutorial :
-1 x 220-440 Ohm Resistor (anything between these two values is fine)
-1 x 100-1000 microFarad Capacitor (anything between these two values is fine)
-5V power supply

Yes, how many strip do you need?

it is complicated if I am gonna just explain it without showing you any layouts but I try my best. So 30 meters stripe divided into 7 channels, each channel has a unique function and is made of 8 to 16 pieces from 10 cm to 60 cm. It's a modular/ parametric/algorithmic design.

Ideally, you would have a resistor between the Arduino pin and the first WS2812B for each strip. 7 strips  could be driven from 7 pins. Everytime you update a strip, the # of LEDs x 3 is how many bytes of data get sent out. You could also do it as one very long strip - the amount of data being sent out for a color change is then 7 times as much.  Adafruit.com has a  neopixel library for driving these LEDs, and fastled.h is another option.  Ex: here are four rings with 43 or 44 WS2812B each that I made, all are connected via individual wires to a 5V/10A supply, each has its own data line

https://www.youtube.com/watch?v=CGOxbehyoM4&t=37s

and another question is that I have 6 PWM pins, can I add one to it ?

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


text:
What is the state of Arduino pins when the arduino is unpowered?
I'm building a control box to provide logical control of power outlets.
I'm using a 4 channel 5V optically isolated relay system to control 4 separate outlets.
To use optical isolation you connect arduino +5V to the VCC line, and logic inputs to the 4 channels of the relay unit, and connect a separate +5V supply to run the coils of the relays.
To energize one of the relays, you pull that control line LOW. To de-energize the coil, you drive the line HIGH.
If I power on the relay but leave the Arduino unpowered, all the relay coils energize.
Do Arduino pins float when it is powered down, or are they grounded?
Could I wire a pullup resistor to the inputs? And how would I do that without losing optical isolation? If I connect my pullup resistors to the +5V for the relays, the relay's +5 is connected to the Arduino's logic lines. If I instead use the Arudino's +5 rail, then when the Arduino is powered down, it's +5V line is dead.

Did you remove the jumper between VCC to JD-VCC?

PS why do you want optical isolation? The relays already provide galvanic isolation.

Yes, I removed the jumper so the 2 +5v supplies are isolated.

connect the opto-isolator LED between two of the digital pins ..... if the pins float or if the pins are both the same level then the opto-isolator will not activate

You mean use one of the Arduino pins as the VCC for the Arduino, and the other as the logic input? Then use the pin connected to VCC as a power switch? I like it. It still doesn't protect the Arduino from +5 coming into it's logic lines while the Arduino is unpowered however.

would an nchannel fet between the logic's gnd and the AVR's gnd prevent the intrinsic pull-down? you can then use the fet as a "relay enable" by driving its gate high, or simply tying it to the AVR's VCC

The pins have input protection diodes that clamp the pins to Vcc and Gnd. If a pin gets to >VCC +0.5V the positive diode clamp conducts and Vcc is powered via the internal Vcc bus, and if a pin get to < -0.5V the negative diode clamp conducts.  With Vcc = 0V, the pin could act as if it were a low, but more generally folks see the chip acting like it was phantom powered and attempting to run code with perhaps unpredictable results.  That's why the datasheet says to not drive the pins when th chip is unpowered.  If the clamp current becomes too much, the diode can blow, and either just the one pin is impacted, or the whole chip dies and it will feel warm/hot to the touch when powered up.
So don't power up the relays without also powering up the Arduino.

the circuit is wired only to Arduino VCC and pin on the LED side of the optocoupler  https://i.stack.imgur.com/14WTN.jpg

Hmm, that doesn't seem like the Opto could be turning on its output transistor then. Some relay boards have a jumper that connects the VCCs together. If you measure pins 1 and 4, is 1 low and 4 high?

My goal is to not power the relay without powering the Arduino. However, it would be bad if the AC power is on and the relay's power supply is "lit" but the Arduino's power supply fails or the Arduino fails to power up. In that case my outlets would all be turned on.

I have my project built so I can plug a computer into the Arduino's USB, in which case it draws it's power from USB and the relay is powered from a separate supply.

That would work.  Or use a 5V wallwart into the USB connector to keep the Arduino powered, if you don't need PC connectivity all the time.

Right, but my question is, how do I handle the error case where there is power to the relay board and the AC source, but not to the Arduino? (Simple case: I forget to plug the USB cable into the Arduino. More serious case: The Arduino's power supply fails or the Arduino fails to start for some reason.)

I guess there's no good answer other than "Don't do that." I might need a power transistor (like an N-channel MOSFET on the relay power supply, with it's gate controlled by a logic line from the Arduino.

or a relay board with coil powered if signal is HIGH

As it turns out my question was a bit of an X/Y problem. I wanted to know what the pins on the Arduino do when the board is unpowered, because I was feeding +5V into the VCC input on my relay board when the Arduino was unpowered, and having the relay control lines connected to Arduino pins.
If you remove the jumper on my relay board, it has a VCC line that ONLY powers the logic level inputs to the relay control optical isolators  and a JVCC line that drives the relay coils. (The VCC line might also power the optical isolators and the other CMOS circuitry on the board, I'm not sure.)
I have my Arduino wired to a USB input that is driven by a regulated AC power supply when it's running stand-alone, and from my computer when it's being programmed. Sometimes I forget to plug the AC powered USB cable into the Arduino when I switch to running it stand-alone off of AC, and in those cases the relay lines tend to energize when I don't want to, and I end up driving +5V into the Arduino's relay control GPIO lines, which is not a good idea.
The simple answer is to connect the +5V line from the Arduino to the VCC pin on the relay board. Then when the relay's JVCC is powered but the Arduino is not, the VCC line to the relay and the control lines to the relay are all unpowered, so the relay is off.
Duh.


text:
'RtcDateTime' does not name a type
I've tested a code that compiles successfully.
But after i merged it to another code, here it shown an error says RtcDateTime doesn't name a type.
Used library : https://github.com/Makuna/Rtc

Some notes :
- RtcDateTime instances are being used in setup() and loop() without a problem.
- RtcDS3231 header file is included (which includes RtcDateTime.h inside it).
- Tried to include RtcDateTime.h in my sketch, doesn't work !
Code : (Contains combination of 3 devices : RTC , I2C Ultrasonic and HX711 loadcell)
/*
Below, I define the SCL and SDA pins by their ATMEGA pins I have included links to common mappings below.
    UNO:  http://arduino.cc/en/Hacking/PinMapping168
    NANO: (matches UNO but has fewer pins)
    MEGA 2560: http://arduino.cc/en/Hacking/PinMapping2560
The current data matches the setup for the Arduino Uno -- they may need to be changed if the hardware changes.
You can also switch the I2C interface
to any of the tristate pins that you want (not just the SDA or SCL pins).
*/
#define SCL_PIN D2              //Default SDA is Pin5 PORTC for the UNO -- you can set this to any tristate pin
#define SDA_PIN D1              //Default SCL is Pin4 PORTC for the UNO -- you can set this to any tristate pin
#define I2C_TIMEOUT 100        //Define a timeout of 100 ms -- do not wait for clock stretching longer than this time

#include "HX711.h"  //You must have this library in your arduino library folder

#define DOUT  D1
#define CLK  D2

HX711 scale(DOUT, CLK);
float calibration_factor = -10060; //-106600 worked for my 40Kg max scale setup

/*
I have included a couple of extra useful settings for easy reference.
//#define I2C_CPUFREQ (F_CPU/8)//Useful if you plan on doing any clock switching
#define I2C_FASTMODE 1         //Run in fast mode (400 kHz)
#define I2C_SLOWMODE 1         //If you do not define the mode it will run at 100kHz with this define set to 1 it will run at 25kHz
*/
#include <SlowSoftI2CMaster.h>     //You will need to install this library
// create new instance with A4 as SDA, A5 as SCL and enable internal pullups
SlowSoftI2CMaster si = SlowSoftI2CMaster(SDA_PIN, SCL_PIN);

/*
 *  RTC Code starts here
 */

#include <Wire.h> // must be included here so that Arduino library object file references work
#include <RtcDS3231.h>
RtcDS3231<TwoWire> Rtc(Wire);
/*
 *  RTC Headers Ending
 */

void setup(){
  // Initialize both the serial and I2C bus
  Serial.begin(9600);
  Serial.println("Press T to tare");
  scale.set_scale(calibration_factor);  //Calibration Factor obtained from first sketch
  scale.tare();             //Reset the scale to 0

if (!si.i2c_init()) // initialize I2C module
        Serial.println("I2C init failed");

    /*
     *  RTC Setup :
     */
     Rtc.Begin(SDA_PIN,SCL_PIN);

    RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
    printDateTime(compiled);
    Serial.println();

    if (!Rtc.IsDateTimeValid())
    {
        // Common Cuases:
        //    1) first time you ran and the device wasn't running yet
        //    2) the battery on the device is low or even missing

        Serial.println("RTC lost confidence in the DateTime!");

        // following line sets the RTC to the date & time this sketch was compiled
        // it will also reset the valid flag internally unless the Rtc device is
        // having an issue

        Rtc.SetDateTime(compiled);
    }

    if (!Rtc.GetIsRunning())
    {
        Serial.println("RTC was not actively running, starting now");
        Rtc.SetIsRunning(true);
    }

    RtcDateTime now = Rtc.GetDateTime();
    if (now < compiled)
    {
        Serial.println("RTC is older than compile time!  (Updating DateTime)");
        Rtc.SetDateTime(compiled);
    }
    else if (now > compiled)
    {
        Serial.println("RTC is newer than compile time. (this is expected)");
    }
    else if (now == compiled)
    {
        Serial.println("RTC is the same as compile time! (not expected but all is fine)");
    }

    // never assume the Rtc was last configured by you, so
    // just clear them to your needed state
    Rtc.Enable32kHzPin(false);
    Rtc.SetSquareWavePin(DS3231SquareWavePin_ModeNone);

    /*
     *  RTC Setup Ending
     */
}
#define countof(a) (sizeof(a) / sizeof(a[0]))

void loop()
{
  if (!si.i2c_init()) // initialize I2C module
        Serial.println("I2C init failed");
  // (OPTIONAL) Read a sensor at the default address
  read_the_sensor_example();

  scale.begin(SDA_PIN,SCL_PIN);
  Serial.print("Weight: ");
  Serial.print(scale.get_units(), 5);  //Up to 3 decimal points
  Serial.println(" kg"); //Change this to kg and re-adjust the calibration factor if you follow lbs

  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == 't' || temp == 'T')
      scale.tare();  //Reset the scale to zero
  }

  /*
   *  RTC Loop Start
   */
  if (!Rtc.IsDateTimeValid())
    {
        // Common Cuases:
        //    1) the battery on the device is low or even missing and the power line was disconnected
        Serial.println("RTC lost confidence in the DateTime!");
    }

    RtcDateTime now = Rtc.GetDateTime();

    Serial.println();
    // String date = dateS(now);
    // String time = timeS(now);

  RtcTemperature temp = Rtc.GetTemperature();
  temp.Print(Serial);
  // you may also get the temperature as a float and print it
    // Serial.print(temp.AsFloatDegC());
    Serial.println("C");

  /*
   *    RTC loop Ending
   */
}

void printDateTime(const RtcDateTime& dt)
{
    char datestring[20];

    snprintf_P(datestring,
            countof(datestring),
            PSTR("%02u/%02u/%04u %02u:%02u:%02u"),
            dt.Month(),
            dt.Day(),
            dt.Year(),
            dt.Hour(),
            dt.Minute(),
            dt.Second() );
    Serial.print(datestring);
}

///////////////////////////////////////////////////
// Function: Start a range reading on the sensor //
///////////////////////////////////////////////////
//Uses the I2C library to start a sensor at the given address
//Collects and reports an error bit where: 1 = there was an error or 0 = there was no error.
//INPUTS: byte bit8address = the address of the sensor that we want to command a range reading
//OUPUTS: bit  errorlevel = reports if the function was successful in taking a range reading: 1 = the function
//  had an error, 0 = the function was successful
boolean start_sensor(byte bit8address){
  boolean errorlevel = 0;
  bit8address = bit8address & B11111110;               //Do a bitwise 'and' operation to force the last bit to be zero -- we are writing to the address.
  errorlevel = !si.i2c_start(bit8address) | errorlevel;   //Run i2c_start(address) while doing so, collect any errors where 1 = there was an error.
  errorlevel = !si.i2c_write(81) | errorlevel;            //Send the 'take range reading' command. (notice how the library has error = 0 so I had to use "!" (not) to invert the error)
  si.i2c_stop();
  return errorlevel;
}

///////////////////////////////////////////////////////////////////////
// Function: Read the range from the sensor at the specified address //
///////////////////////////////////////////////////////////////////////
//Uses the I2C library to read a sensor at the given address
//Collects errors and reports an invalid range of "0" if there was a problem.
//INPUTS: byte  bit8address = the address of the sensor to read from
//OUPUTS: int   range = the distance in cm that the sensor reported; if "0" there was a communication error
int read_sensor(byte bit8address){
  boolean errorlevel = 0;
  int range = 0;
  byte range_highbyte = 0;
  byte range_lowbyte = 0;
  bit8address = bit8address | B00000001;  //Do a bitwise 'or' operation to force the last bit to be 'one' -- we are reading from the address.
  errorlevel = !si.i2c_start(bit8address) | errorlevel;
  range_highbyte = si.i2c_read(0);           //Read a byte and send an ACK (acknowledge)
  range_lowbyte  = si.i2c_read(1);           //Read a byte and send a NACK to terminate the transmission
  si.i2c_stop();
  range = (range_highbyte * 256) + range_lowbyte;  //compile the range integer from the two bytes received.
  if(errorlevel){
    return 0;
  }
  else{
    return range;
  }
}

/////////////////////////////////////////
// Function: Change the sensor address //
/////////////////////////////////////////
//Uses the I2C library to change the address of a sensor at a given address
//Collects and reports an error bit where: 1 = there was an error or 0 = there was no error.
//INPUTS: byte oldaddress = the current address of the sensor that we want to change
//INPUTS: byte newddress  = the address that we want to change the sensor to
//OUPUTS: bit  errorlevel = reports if the function was successful in changing the address: 1 = the function had an
//      error, 0 = the function was successful
boolean change_address(byte oldaddress,byte newaddress){
  //note that the new address will only work as an even number (odd numbers will round down)
  boolean errorlevel = 0;
  oldaddress = oldaddress & B11111110;  //Do a bitwise 'and' operation to force the last bit to be zero -- we are writing to the address.
  errorlevel = !si.i2c_start(oldaddress) | errorlevel; //Start communication at the new address and track error codes
  errorlevel = !si.i2c_write(170) | errorlevel;        //Send the unlock code and track the error codes
  errorlevel = !si.i2c_write(165) | errorlevel;        //Send the unlock code and track the error codes
  errorlevel = !si.i2c_write(newaddress) | errorlevel; //Send the new address
//  si.i2c_stop();
  return errorlevel;
}

//////////////////////////////////////////////////////////
// Code Example: Read the sensor at the default address //
//////////////////////////////////////////////////////////
void read_the_sensor_example(){
  boolean error = 0;  //Create a bit to check for catch errors as needed.
  int range;

  //Take a range reading at the default address of 224
  error = start_sensor(224);    //Start the sensor and collect any error codes.
  if (!error){                  //If you had an error starting the sensor there is little point in reading it as you will get old data.
    delay(100);
    range = read_sensor(224);   //reading the sensor will return an integer value -- if this value is 0 there was an error
    Serial.print("R:");Serial.println(range);
  }
}

////////////////////////////////////////////////////////////////
// Code Example: Poll all possible addresses to find a sensor //
////////////////////////////////////////////////////////////////
void address_polling_example(){
  boolean error = 0;  //Create a bit to check for catch errors as needed.
  int range = 0;
  Serial.println("Polling addresses...");

  //Walk through all possible addresses and check for a device that can receive the range command and will
  //    return two bytes.
  for (byte i=2; i!=0; i+=2){   //start at 2 and count up by 2 until wrapping to 0. Checks all addresses (2-254) except 0 (which cannot be used by a device)
    error = 0;
    error = start_sensor(i);    //Start the sensor and collect any error codes.
    if (!error){                //If you had an error starting the sensor there is little point in reading it.
      delay(100);
      range = read_sensor(i);   //reading the sensor will return an integer value -- if this value is 0 there was an error
      Serial.println(i);
      if (range != 0){
        Serial.print("Device found at:");Serial.print(i);Serial.print(" Reported value of:");Serial.println(range);
      }
    }
    else{
      Serial.print("Couldn't start:");Serial.println(i);
    }
  }

  Serial.println("Address polling complete.");
}

//////////////////////////////////////////////
// Code Example: Change the default address //
//////////////////////////////////////////////
void default_address_change_example(){
  boolean error = 0;  //Create a bit to check for catch errors as needed.
  int range;

  Serial.println("Take a reading at the default address");

  //Take a range reading at the default address of 224
  error = start_sensor(224);    //Start the sensor and collect any error codes.
  if (!error){                  //If you had an error starting the sensor there is little point in reading it.
    delay(100);
    range = read_sensor(224);   //reading the sensor will return an integer value -- if this value is 0 there was an error
    Serial.print("R:");Serial.println(range);
  }

   Serial.println("Change the sensor at the default address to 222");
  //Change the address from 224 to 222
  error = 0;
  error = change_address(224,222);  //Change the address -- I don't do anything with the error handler at this point but you can if you want.
  delay(200);    //Wait 125ms for the sensor to save the new address and reset

   Serial.println("Take a reading at the new address");

  //Take a range reading at the new address of 222
  error = 0;
  error = start_sensor(222);     //Same as above but at the new address
  if (!error){
    delay(100);
    range = read_sensor(222);
    Serial.print("N:");Serial.println(range);
  }

   Serial.println("Change the sensor back to the default address");

  //Change the address from 222 to 224
  error = 0;
  error = change_address(222,224);
  delay(200);    //Wait 125ms for the sensor to save the new address and reset

}

So i have no idea why this happens .
Any help ?

well, I'VE FOUND THE ERROR! But wtf is this error !? after trimming code out many times finding what addition caused the error. it was line 21 float calibration_factor = -10060;  switching it on/off is the edge of the error appearing !

Believe or don't believe ! the comment causes the error [facepalm]

What version of the IDE are you using? I believe the problem is with the location of the auto generated function prototypes.

It's 1.8.7 - But it's so weird a comment can cause such a thing !

It's not the comment. It's the face that the float is before the include, and that float is where the IDE codes to place the prototypes. Move the include for the rtc to before that float.

move all includes to the top of the file. you make it hard for Arduino builder ino-to-cpp conversion with your style

@Majenko  Thanks for the solution! Now it compiles without errors :) . But the weird thing that removing the comment was resolving the error too! xD

@Majenko Is it terrible if i split my sketch into more than a helper .h file within sketch directory, then include them all in my .ino file?

Weird things happen with the Arduino IDE's prototypes if you're not careful. It's one of the first things I tackled in UECIDE, which always places the prototypes immediately before the first actual function in the code.

It is better to split your code into multiple INO files. The IDE then combines them for you - no need to include them manually.

So, INO not h files ? there could be some interactions between them.

The INO files are only separate to you. To the code it's just one single INO file.

Sorry, I didn't understand you.  I see that there could be 1 .ino file between some .h files at sketch folder, where these are included into .ino file as a header. Is that what you mean?

@Majenko I've just read a thread in arduino forums, It's now more clear to me. I'll figure it out.

@Majenko Hi mister, I've tried to split my code into multi INO files. But the error message returns to appear. I've checked in every INO file : library includes first, then comes defines, then comes global instances and variables.

Make sure that the includes only come at the start of the "main" .INO file - the one that is the name of the sketch.

Thank you very much @Majenko, It works now without any problem. I had before split the includes into files too. Now fixed that and it compiles (y)

I was also getting the same problem,  place the printDateTime function on the first page or the page where the headers and declaration's available
below function
#define countof(a) (sizeof(a) / sizeof(a[0]))
void printDateTime(const RtcDateTime& dt)
{
    char datestring[20];

    snprintf_P(datestring,
            countof(datestring),
            PSTR("%02u/%02u/%04u %02u:%02u:%02u"),
            dt.Month(),
            dt.Day(),
            dt.Year(),
            dt.Hour(),
            dt.Minute(),
            dt.Second() );
    Serial.print(datestring);
}


text:
Measure Sofware Serial write() time
As you probably know, SoftwareSerial uses Interrupts to do some of the timing stuff of the Serial communication.
What I am trying to accomplish is to measure the time that it takes SoftwareSerial.write() to write/send one byte.
Obviously, I started trying with timestamps based on millis(), but found out that SoftwareSerial messes with the millis() timer and it simply doesn't count properly.
I have something like this:
timestamp = millis();
HC12.write(endByte); //HC12 is a SoftwareSerial object

//After sending waits for the answer
while (HC12.available() > 0) {
  byte r = HC12.read();
  if (r == (byte) 254) { //The other HC12 module sends 0xFE
    unsigned long received = millis() - timestamp;
    Serial.println(received);
  }
...

Any suggestion on how I could measure this?
I am trying to implement a half-duplex communication with HC12 433MHz modules and I am testing some theoretical/real timing values for the communication between two boards.

the time is dependent on the baud rate (bits/second) ..... at least 10 bits are sent .... one start bit, 8 data bits and one stop bit ........ the stop bit has to be at least one bit-length, but it could be longer

@jsotola, Hi. Thanks for your help.
Well, I know :-). The thing is, that's theoretical. Also, I want to try with more bytes and I don't think that the timings are exacly the same of calculations based on baud rate.

actually the solution is quite simple ..... the transmitting arduino is actually stand-alone ..... there does not have to be a receiving arduino ........ connect the two arduinos  together using one of the digital pins  ...... the transmitting arduino sets the digital pin, sends software serial byte and clears the digital pin ...... the other arduino measures the time between setting and clearing of the pin .............. you could also time the software serial pin itself

try this .... https://github.com/gillham/logic_analyzer

@juraj, The snippet is now correct. What do you mean the title of the question doesn't match the question?

@jsotola, great idea! Thank you very much.

It is very simple, and you don't need any code to work it out.
SoftwareSerial is completely synchronous (i.e., blocking) when writing.  That means that the amount of time taken to peform the write is the time taken to send the data on the line plus a small function call overhead.
That means the time taken is:
1 / baud * 10 seconds

So at 9600 baud one bit is sent in 1/9600 of a second, and there are 10 bits (1 start, 8 data, and 1 stop bit), so it takes 1/960th of a second.
That's about 1ms per byte, plus a few extra clock cycles for calling the actual functions.
To put it in more detail, when you send a byte this happens:

Set the line level to the start bit level
Wait 1/9600th of a second
Set the line level to the first data bit level
Wait 1/9600th of a second
Repeat 3&4 for the rest of the data bits
Set the line level to the stop bit level
Wait 1/9600th of a second
Set the line level to the idle level

So you have 10 "wait 1/9600th of a second" in total, or a total time of 1/960th of a second.
The same can be said of receiving data. When the start bit arrives it triggers a pin change interrupt.  A synchronous blocking interrupt routine then executes that does the same as above but with reading instead of writing. So that takes about 1ms to execute at 9600 baud - plus some extra to insert the incoming byte into a circular buffer, which you then read from in your sketch.
So the round-trip time of a single byte from unit A to unit B then from unit B to unit A can be estimated as:
1/960 + 1/960 + overheads

That means the minimum time will be 1/480 seconds plus whatever time is spent at the remote unit processing the byte to send data back to you, and a little bit for the function call overheads.
Incidentally, it's that last operation in the interrupt, the "adding the byte to a circular buffer" that means you can't reliably receive at 115200 baud with SoftwareSerial. That takes more time to process than the typical gap between bytes (could be zero - just the width of the stop bit...) that the next byte could have already started to arrive at the GPIO pin before the Arduino is capable of triggering the ISR again, so it misses the start bit.

Hi,
Awesome explanation. Thanks for your time!


text:
Combining code for multiple sensors in a single program
I need to operate 3 different sensors (taken 6 sensors of each type) by Arduino Mega2560 :-

DHT11 (temperature-Humidity sensor)
MQ5 (gas sensor) and
Soil Moisture sensor
{taken 6 of each type (total=18).}

I have managed to run each one of them separately and I don't know how to manipulate the code so they could work all together. My background in coding is basic, so it would be great help if someone can help me for combining these codes.
Here are the sketches:
MQ5 Code:
int sensor=7;
int gas_value;
void setup()
{

pinMode(sensor,INPUT);
Serial.begin(9600);

}

void loop()
{

gas_value=digitalRead(sensor);
Serial.println(gas_value);
}

{other digital pins to be used: D6,D5,D4,D3,D2}
DHT11 Code:
#include <dht.h>
#include <dht.h>
#include "dht.h"
#define dht_apin A0 // Analog Pin sensor is connected to
dht DHT;

void setup(){

  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(1000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    DHT.read11(dht_apin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");

    delay(5000);//Wait 5 seconds before accessing sensor again.

  //Fastest should be once every two seconds.

}// end loop()

{analog pins for other sensors: A1,A2,A3,A4,A5}
Soil_Moisture Sensor Code:
int sensor_pin = A6;
int output_value ;

void setup() {

   Serial.begin(9600);
   Serial.println("Reading From the Sensor ...");
   delay(2000);

   }

void loop() {

   output_value= analogRead(sensor_pin);
   output_value = map(output_value,550,0,0,100);
   Serial.print("Mositure : ");
   Serial.print(output_value);
   Serial.println("%");
   delay(1000);
   }

{Analog pins for other sensors to be used: A6,A7,A8,A9,A10}

your finished program has to have setup() and loop() blocks ..... what do you feel that should happen with the codes in the three setup() blocks?  ..... what do you think that should happen with the code in the three loop() blocks?

All things before void setup() put before one setup() function. All things in void setup() put to the one void setup() - do not duplicate things like #include or Serial.begin(). And things from loop() function put to the loop() function.
It's a good practice to don't use delay() in  loop() when you are processing more things than one. Instead of delay() use millis() to get current uptime and after that compare this uptime to last uptime of check.
I modified your code, so read it and try it.
#include <dht.h>

#define dht_apin A0 // Analog Pin sensor is connected to
dht DHT;

int sensor=7;
int gas_value;

int sensor_pin = A6;
int output_value ;

unsigned long gas_last_time = 0;
unsigned long dht11_last_time = 0;
unsigned long analog_last_time = 0;

void setup(){
  Serial.begin(9600);
  pinMode(sensor,INPUT);
}

void loop(){
  if(millis() - gas_last_time >= 10){
    gas_last_time = millis();

    gas_value=digitalRead(sensor);
    Serial.println(gas_value);
  }

  if(millis() - dht11_last_time >= 5000){
    dht11_last_time = millis();

    DHT.read11(dht_apin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");
  }

  if(millis() - analog_last_time >= 1000){
    analog_last_time = millis();

    output_value= analogRead(sensor_pin);
    output_value = map(output_value,550,0,0,100);
    Serial.print("Mositure : ");
    Serial.print(output_value);
    Serial.println("%");
  }
}

Thank you so much for your precious help, specially in letting me know the basic things you told me via your code. A lot of thanks to you, because of all help by all you guys, I completed my code.(i'm sorry for replying too late from the day of completion of code)

@Deepanshu No problem. :)

In general:
All #defines and #includes get put from all separate sketches, at the top.
Globals and function definitions (except for setup() and loop()) get mixed together below the #defines and #includes.
All code in the separate setup()s get put in the combined setup().
All code in the separate loop()s get put in the combined loop().
You have to be aware that any loop() from the separate programs that include a delay() will likely have to be refactored to use the same kind of scheduled execution method as the Blink Without Delay example from Arduino. delay() stops the whole program while it twiddles thumbs, which means your other sensors aren't being read or managed during that time.

Thank you so much for your precious help. Because of all help by all you guys, I completed my code.(i'm sorry for replying too late from the day of completion of code)


text:
How to multitask while writing on Serial
I am trying to send real-time data taken from an ADC by Arduino Uno (SPI) to Arduino IDE through a USB cable. I found that one byte takes around 70 microseconds when Serial.write() is used at a baud rate of 115200. My question is that if I send 14400 bytes (which would be the maximum limit at this baud rate), can I perform any other tasks? Does Arduino allow multitasking while the serial buffer is busy writing data?

why do you say that 14400 bytes is a limit?

Until you fill the transmit buffer (64 bytes by default but can be recompiled to enlarge it if you need to), Serial.print() or Serial.write() will return immediately. The characters in the buffer will be transmitted by an interrupt service routine, so essentially, the Arduino is double-tasking for that purpose. If the buffer is full when you call Serial.print() or Serial.write() or Serial.print() fills it before having sent all of its characters, those calls block (won't return) until there is buffer-space for their remaining characters.
So yes, you can do other things while the writing happens, as long as you haven't filled the buffer. You can call Serial.availableForWrite() to find out how many characters you can send without blocking.
By the way, at 115200 baud, or 11520 bytes/second, each character should take 1/11520 seconds or 86.8 microseconds, not 70 milliseconds.

Thanks @JRobert. I will use serial.available and find out the time periods taken by serial.write and then I will get back.

I think baud rate specifies bits per second. So, to write a byte, it should take 1/115200*8 seconds, which comes out to be around 70 microseconds which is what exactly I found. Sorry for the typo earlier, I wrote milliseconds by mistake.

But in fact, serial transmission takes 10 or 11 bits (1 start bit, 8 data bits and 1 or 2 stop-bits; 1 is most common) to send an 8 bit byte. So you need to divide by ten instead of by 8.

Yes you are right. I will recheck the time values.

JRobert said Serial.availableForWrite not Serial.available. They are totally different things.


text:
Trouble with reading Bitmaps from SD-Card
I'm having problems with reading a bitmap file with the SD library.
I wrote a small header that reads uncompressed 24-bit bitmap files. It works fine when I try it on Windows 10 MingW with fread() instead of SD.read().
On my UNO it only reads the correct offset address, the other parts are garbage.
For a pure red 1x1 px bitmap I get the following expected output on Windows with MingW:
Fname: ..\rot.bmp
Offset: 00000036
W * H: 1 * 1
Bit# 24
Cmp: 0
ArraySize: 1
---------------------------
RGB: ff0000

Arduino outputs:
Fname: rot.bmp
Offset: 00000036
W * H: 0 * 2304
Bit# 58
Cmp: 0
ArraySize: 8
---------------------------
Error while reading BMP file

bmp.hpp
#ifndef BMP_HEADER
#define BMP_HEADER

#if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
#include <SD.h>
#include<stdint.h>
#define BYTE uint8_t
#define WORD uint16_t
#define DWORD uint32_t
#define LONG int32_t
#else
#include<stdlib.h>
#include<windows.h>
#endif // defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
#pragma pack(2)
typedef struct
{
  BYTE B;
  BYTE G;
  BYTE R;
} pixel;

typedef struct
{
  WORD bfType;
  DWORD bfSize;
  DWORD bfReserved;
  DWORD bfOffset; //offset to byte array
} bfheader;

typedef struct
{
  DWORD biSize; //size of this header
  LONG biWidth; //image width
  LONG biHeight;//image height
  WORD biPlanes;
  WORD biBitCount; //color depth in bit per pixel
  DWORD biCompression; //0 for none(RGB mode)
  DWORD biSizeImage; //size of image in byte; may be 0 if biCompression is RGB
  LONG biXPelsPerMeter;
  LONG biYPelsPerMeter;
  DWORD biClrUsed; //palete stuff
  DWORD biClrImportant; //more palete stuff
} biheader;

//returns BGR array of bitmap
//header and biheader are assumed to be allocated upon execution
//returns null if unsuccessful
inline pixel* readBMP(const char* filename, bfheader* header, biheader* infoheader)
{
    #if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
    SDLib::File f = SD.open(filename);
    if(!f) return NULL;
    f.read((uint8_t *)header, sizeof(bfheader)); // read the 14-byte file header
    f.read((uint8_t *)infoheader, sizeof(biheader)); //read the 40-byte info header
    #else
    FILE* f = fopen(filename, "rb");
    if(f == NULL) return NULL;
    fread(header, sizeof(bfheader), 1, f);
    fread(infoheader, sizeof(biheader), 1, f);
    #endif //defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
  if(infoheader->biCompression != 0 || infoheader->biBitCount != 24) //if the file is not RGB encoded or if its not 24bit
  {
    #if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
    f.close();
    #else
    fclose(f);
    #endif // defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
    return NULL;
  }
  int size = (int) infoheader->biSizeImage/sizeof(pixel); //get byte size of pixel array
  pixel* data = (pixel*) malloc(sizeof(pixel)*size); // allocate
  #if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
    f.seek(header->bfOffset); //set file cursor to starting address of RGB array
    f.read((uint8_t *)data, sizeof(uint8_t)*size); // read the rest of the data at once
    f.close();
  #else
    fseek(f, header->bfOffset, SEEK_SET);
    fread(data, sizeof(pixel), size, f);
    fclose(f);
  #endif //__arm__
  return data;
}
#endif //BMP_HEADER

readbmp_test.ino
#include<arduino.h>
#include <SPI.h>
#include "bmp.hpp"

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");

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

void loop()
{
  char debug[160];
  char rgbdata[8];
  const char* const files[] = {"rot.bmp", "gruen.bmp", "blau.bmp"};
  int files_len = 3;
  bfheader header;
  biheader infoheader;
  pixel* image;
  for(int i=0; i<files_len; i++)
  {
    image = readBMP(files[i], &header, &infoheader);
    Serial.println("----------------------------");
    sprintf(debug,  "Fname: %s\n"
                "Offset: %08lx\n"
                "W * H: %ld * %ld\n"
                "Bit# %u\n"
                "Cmp: %lu\n"
                "ArraySize: %lu\n"
                "---------------------------\n",
                  files[i],
                  header.bfOffset,
                  infoheader.biWidth, infoheader.biHeight,
                  infoheader.biBitCount,
                  infoheader.biCompression,
                  infoheader.biSizeImage/sizeof(pixel));
    Serial.print(debug);
    if(image != NULL)
    {

      for(unsigned j=0; j<infoheader.biSizeImage/sizeof(pixel); j++)
      {
        sprintf(rgbdata, "%02x %02x %02x", image[j].R, image[j].G, image[j].B);
        Serial.println(rgbdata);
      }
    }else{
        sprintf(debug, "Error while reading BMP file\n");
        Serial.print(debug);
    }
    free(image);
  }
}

main.cpp //MingW Windows Test
#if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)  //arduino compiler wants to run this main?
#else
#include<stdio.h>
#include "bmp.hpp"

int main(const int argc, const char** argv)
{
    if(argc < 2) return -1;

    bfheader header;
    biheader infoheader;
    for(int i=1; i<argc; i++)
    {
        pixel* image = readBMP(argv[i], &header, &infoheader);
        if(image != NULL)
        {
            printf("Fname: %s\n"
                    "Offset: %08x\n"
                    "W * H: %d * %d\n"
                    "Bit# %d\n"
                    "Cmp: %d\n"
                    "ArraySize: %d\n"
                    "---------------------------\n",
                    argv[i],
                    header.bfOffset,
                    infoheader.biWidth, infoheader.biHeight,
                    infoheader.biBitCount,
                    infoheader.biCompression,
                    infoheader.biSizeImage/sizeof(pixel));
            for(int j=0; j<infoheader.biSizeImage/sizeof(pixel); j++)
            {
                printf("RGB: %02x%02x%02x\n", image[j].R, image[j].G, image[j].B);
            }
        }else{
                printf("Error while reading BMP file\n");
                return 1;
        }
        free(image);
    }
    return 0;
}
#endif

I'm really stuck on this, I actually rewrote it a couple times already.
I would really appreciate some help.

print out the number of bytes read with file.read (return value). try to use readBytes instead of read if the count of read bytes doesn't match the expected size

@Juraj I tried with with readBytes and read. Same result: The first read returns the expected 14 bytes. The second only returns 2 instead of the expected 40.

print the structure as bytes with println(b, HEX), to see the raw bytes to check their position in struct fields

How would I do so? Serial.println(*infoheader, HEX); results in 'HardwareSerial::println(biheader&, int)'

I tried  withfor(int i=0; i<sizeof(biheader); i++) The output seems to match the hex dump of the file. I put a a hexdump of the bitmap and the output on Pastebin

it could be a problem of printf. you have %d and that reads only two bytes on Arduino. print the values without sprintf as Serial.println(number)

Hint: Start by correcting the header read. The sizeof is wrong. Use sizeof the struct and not the pointer. Use the same sizeof for both variants.

@MikaelPatel thanks for your input. I fixed that part, but I still have problems.

@Juraj Your tipp with the sprintf was pretty good. I turned on all warnings during compile and saw that the datatypes didn't match the format strings. I fixed that and now my header information is displayed correctly. There is sadly still a problem left as the pure red bitmap displays false pixel values: sprintf(rgbdata, "%02x %02x %02x", image[j].R, image[j].G, image[j].B);         Serial.println(rgbdata); displays: c5 00 00 dispite the bitmap not containing C5 at all.

f.read((uint8_t *)infoheader, sizeof(infoheader));
should be
f.read((uint8_t *)infoheader, sizeof(biheader));
the size of the variable (pointer) is only 2. you want to read 40 bytes of biheader struct
and
f.read((uint8_t *)data, sizeof(uint8_t)*size)
should be
f.read((uint8_t *)data, sizeof(pixel)*size)

The next problem is %d and %x in sprintf. %d and %x read two bytes on Arduino, not 4, not 1. Print the values without sprintf as Serial.println(number)

Oh wow, thanks for pointing that out. It reads the expected amount of bytes. However he output is still wrong. Fname: rot.bmp
Offset: 00000036
W * H: 0 * 1
Bit# 0
Cmp: 1
ArraySize: 0

Hey @juraj I answered on your comment on the main post.

Hey @Juraj, I modified the format string so the correct datatype is expected, lu for uint32_t etc. For the header that works fine now. Pixeldata is still wrong. I followed your advise and tried displaying the Pixeldata using raw Serial.print. Problem still persists. `Fname: rot.bmp
Offset: 00000036
W * H: 1 * 1
Bit# 24
Cmp: 0
ArraySize: 1
58 0 0` is my current output

@MatC, did it help?


text:
Method to iterate over the bits in a byte sent over serial
In my current project which integrates Arduino/avr IC with Raspberry-Pi, and each communicating via serial, I'm looking to send a byte of data to the Arduino from the RPi, which then would be iterated over, bit by bit.
Each bit represents a setting. If a bit is 0, then the Arduino would turn that respective device off, if a bit is 1, then Arduino would turn that respective device on. For example, a byte such as: 01100110, would mean the Arduino would have to turn four devices off, and four devices on.
I'm looking for information on how to take a byte over serial, and iterate over that byte bit by bit, and have the Arduino make decisions based on the value of each bit.
Excuse my post for lacking much technical detail, I'm refraining from using terms that are still very vague to me.
Regards.

your question is a C++ programming question  ..... it is not related to the Arduino  specifically

In all the examples below, value is the value of the byte
LSB -> MSB - so 00001111 would turn ON the first 4 devices and turn OFF the last 4
for(int i = 0, mask = 1; i < 8; i++, mask = mask << 1)
{
    if (value & mask)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

Alternatively, you can do the following, but value will be altered
for(int i = 0; i < 8; i++, value = value >> 1)
{
    if (value & 1)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

Working the other way around in each byte:
MSB -> LSB - so 00001111 would turn OFF the first 4 devices and turn ON the last 4
for(int i = 0, mask = 128; i < 8; i++, mask = mask >> 1)
{
    if (value & mask)
    {
        // bit "i" is on
    }
    else
    {
        // bit "i" is off
    }
}

Alternatively, you can do the following, but value will be altered
for(int i = 0; i < 8; i++, value = value << 1)
{
    if (value & 128)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}


text:
map() function with stepper motor
I am controlling a stepper motor with a potentiometer and I am trying to map the potentiometer values (0-1023) to the stepper motor steps (200). I only want this stepper motor to turn 1 (one) rotation from 0 on the potentiometer (0 steps on the stepper, yes I have a micro switch to mark 0) all the way to 1023 on the potentiometer (200 steps on the stepper). But I have trouble understanding the map() function.
potValue = map ( potPinValueRead,0,1023,0,200) ;

As per the Arduino example:
map(value, fromLow, fromHigh, toLow, toHigh)

I think I am interpreting the map() function wrong
UPDATE:
Even with the map() values the stepper still turns 5 (and a bit (1023/200) ) rotations and not just 1 (one) rotation.
Here is my code:
#include <Stepper.h>
#define STEPS 200
Stepper stepper(STEPS, 7, 8, 9, 10);
int previous = 0 ;
int potData = 0 ;
int potPin = A0 ;

int outputA = 7 ;  //Stepper Output
int outputB = 8 ;  //Stepper Output
int outputC = 9 ;  //Stepper Output
int outputD = 10 ; //Stepper Output

int limitSwitch = 2 ; //Limit switch (home switch) is on pin 2

void setup() {
   Serial.begin(9600) ;
   stepper.setSpeed(10);
   pinMode ( outputA, OUTPUT ) ;
   pinMode ( outputB, OUTPUT ) ;
   pinMode ( outputC, OUTPUT ) ;
   pinMode ( outputD, OUTPUT ) ;
   pinMode ( limitSwitch, INPUT ) ;

   //Turn the motor until the limit scwitch is triggered
   while ( digitalRead(limitSwitch) == 0 )
    {
      stepper.step(30);
    }
   //Stop turning when the limit switch has been triggered
   while ( digitalRead(limitSwitch) == 1 )
    {
      stepper.step(0);
    }
   //Turn 5 steps away from the limit switch to un-trigger
   //This is also the "home" position
   stepper.step(-5);
 }

 void loop() {
   int potData = map(analogRead(potPin),0,1024,0,200);

   if (potData>previous)
    {
      stepper.step(5);
    }
   if (potData<previous)
    {
      stepper.step(-5);
    }

  previous = potData;
}

I have updated my post and added code

you have misdiagnosed the problem ...... write a sketch that moves 200 steps, waits for a second, then repeats .... no potentiometer code, no limit switch code ... do you get one revolution? ..... you have to get 1 rev per 200 steps  before you do anything else

I did as you suggested and I get 1 revolution for 200 steps

now you are certain that the hardware works correctly ..... that means that the problem is inside your program ...... look at your loop() code  ..... how many steps will the motor move if you change the potentiometer by one "position"?

@jsotola : it turns out the Arduino I was using was defective. I bought 20 of them and it turns out 4 of them had the same issues (the supplier got it from you know where). I returned all for genuine Arduino's. Anyway, everything is working fine now. Thank you for your help.


text:
Do you need an ESC to run this brushless DC motor with Arduino Uno?
This is the motor:
https://www.aliexpress.com/item/Wholesale-JGA25-2418-8-5-1977-rpm-Electric-Motors-Brushless-Motor-High-Torque-Speed-Controlled-DC/32360228129.html
I'm hooking it up to the arduino as described and giving the PWM outputpin analogWrite functions, but it's not working.

No. It has an ESC built in.
You just provide power and a PWM signal, and optionally a direction signal.
To test:

Connect red to +12V.
Connect black to 12V GND and to Arduino GND
Connect white to D5
analogWrite(5, 128);

Stupid question, but why does the motors have to connect to Arduino GND as well as the 12V GND?

@Ary https://majenko.co.uk/blog/importance-sharing-grounds


text:
Button for Delay Select
My target is to make an Arduino system that is able to change modes with different delays by pushing a button. For example, if I pressed the button, it will go into mode 1 with loop 1 that has a 30s delay. If I pressed it one more time, it will go to mode 2 with with loop 2 that has a 1 min delay, etc. The important thing is that mode 1 should be breaked when the push button pressed.
The code below solved part of the problem. However, LEDs are only constant ON, they are not blinking for a certain time then it turned either on-off within the mode when the push button pressed.
int b =3;int rl= 5;int gl=6;
int yl=7; int s=0; int o=0;
 int bp =0;

void setup() {
  // put your setup code here, to run once:
pinMode(b,INPUT);
pinMode(rl,OUTPUT);
pinMode(gl,OUTPUT);
pinMode(yl,OUTPUT);

 digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
}

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

bp=digitalRead(b);
if (bp==1){
  delay(50);
  bp=digitalRead(b);
  if (bp==0){
    s=o+1;}}
    else{
      delay(100);}
      switch(s){
        case 1:
        digitalWrite(rl,HIGH);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
o=s;
break;

case 2 :
digitalWrite(rl,LOW);
digitalWrite(gl,HIGH);
digitalWrite(yl,LOW);
o=s;
break;

case 3:

digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,HIGH);
o=s;
break;
default:

digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
o=0;
break;}}

S1 is responsible to activate D12 to be constant ON (when it’s pressed once) which lead UNO2 to be powered then blink the right LED ON (1min) OFF(4Hr), (pressing it twice should turn D12 OFF (optional)). The same thing with S2, when it’s pressed once it should first disable D12 and activate D11 instead, powering UNO3, blinking the left LED ON(30S), OFF (4Hr).
In addition, blinking on() off() repeatedly is needed (unless action break/occur, ex: pressing S1 or S2).
About S1 and S2. The LED on D12 will flash ON for 1 minute then turn off for 4 hours. After the 4 hours, the LED on D12 will flash ON again for 1 min then turn off for 4 hours again & again...as an infinite loop. With S2 The LED on D11 will flash ON for 30 seconds then turn off for 4 hours. After the 4 hours, the LED On D11 will flash ON again for 30 s then turn off for 4 hours again and again as an infinite loop.

I got tired with no result>< what does this even mean? What have you tried so far? Have you written ANY code at all?

state machine triggered by interrputs

In response to your comment on Matej's answer @Ibrahim.M: "I wish I can abbreviate it with only one UNO that able to do the same task by using programming.". You can do this with just one Uno.
I would start by detecting the button presses and debouncing them. This is easy to do using the Bounce2 library. You can use the button presses to start timers which will turn the LEDs On and Off.
EDIT
To make an LED flash on and off, and to keep time, you can use the millis() function. I started with the BlinkWithoutDelay tutorial, and came up with the following sketch. It only has one timer / LED flasher, but there is enough information in the sketch to figure out how to make the second timer / LED flasher.
#include <Bounce2.h>

byte led1State = LOW;
byte timer1Active = 0;
const byte led1Pin = LED_BUILTIN;
const byte buttonPin1 = 6;
const byte buttonPin2 = 7;
unsigned int timer1Counter = 0;
const unsigned long debouncerInterval = 50;
const unsigned long oneSecond = 1000;
unsigned long previousMillis = 0;

Bounce debouncer = Bounce();
Bounce debouncer2 = Bounce();

void setup(){
  Serial.begin(9600);
  debouncer.attach(buttonPin1, INPUT_PULLUP);
  debouncer.interval(debouncerInterval);
  debouncer2.attach(buttonPin2, INPUT_PULLUP);
  debouncer2.interval(debouncerInterval);
  pinMode(led1Pin, OUTPUT);
}

void loop(){

  unsigned long currentMillis = millis();

  // 4 hour, 30 second timer.
  if((currentMillis - previousMillis >= oneSecond) && (timer1Active == 1)){
    previousMillis = currentMillis;
    timer1Counter++;
    if(timer1Counter < 31){
      //if(led1State == LOW){
        led1State = HIGH;
      //}
      //else{
        //led1State = LOW;
      //}
      digitalWrite(led1Pin, led1State);
    }
    else if(timer1Counter == 31){
      digitalWrite(led1Pin, LOW);
    }

    // 60 sec X 60 min X 4 hours + 30 seconds.
    if(timer1Counter > 14430){
      timer1Counter = 0;
    }
  }

  // Button 1
  if(debouncer.update()){
    if(debouncer.read() == 0){
      Serial.println("Start 30 second ON, 4 hour OFF timer.");
      timer1Active = 1;
      timer1Counter = 0;
    }
  }

  // Button 2
  if(debouncer2.update()){
    if(debouncer2.read() == 0){
      Serial.println("Start 1 minute ON, 4 hour OFF timer.");
      timer1Active = 0;
      digitalWrite(led1Pin, LOW);
    }
  }

}

Based on this part of your last comment "I’ve a trick! ‘const unsigned long oneSecond = 1000;’ should be edited to ‘const unsigned long oneSecond = 10;’ this make the led be as a constant ON.", it sounds like you want the LED to remain ON constantly for the 30 or 60 seconds. I have "commented out" 5 lines of the above sketch that will make this happen.

Matej and VE7JRO you are a great persons, thank you so much.

Do not use delay but millis().
Example:
#define BTN 2
#define MAX_MODE 1   //2 modes

const unsigned int times[] = {1000, 2000};

unsigned int time = times[0];

unsigned long btn_tm = 0;
unsigned long l_time = 0;

byte mode = 0;

void setup(){
  Serial.begin(9600);
  pinMode(BTN, INPUT);
}

void loop(){
  if(digitalRead(BTN) == 1 && millis() - btn_tm > 200){
    btn_tm = millis();
    mode ++
    if(mode > MAX_MODE) mode = 0;
    time = times[mode];
 }
  if(millis() - l_time >= time){
    l_time = millis();
    if(mode == 0) Serial.println("mode 0");
    if(mode == 1) Serial.println("mode 1");
 }
}

Read it and try it.

Thank you Matej. The code has an error related to this part: ' if(mode > MAX_MODES) mode = 0; ' , kindly, how can I add LEDs as an output for each mode pls?

Is it possible to make the code inside the link take place each case mentioned in my topic code? where then  each case will has its own time [https://www.arduino.cc/en/tutorial/BlinkWithoutDelay]

@Ibrahim.M I fixed this error, it was wrong name of variable. If you want to use code from the link, remove this part from code if(millis() - l_time >= time){ l_time = millis(); if(mode == 0) Serial.println("mode 0"); if(mode == 1) Serial.println("mode 1"); }  and instead of it, put inside if(mode == 0){  } code which is in the loop() from your link.

@Ibrahim.M And for your first comment, simply put pinMode() to the setup() above setup put bool state = 0; and into a if(mode == 0){ }  put digitalWrite(LED, state); state = !state;

Thank you Matej, I appreciate it. Unfortunately, my problem is still not solved. I assume that uno’s IC cannot do what I want ( ex; yellow button activates pin9 1min each 6 hr wherase blue button activate pin10 30 sec each 6hr ).

I’ve just uploaded a picture has a long tail circuit diagram at this link: https://i.stack.imgur.com/Cg3k0.jpg . I wish I can abbreviate it with only one UNO that able to do the same task by using programming.

@Ibrahim.M Write 3 codes for 3 unos and I will help you to merge these codes.


text:
RC-oscillator calibration in real time
This pesky watchdog RC oscillator is at the limit of its 10% tolerance already at room temperature. i was looking to bringing it to more like 5% (it stems from an internak 128 kHz RC oscillator) and the whole -40 ... 125 deg Celsius operating range. Can this reliably be done by reading the temperature of the MCU and applying an algorithm ? Any such working algorithm ?
The calibration is actually the adjusting of the number of cycles (of say, 125ms) the watchdog will run for. i.e. for 12.5 seconds I would run the watchdog timer 100 times, nominally. How do I temperature-compensate the 100 figure ?

You could run a calibration routine whereby you run a timer at the same time as the watchdog timer and then compare the difference between the two... For example run the timer for 1 second and count how many times the watchdog interrupts in that period.

I think that just measuring the actual frequency at room temperature will be enough to calibrate to a reasonable amount. I don't think you'd get much more precision using temperature dependent calibration. If you want more precision I'd suggest adding an RTC. For example the DS3231.

Your description is pretty detailed but you've missed to tell, which device you are talking about.
I assume you are talking about the ATmega 328P in an Arduino Uno.
AFAIK you can only calibrate the so called Calibrated internal RC oscillator, which is used for the main operations.
You cannot calibrate the Internal 128kHz RC oscillator from the watchdog.
I think you might have some overhead from your sleep/wake cycles.
Instead of sleeping 100 times to get from 125ms to 12.5s you could sleep for 8s + 4s + 0.5s. Thus sleeping only 3 times. Which might save you some battery life.

We've been using the WDT delta as a temperature sensing method:
https://thecavepearlproject.org/2019/02/25/no-parts-temperature-measurement-with-arduino-pro-mini-to-0-005c-or-better/
Point being that once you have those calibration constants, you could use them use them to correct for WDT variation. OR you might be able to get away with a much shorter  interval than the 1sec we use, with the micros reading as your WDT correction factor more directly.

"The other big limitation is that you can only do this trick on a voltage regulated system, because RC oscillators are affected by the applied voltage," - this is a nice finding from that article, good thing I have ditched the WDT; otherwise it seems to be concerned with that Silabs temperature sensor.


text:
Can I power a Wemos D1 R2 via the VIN and GND pins?
Can I power a Wemos D1 R2 via the VIN and GND pins?
If so, at what voltage?

Wemos D1 R2 has on-board regulator with input from power jack and Vin pin. The regulator is for 9 to 24 V.


text:
My software serial code won't work at > 4800bps
I've put together a simple software serial (send-only) implementation for use on my attiny8[45] microcontrollers.  I realize that there are more efficient USI-based implementations out there; this was mostly an educational exercise.  The code uses TIMER0 in CTC mode to time the sending of bits on an available output pin.
It works fine from 300bps up to 4800bps, but anything faster than that just results in garbage.
The complete code is at the bottom of this answer.    The following settings all work correctly:

4800bps
#define BPS 4800
#define SCALE_FLAG 1
#define SCALE_VAL 1

2400bps
#define BPS 2400
#define SCALE_FLAG 2
#define SCALE_VAL 8

1200bps
#define BPS 1200
#define SCALE_FLAG 2
#define SCALE_VAL 8

300bps
#define BPS 300
#define SCALE_FLAG 3
#define SCALE_VAL 64

While this fails:

9600bps
#define BPS 9600
#define SCALE_FLAG 1
#define SCALE_VAL 1

Because everything other than 9600bps works I'm tempted to think that my code is correct, and yet I expect that I should be able to achieve 9600bps with these microcontrollers.
Are there any obvious bugs in this code? I think that's the most likely explanation, but after poking at this for a couple of days I'm not seeing it.

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>
#include <string.h>

#define BPS 9600
#define SCALE_FLAG 1  // This is the value that goes in the TCCR0B register
#define SCALE_VAL 1   // This is the divisor selected by SCALE_FLAG

#define TXPORT PORTB
#define TXDDR DDRB
#define TXPIN PORTB0

#define TICKS_PER_BIT (F_CPU/BPS/SCALE_VAL)
#define mS_PER_BIT (1000000/BPS/1000)
#define uS_PER_BIT ((1000000 / BPS) - (1000 * mS_PER_BIT))

typedef struct SERIAL_PORT {
    uint8_t data;
    uint8_t index;
    uint8_t busy;
} SERIAL_PORT;

void millis_init();
uint32_t millis();

void serial_init();
void serial_putchar(char c);
void serial_print(char *s);
void serial_println(char *s);
void delay(uint32_t m);

volatile SERIAL_PORT port;
volatile uint32_t _millis,
         _micros = 1000;

int main() {
    millis_init();
    serial_init();
    while (1) {
        serial_println("hello world");
        delay(500);
    }
}

void delay(uint32_t m) {
    uint32_t t_start = millis();
    while (millis() - t_start < m);
}

void millis_init() {
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        _millis = 0;
    }
}

uint32_t millis() {
    uint32_t x;
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
      x = _millis;
    }
    return x;
}

void serial_init() {
    DDRB |= 1<<TXPIN;       // Set TXPIN as an output
    TXPORT |= 1<<TXPIN;     // Set TXPIN high (serial idle)
    TCCR0A = 1<<WGM01;      // Select CTC mode
    TCCR0B = SCALE_FLAG;    // Set clock scaler
    OCR0A = TICKS_PER_BIT;  // Set CTC target value
    TIMSK0 |= 1<<OCIE0A;    // Enable compare match interrupt
    sei();
}

void serial_putchar(char c) {
    while (port.busy);
    port.data = c;
    port.index = 0;
    port.busy = 1;
}

void serial_print(char *s) {
    while (*s) serial_putchar(*s++);
}

void serial_println(char *s) {
    serial_print(s);
    serial_putchar('\r');
    serial_putchar('\n');
}

ISR(TIM0_COMPA_vect) {
    if (port.busy) {
        switch(port.index) {
            case 0:
                // send start bit
                TXPORT &= ~(1<<TXPIN);
                break;
            case 9:
                // send stop bit
                TXPORT |= (1<<TXPIN);
                port.busy = 0;
                break;
            default:
                // send data bit
                if (port.data & 1) {
                    TXPORT |= 1<<TXPIN;
                } else {
                    TXPORT &= ~(1<<TXPIN);
                }
                port.data >>= 1;
                break;
        }
        port.index++;
    }

    _millis += mS_PER_BIT;

    if (uS_PER_BIT > _micros) {
        _millis++;
        _micros = 1000;
    } else {
        _micros -= uS_PER_BIT;
    }
}

What is your clock frequency?

Sorry, I should have mentioned.  The attiny84 is currently running at 1Mhz.

Have you considered that you just don't have enough time to run your ISR at that speed? Simplify it (remove the millis stuff) and see if it improves.

...and if I set the clock frequency to 8Mhz instead, it starts working. I suspect you are correct.

Well for 9600 at 1MHz you have 104 ticks per bit. That's the number of clock cycles you have to git your ISR into, and that ISR compiles to around 126 clock cycles total (I didn't follow the branches, just counted the instructions).

You should move your comments into an answer, because (a) you took the time to look at it, (b) you were spot on, and (c) you even beat me to the cycle counting, which is what I was doing just now :)

At 1MHz and 9600 baud, you have a total of 104 clock cycles available to run your interrupt routine in.  A quick count up of the assembly instructions generated comes to more than that (around 126 at first glance), so you can't fit it into the time.
As a result, your baud rate will actually be lower than 9600, and the chip will be completely starved of clock cycles for doing anything in your main loop.


text:
STM32F103C8 - Arduino Mega FAST MODE(400000L) I2C communcation not working
I'm trying to connect a stm32F103C8 board (master) to an Arduino Mega (slave) over I2C. I have a master and slave program which runs perfectly fine when the clock frequency for I2C communication is set to standard (100000L) which is default.
I wanted the communication to happen a bit faster. So I changed the clock frequency to fast mode i.e., 400000L. I am seeing some weird behavior.
I can send data from master to slave (I can see the data appearing on slave) but when the master requests data from the slave, I don't receive any data on master.
I have tried the same code out on an Arduino Uno (master) and Mega (slave). The code works fine for both standard and fast mode.
I run the code in standard mode by commenting the following line in the master code.

    Wire.setClock(400000L);
Here's the code I have for the Master and Slave:
//Master Code

#include <Wire.h>

int data = 1;
void setup() {

  Wire.begin();
  Wire.setClock(400000L);
  Serial.begin(9600);
}
void loop() {
  Wire.beginTransmission(9);
  Wire.write(data);
  Wire.endTransmission();

  Wire.requestFrom(9, 1);
  int x = Wire.read();
  Serial.print(x);
  delay(500);

}

//Slave Code

#include <Wire.h>

int send_data = 1;
void setup() {

  Serial.begin(9600);

  Wire.begin(9);

  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}
void requestEvent()
{
  Wire.write(send_data);
}

void receiveEvent(int bytes) {
  int x = Wire.read();
  Serial.println(x);
}
void loop() {
delay(500);
}

I'm having hard time understanding what's causing the issue. Please help me make sense as to why it's doing this and how I can resolve it.

try setting the i2c clock speed in the slave alsp

tried it. it didn't work.

Please add information about the wiring, wire length, common ground, power source, pullup resistors, etc.


text:
Find vehicle movement by IMU and GPS
I'm using MPU9250 which has both accelerometer and gyroscope in a vehicle. What I want is to just know that if the vehicle is currently moving or not. I searched and find out that I can't get velocity easily so I skipped that but I was wondering how can I found movement with an IMU.
Edit:
As @Duncan said, it seems that it cannot be examined with only IMU. I also have a GPS sensor in my device and having the speed value from GPS but it is not very accurate. For example, if the vehicle is stopped for 5 minutes I get variable speeds between 0 to 10.0 kmph and on the other hand getting the location as lat/long has about 20 meters error. So I can't really rely on it. I was wondering can I combine both GPS and IMU to find out if it is really moving or not?
One solution that I came was relying on GPS speed but for spikes just check the accelerometer variations and if it is beyond a threshold, it means that it actually moved.

You can't measure velocity with an accelerometer and gyroscope.There is no way to tell if you are sitting still or traveling on a smooth road at 200kph when you start taking readings. Vibration is the only thing you can measure, and a parked car with a rough idle might show more vibration than a smoothly running car traveling at 100kph. There is really no way to tell.

@DuncanC Thanks, I've edited the question.

You noted that your goal is to determine whether or not a vehicle is in motion. Because you are trying an IMU, I assume the device that needs to know this is on-board the vehicle.
There are many complicated ways to know this, such as using the acceleration data from the IMU to perform Inertial Dead Reckoning, this has the problem of temporal drift. A GPS has the issue of needing it's speed data to be filtered a bit to get rid of high-speed spikes.
But -- if you just need to know if the vehicle is moving or not, and if the vehicle has wheels, you can use an light detector, such as an IR emitter and IR receiver pair, along with a slitted disc attached to the wheel, and simply count when the last time the receiver was activated -- if beyond some threshold of time, then you assume the wheel is not turning, and thus that the vehicle is not moving. Or perhaps just use a light sensor and paint white and dark patterns on the wheel.
Or put a magnet on the wheel and place a hall effect sensor (magnet sensor) near where the magnet will pass. Count the pulses from the hall effect sensor.
If the vehicle is not a wheel-based vehicle, then you may have to rely on GPS or some other method, however.

Unless you know for certain that the vehicle is stationary when recording begins, you don't have a frame of reference for Inertial Dead Reckoning. You can't know if the vehicle is stationary or traveling at 100kph, as I mentioned in my comment. Also, with typical low cost accelerometer and gyroscope units, measurements are not accurate enough, and drift quickly swamps actual velocity calculations.

Indeed -- which is why my answer steered away from that and toward something more concrete.

You are right but, I can't add sensors. I don't need accurate accuracy and I need to solve this problem with only IMU and GPS.


text:
ATmega328p keeps restarting
When I was programming an arduino uno with atmel studio via usb cable, everything worked fine. Now I am trying to upload a code via usbasp programmer, it works, whereas arduino keeps restarting and L labelled pin flashes even when I have not activated it by code. After a bit searching I've found that,I should unprogram watchdog timer by adding this command:
C:\Users\Eldar>avrdude -c usbasp -p m328 -P COM5 -b 19200 -U lfuse:w:0xEF:m -U hfuse:w:0xD9:m
output of that:
 avrdude: warning: cannot set sck period. please check for usbasp firmware update. avrdude: AVR device initialized and ready to accept
    instructions Reading |
    ################################################## | 100% 0.03s avrdude: Device signature = 0x1e950f avrdude: reading input file
    "0xEF" avrdude: writing lfuse (1 bytes): Writing |
    ################################################## | 100% 0.01s avrdude: 1 bytes of lfuse written avrdude: verifying lfuse memory
    against 0xEF: avrdude: load data lfuse data from input file 0xEF:
    avrdude: input file 0xEF contains 1 bytes avrdude: reading on-chip
    lfuse data: Reading |
    ################################################## | 100% 0.01s avrdude: verifying ... avrdude: 1 bytes of lfuse verified avrdude:
    reading input file "0xD9" avrdude: writing hfuse (1 bytes): Writing
    | ################################################## | 100% 0.02s
    avrdude: 1 bytes of hfuse written avrdude: verifying hfuse memory
    against 0xD9: avrdude: load data hfuse data from input file 0xD9:
    avrdude: input file 0xD9 contains 1 bytes avrdude: reading on-chip
    hfuse data: Reading |
    ################################################## | 100% 0.02s avrdude: verifying ... avrdude: 1 bytes of hfuse verified avrdude:
    safemode: Fuses OK avrdude done.  Thank you.

I changed  0xD9 to 0xC9 but it`s still the same.Moreover,when i try to program arduino with usb cable again,avrdude gives this error:
avrdude.exe: stk500_getsync(): not in sync: resp=0x00
avrdude.exe done.  Thank you.

This is my code that I try to upload just for testing
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
    DDRD |= 0B11111111;
    DDRB |= 0B11111111;
    while(1)
    {
    PORTD |= 0B00110000;
    PORTB |= 0B00110000;
    _delay_ms(1000);
     PORTD ^= 0B00000000;
     PORTB ^= 0B00000000;
    }
}

Ive also tried unprogram watchdog timer inside the program itself,its still the same.There are attempts below.
Attempt1
#define F_CPU 16000000UL
    #include <avr/io.h>
    #include <util/delay.h>
    #include <avr/wdt.h>
     int main(void)
    {
    MCUSR = 0;
    wdt_disable( );
     while(1)
     {
        //nothing
     }
     }

Attempt2
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/wdt.h>
 int main(void)
{

    wdt_reset();
     MCUSR=0;
     WDTCSR|=_BV(WDCE) | _BV(WDE);
     WDTCSR=0;
     while(1)
     {
        //nothing
     }
     }

Also,why it does not work when i configure the chip with avrdude directly via command line either?

Professional programs always have the watchdog enabled. The correct fix is to write to the relevant watchdog refresh register once from the main while(1) loop. For debug build, you can disable the watchdog. But it's good to have even then, if you can set it to freeze upon single step debugging, because it will expose timing problems in your program.

(But then again, Ardunio was never meant to be used for non-hobbyist purposes)

Could you suggest relevant code for watchdog refresh register once from the main while(1) loop,because Ive tried these(in the below comment),but its still the same


text:
Arduino SIM5320e HTTP GET request to 000webhost.com
Im having trouble getting a successful HTTP GET request to a domain under 000webhost.com
I am trying to do a GET request which sends data to a php file on my domain and save it to MySQL database. I also did this first on my browser and it works fine so I don't think there are problem in my php file.
MY DOMAIN: wastedb.000webhostapp.com
But if I try to send a request to dweet.io, it works as expected.
I am using a modified version of Adafruit_FONA library and will post the code snippet and response from serial monitor below.
Here are the parameters that I used for the WORKING GET request:
Host Address: www.dweet.io
Host: dweet.io
Response from Serial monitor for dweet.io (working):
---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="www.dweet.io",80,1
<--- OK
---> AT+CHTTPSSEND=64
<--- >
---> GET /dweet/for/gearhead?hello=world HTTP/1.1
Host: dweet.io

<--- OK
---> AT+CHTTPSSEND
<--- OK
<--- +CHTTPSSEND: 0
---> AT+CHTTPSRECV?
<--- +CHTTPSRECV: LEN,361
---> AT+CHTTPSRECV=361
<--- OK
+CHTTPSRECV: DATA,361
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Date: Wed, 30 Jan 2019 00:16:43 GMT
Connection: keep-alive
Content-Length: 196

{"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing
---> AT+CHTTPSCLSE
<--- OK
---> AT+CHTTPSSTOP
<--- OK

As we can see, the Arduino received a JSON response from the website.
Here are the parameters that I used for the NOT WORKING GET request:
Host Address: wastedb.000webhostapp.com
Host: wastedb.000webhostapp.com
Response from Serial monitor for wastedb.000webhostapp.com (NOT WORKING):
---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="wastedb.000webhostapp.com",80,1
<--- OK
---> AT+CHTTPSSEND=113
<--- >
---> GET /wastedb/get_location.php?lat=14.640155&lon=120.974920&stat=LOW HTTP/1.1
Host: wastedb.000webhostapp.com

<--- OK
---> AT+CHTTPSSEND
<--- ERROR

Am I missing something here? Seems like the shield cannot find the Host Server I provided for my website.
EDIT: It is working now. The only solution that worked for me is to find another hosting site.

Please consider answering your own question with the information in your "edit". After a day or two, you can accept your answer as the solution.

It is working now. The only solution that worked for me is to find another hosting site.

Try just using IP address for the Host line instead. I did the same thing for POST and it works fine for me.
Example:
Host: 13.xxx.xx.xx


text:
Large(ish) strings failing to send over WiFi101 using WiFiServer
I've based a sketch off the vanilla WiFi101 server examples.
If I define a const char array like this:
const char HTML_index[] = "test";

The server works well.  However if I increase the char[] size to about 1,300 bytes the server fails to send a response.  The device (Feather M0 WiFi) doesn't lock up, I can continue to make HTTP requests and the serial console functions correctly, just no HTTP response.  The device and laptop (client) are both on the same WiFi AP so nothing weird there.
First I thought this was a memory issues, but as I'm using newer architecture and IDE using const should ensure the string is in FLASH.
So I then read some threads about buffer limits per response using other libraries: https://github.com/esp8266/Arduino/issues/3205
But again not sure how applicable this is to an ARM based system/ WiFi101 library.
Is there a limiting buffer size etc when sending HTTP data in my setup? Do I need to split the string up into smaller pieces and send multiple responses?  How could I go about debugging this situation?
Edit:
This is the example sketch my code is based off:
https://www.arduino.cc/en/Tutorial/Wifi101SimpleWebServerWiFi
Edit2: ok I think I know what's going on but can't test right now, will post an answer when I do.  I found this thread https://github.com/arduino-libraries/WiFi101/issues/163 which talks about SOCKET_BUFFER_UDP_SIZE.  So I looked through the WiFi101 src and found this:
#ifdef LIMITED_RAM_DEVICE
#define SOCKET_BUFFER_SIZE 64
#else
#define SOCKET_BUFFER_SIZE 1472
#endif

https://github.com/arduino-libraries/WiFi101/blob/master/src/utility/WiFiSocket.cpp
It's likely that my string was actually over 1472 bytes so this makes sense.
Edit3:
Found more references:
https://github.com/arduino-libraries/ArduinoHttpClient/issues/14
https://github.com/arduino-libraries/WiFi101/pull/116
So I take it the 1500 in WINC1500 could mean the buffer size.  Either way looks like there's a hardware buffer limit and responses larger than ~1400 bytes need to be chunked.

the examples don't use const char HTML_index[]. show the sketch you use. do you set content-legth header?

I'll add a stripped down example sketch soon.  But it follows this example exactly, except I define a const char HTML_index[] = "..."; in global scope and call client.print(HTML_index); in the client connected loop. https://www.arduino.cc/en/Tutorial/Wifi101SimpleWebServerWiFi

try to add a delay before client.stop()

I'll give that a try, but since my HTTP header doesn't specify Connection: close execution stays in the while (client.connected()) loop and doesn't hit client.stop().  But maybe that's a problem

As per my notes the WINC1500 has a limit of 1500 bytes per transmission.  But some of this is always taken up by TCP overhead so the payload buffer must be smaller, that's why you see numbers like 1460.
From:
http://ww1.microchip.com/downloads/en/appnotes/atmel-42739-tcp-client-and-server-operation-using-atwinc1500_at14596_applicationnote.pdf

2.2.2 TCP Packet Size
A packet is sized as per the lowest MTU (Maximum
  Transmission Unit) on the path, which is typically 1500 bytes (for
  Ethernet) of data including TCP (20 bytes) and IP headers (20 bytes).
  The packet size is defined in main.h as :

#define MAIN_WIFI_M2M_BUFFER_SIZE 1460

The application then defines a socket buffer of this size in main.c as:

static uint8_t gau8SocketTestBuffer[MAIN_WIFI_M2M_BUFFER_SIZE];

This means that HTTP responses over ~1400 bytes need to be chunked which means split up into multiple calls.
FYI chunked Transfer-Encoding is superseded in HTTP/2:
http://undertow.io/blog/2015/04/27/An-in-depth-overview-of-HTTP2.html
Info on HTTP chunked encoding:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding
Transfer-Encoding: chunked

Data is sent in a series of chunks. The Content-Length header is
  omitted in this case and at the beginning of each chunk you need to
  add the length of the current chunk in hexadecimal format, followed by
  '\r\n' and then the chunk itself, followed by another '\r\n'. The
  terminating chunk is a regular chunk, with the exception that its
  length is zero. It is followed by the trailer, which consists of a
  (possibly empty) sequence of entity header fields.

https://www.httpwatch.com/httpgallery/chunked/
https://gist.github.com/CMCDragonkai/6bfade6431e9ffb7fe88

Transfer-Encoding
The use of Transfer-Encoding: chunked is what allows streaming within
  a single request or response. This means that the data is transmitted
  in a chunked manner, and does not impact the representation of the
  content.
Officially an HTTP client is meant to send a request with a TE header
  field that specifies what kinds of transfer encodings the client is
  willing to accept. This is not always sent, however most servers
  assume that clients can process chunked encodings.
The chunked transfer encoding makes better use of persistent TCP
  connections, which HTTP 1.1 assumes to be true by default.
Chunked data is represented in this manner:

4\r\n
Wiki\r\n
5\r\n
pedia\r\n
e\r\n
 in\r\n\r\nchunks.\r\n
0\r\n
\r\n

Each chunk starts with its byte length expressed as a hexadecimal
  number followed by optional parameters (chunk extension) and a
  terminating CRLF sequence, followed by the chunk data. The final chunk
  is terminated by a CRLF sequence.
Chunk extensions can be used to indicate a message digest or an
  estimated progress. They are just custom metadata that your layer 7
  receiver needs to parse. There's no standardised format for it.
  Because of this, it's probably better to just add your metadata (if
  any) into the chunk itself for your layer 7.5 application to parse.
For your application to send out chunked data, you must first send out
  the Transfer-Encoding header, and then you must flush content in
  chunks according to the chunk format. If you don't have an appropriate
  HTTP server that handles this, then you need to implement the syntax
  generator yourself. Sometimes you can use a library to provide an
  abstract interface.

Possible fix on Arduino platforms is to use StreamLib library or roll-your-own chunking system.
Update:  I hacked together a sketch and confirmed this works.  Next issue was the buffer must be null terminated, BUT this is stripped out before transmitted over TCP so the HTTP chunk size is the buffer size -1.


text:
How to parse multi line serial data with an unknown number of lines?
Here's the example data I've read in H-Term:
\r\n
\r\n
NO:0015\r\n
G:   5.97kg\r\n
T:   0.00kg\r\n
N:   5.97kg\r\n
\r\n
\r\n

How to save the number including "kg" to each variable (NO, G, T, N)?

so you need to save strings?

yes, i need to save that into 4 variable represent each line

what did you try?

This is an overly broad question which borders "write me the code" - this isn't a coding service - and if anything belongs on StackOverflow since it regards processing.  That being said, this question would be flagging as overly broad there too.
I'm providing an answer because I believe it may help others here as it speaks to some fundamental programming concepts.  This is not a perfect solution by any means, for example it doesn't take program size into account. See the end of the post for a sketch.
There are two main problems you face:

Model the input data
Process the data

Modeling the input data means structuring your expected input in a meaningful way.  Looking at the input data provided, I see this format

0-N chars indicate some metadata delimited by a colon (:)
0-N white space
0-N digits with optional decimal point (0015,5.97)
0-N unit designation (kg)
data is delimited with a CRLF (\r\n)

Now think of each line as a packet of information.  In that sense, let's create some data structures that describe the data of the packet.
// Types
typedef enum {
  NoType,
  NO,
  G,
  T,
  N,
} Type;

// Units
typedef enum {
  NoUnit,
  uKg, // kilogram
  uG,  // gram
} Unit;

// Values - unions are handy to model variants.
typedef union {
  char str[5];
  float dval;
} Value;

Given the basics above, let's model a Packet:
// the data model for a CRLF delimited packet
typedef struct {
  Type type;
  Value value;
  Unit unit;
  byte valid;
  // metadata
  byte expectUnit; // 1 if a Value has a Unit; 0 otherwise.

} Packet;

OK, so that's a basic model of the input data.  How to process?  Always break down big problems to the smaller, manageable units to provide a solution.
Now there's a huge number of possibilities to parse/interpret your data packets.  I am providing a bare bones, brute force approach that you may learn from, and hopefully improve upon.  For example I am not providing much in the way of array overruns which can crash a program.
Here's the main processing function, which takes a string of input data (a line) and produces a Packet.  In all I am only going to provide for the Type 'G' and leave the rest to you.
// readPacket processes the input string pszBuffer and fills pPacket accordingly.
//
// pszBuffer should be a string of characters delimited by \r\n.
// pPacket is a pointer to a Packet which is filled by this function.
//
// returns 1 if packet is valid, 0 otherwise.
byte readPacket(Packet* pPacket, const char* pszBuffer) {
  byte isvalid = 0;
  if (pszBuffer && pPacket) {
    char tmp[10];
    char* psz = (char*)pszBuffer;
    char* pszTmp = 0;
    byte len = 0;
    // initialize packet
    pPacket->type = Type::NoType;
    pPacket->unit = Unit::NoUnit;
    pPacket->valid = 0;
    pPacket->expectUnit = 0;
    // get the Type
    psz = processType(pPacket, psz);
    if (psz) {
      // skip any space characters now.
      psz = trimLeadingSpaces(psz);
      psz = processValue(pPacket, psz);
      // if Type handled, check units and finish.
      if (psz) {
        if (pPacket->expectUnit)
          pPacket->valid = processUnit(pPacket, psz);
        else
          pPacket->valid = 1;
      }

    } // Type not found

    isvalid = pPacket->valid;
  }
  return isvalid;
}

OK that's not a lot.  The logic is

Get the packet Type
IFF a packet Type was found, get the packet Value
IFF a value was found, get the Unit if required

It's important to breakdown these steps in smaller, manageable functions.  First, the code for getting the packet Type.
// processType
// Sets pPacket->type to the type found in psz.  Type is delimited by a colon (:)
// Returns 0 (null) if a known Type wasn't found.
// Otherwise a ptr to the data past colon delimiter.
//
char* processType(Packet* pPacket, const char* psz) {
  // find the colon (:) delimiter and return what it leads to.
  byte len = 0;

  char* ptr = strchr((char*)psz, ':');
  char* pResult = 0;
  if (ptr) {
    // found the colon.
    char buffer[4];
    byte len = (ptr - psz) / sizeof(char); // pointer math to find length.
    strncpy(buffer, psz, len);
    // null term buff
    buffer[len] = 0;
    // assume succcess; default will rest to fail.
    pResult = (char*)psz + len + 1; // +1 to skip colon character.
    switch (buffer[0]) {
    case 'G':
      pPacket->type = Type::G;
      pPacket->expectUnit = 1; // unit should be given.
      break;
    default:
      pPacket->type = Type::NoType;
      pResult = 0; // fail, didn't find a known type.
    }
  }

  return pResult;
}

So processType sets up the packet Type and adds information about whether to look for Unit information later.
If processType() found a valid Type, the next step is to get the value based in that type with the function processValue
// Sets pPacket->value according to the packet Type.
// Returns null (0) if type not supported or value not found,
// otherwise a pointer to the remaining characters following the value handled.
char* processValue(Packet* pPacket, const char* psz) {
  char* ptr = 0;
  // value is construed by Type
  switch (pPacket->type) {
  case Type::G:
    ptr = processFloat(pPacket, psz);
    break;
    //
    // add your additonal Type implementations...
    //
  default:
    // invalid, set psz to null.
    ptr = 0;
  }
  return ptr;
}

Great. Now, let's look at a way to get the value for a float:
// Sets pPacket->value.dval
// Returns 0 (null) if a value wasn't found.
// Otherwise a ptr past the last character of the decimal value.
char* processFloat(Packet* pPacket, const char* psz) {
  const char *float_chars = ".0123456789";
  char* ptr = (char*)psz;
  if (ptr) {
    // scan ptr until we don't find a match.
    byte index = 0;
    while (strchr(float_chars, (char)ptr[index]))
      index++;

    if (index) {
      //  get the float using a temporary buffer.
      //  dangerous! assuming this will not overrun!
      char buf[10];
      strncpy(buf, ptr, index);
      // null term buff
      buf[index] = 0;
      pPacket->value.dval = atof(buf);
      // advance ptr past the decimal characters for return valie.
      ptr += index;
    }
    else ptr = 0; // fail
  }
  return ptr;
}

Finally if all went well, the code should look for the Unit if expected (based on the Type)
// Sets pPacket->unit to the unit given in psz.
// Returns 0 if no unit was found, non-zero otherwise.
byte processUnit(Packet* pPacket, const char* psz) {
  pPacket->unit =  Unit::NoUnit;
  if (psz) {
    switch ((char)*psz) {
    case 'k':
      pPacket->unit = Unit::uKg;
      break;
    case 'g':
      pPacket->unit = Unit::uG;
      break;
    default:
      break; // unit initialized to NoUnit.
    }
  }
  return pPacket->unit != Unit::NoUnit;
}

Here's a GIST of an arduino sketch using the code above.
Good luck, hope this helps.  In the future, pose questions regarding processing on StackOverflow.


text:
My ArI was using a potentiometer and the system shorted maybe. Do I have to replace the USB interface chip? It doesn't reset also
See I was using a micro analog rotary potentiometer to control a servo. The pot was in a pcb. The 5v output and gnd were connected to arduino from the pot. The third pin and 5v got touched and it got fused. The Rx and TX led glowed constantly till I disconnected the 12v input.

12V input + short on 5V = possible dead 5V regulator (if it didn't go into thermal shutdown). Possible dead 5V regulator = unknown voltage on 5V rail (could be as high as 12V). High voltage on 5V rail = dead Arduino.

What to do now? Buy a new one?

Unless you like diagnosing hardware faults and doing surface mount soldering then that's the easiest option. If the PC can still see the board the USB chip is OK. The main MCU may be dead though.