body:
On my Linux Mint 17 Quiana I have manually downloaded and ran several versions of the arduino IDE (1.05 which is in the repo, 1.6.x for some time, now 1.8.3). Things worked like a charm.

Now I am trying to get the IDE 1.8.5 going, but I cannot get the IDE started. Started means: I download, extract the files to a directory and run the install.sh command such that the desktop icon gets created. This finishe with a success message. Now I am clicking on the desktop icon, but nothing happens.

Need to say that the IDE 1.05 which comes as a package with Qiana works just fine. I have run the install.sh of both to and fro, but only the 1.05 will start properly. I checked on the desktop link, the execution rights, user, group etc. They are all looking fine for 1.8.5 but it wont start.

I tried to start the 1.85 arduino IDE from the command line - hoping to get some clue from error messages:

    java -DAPP_DIR=/opt/arduino-1.8.5/ Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel processing.app.Base

--> running this it tells me, that the main class cannot be found.

Any hints where I am going wrong? Are there any config files to be cleared up, paths to be set ...?

title: Cannot start Arduino IDE after playing with several versions of it

Answers: 2

body:
You do not *need* to install Arduino at all. In fact I have never had it work right due to things not being found.

All you need to do is, from a terminal, run the `arduino` command in the extracted directory:

    fred@computer:~/arduino-1.8.5 $ ./arduino

Any errors that then throws will be a clue as to why it doesn't want to work.

body:
1.05 is the latest available packaged version (and is quite dated).

You can download and (optionally) install the new version. See https://arduino.stackexchange.com/questions/44591/installing-arduino-ide-on-linux

Either remove (or ignore) the old version. Apart from the additional support the new version supplies, the directories differ - you can either change to the new (recommended) or change the settings.

There is no NEED to "install" the new version. The supplied script DOES NOT `install` in the traditional sense, it merely installs GUI links to the download.


body:
I understand most of it. The part I don't understand is the is the code in for void loop. How does that set the data rate for the software serial port? I thought mySerial.begin(9600) did that? Please help.

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2, 3); // RX, TX

    void setup()
    {
        // Open serial communications and wait for port to open:
        Serial.begin(9600);
        while (!Serial) {
            ; // wait for serial port to connect. Needed for Leonardo only
        }

        Serial.println("Goodnight moon!");

        // set the data rate for the SoftwareSerial port
        mySerial.begin(9600);
        // set master
        mySerial.print("AT+ROLE1");
        delay(10000);

    }

    void loop() // run over and over
    {

        // set the data rate for the SoftwareSerial port
        mySerial.print("test I am master  ");
        delay(10000);
        ***if (mySerial.available())
        Serial.write(mySerial.read());
        if (Serial.available())
        mySerial.write(Serial.read());***
    }

title: Could someone explain this code that sets up the software serial port data rate?

Answers: 2

body:
You're confusing "data rate" with "baud rate".

The *baud rate* is the speed at which bytes are transmitted over the wires, and is set with `mySerial.begin(9600);`.

The *data rate* is the speed at which data is sent over the serial port, and that is set by the `delay(10000);` which dictates how often `"test I am master  "` is sent and any incoming data is checked for and echoed.

body:
The void loop

    while(!Serial) {
    ;
    }

simply wait for the serial port to be ready to transmite/receive data. Otherwise, your first `Serial.print` will be lost.

You can omit it if you don't plan to transmit anything during the first second or two in your sketch.


body:
I am trying to simulate 4 flickering flames on a single LED strip.

The ws2812b strip has 60 LEDs. I cut and chained it into 4 chunks of 15 LEDs. Each chunk has a random Fire2012 sequence, however the entire sequence seems to start and stop at the same time, and therefore they all look extremely similar.

What is the best way to overlap the fire sequences so that timing looks different for each chunk?

Here is my code so far...

    #include <FastLED.h>

    #define LED_PIN     5
    #define COLOR_ORDER GRB
    #define CHIPSET     WS2812B

    #define NUM_CHUNKS           4
    #define NUM_LEDS_PER_CHUNK   15
    #define NUM_LEDS NUM_CHUNKS * NUM_LEDS_PER_CHUNK

    #define BRIGHTNESS  80
    #define FRAMES_PER_SECOND  30

    #define gReverseDirection false

    CRGB leds[NUM_LEDS];

    void setup() {
      delay(3000); // sanity delay
      FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
      FastLED.setBrightness( BRIGHTNESS );
    }

    void loop()
    {
      // Add entropy to random number generator; we use a lot of it.
      // random16_add_entropy( random());

      // Get LED Chunks
      for(int i = 0; i < NUM_CHUNKS; i++){
        //random16_add_entropy( random());
        Fire2012(i); // run simulation frame
      }

      FastLED.show(); // display this frame
      FastLED.delay(1000 / FRAMES_PER_SECOND);
    }

    // Fire2012 by Mark Kriegsman, July 2012
    // as part of "Five Elements" shown here: http://youtu.be/knWiGsmgycY
    ////
    // This basic one-dimensional 'fire' simulation works roughly as follows:
    // There's a underlying array of 'heat' cells, that model the temperature
    // at each point along the line.  Every cycle through the simulation,
    // four steps are performed:
    //  1) All cells cool down a little bit, losing heat to the air
    //  2) The heat from each cell drifts 'up' and diffuses a little
    //  3) Sometimes randomly new 'sparks' of heat are added at the bottom
    //  4) The heat from each cell is rendered as a color into the leds array
    //     The heat-to-color mapping uses a black-body radiation approximation.
    //
    // Temperature is in arbitrary units from 0 (cold black) to 255 (white hot).
    //
    // This simulation scales it self a bit depending on NUM_LEDS; it should look
    // "OK" on anywhere from 20 to 100 LEDs without too much tweaking.
    //
    // I recommend running this simulation at anywhere from 30-100 frames per second,
    // meaning an interframe delay of about 10-35 milliseconds.
    //
    // Looks best on a high-density LED setup (60+ pixels/meter).
    //
    //
    // There are two main parameters you can play with to control the look and
    // feel of your fire: COOLING (used in step 1 above), and SPARKING (used
    // in step 3 above).
    //
    // COOLING: How much does the air cool as it rises?
    // Less cooling = taller flames.  More cooling = shorter flames.
    // Default 50, suggested range 20-100
    #define COOLING  55

    // SPARKING: What chance (out of 255) is there that a new spark will be lit?
    // Higher chance = more roaring fire.  Lower chance = more flickery fire.
    // Default 120, suggested range 50-200.
    #define SPARKING 60

    void Fire2012(int chunk)
    {
    // Array of temperature readings at each simulation cell
      static byte heat[NUM_LEDS_PER_CHUNK];

      int startLed = NUM_LEDS_PER_CHUNK * chunk;
      int endLed = NUM_LEDS_PER_CHUNK * chunk + NUM_LEDS_PER_CHUNK;

      // Step 1.  Cool down every cell a little
        for( int i = 0; i < NUM_LEDS_PER_CHUNK; i++) {
          heat[i] = qsub8( heat[i],  random8(0, ((COOLING * 10) / NUM_LEDS_PER_CHUNK) + 2));
        }

        // Step 2.  Heat from each cell drifts 'up' and diffuses a little
        for( int k= NUM_LEDS_PER_CHUNK - 1; k >= 2; k--) {
          heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2] ) / 3;
        }

        // Step 3.  Randomly ignite new 'sparks' of heat near the bottom

        if( random8() < SPARKING ) {
          int y = random8(7);
          heat[y] = qadd8( heat[y], random8(160,255) );
        }

        // Step 4.  Map from heat cells to LED colors
        for( int j = 0; j < NUM_LEDS_PER_CHUNK; j++) {
          CRGB color = HeatColor( heat[j]);
          int pixelnumber;
          if(gReverseDirection) {
            pixelnumber = (endLed - 1) - j;
          } else { //0 15
            pixelnumber = startLed + j;
          }
          leds[pixelnumber] = color;
        }
    }

title: Multiple random Fire2012 sequence in same strip

Answers: 2

body:
Instead of calling the function on all 3 chunks back to back in the for loop and then only doing show() after you've updated all three chunks, break it up a little and put a little delay between them.

        byte i = 0;

        void loop(){
           Fire2012(i);
           FastLED.show();
           FastLED.delay(1000 / NUM_CHUNKS / FRAMES_PER_SECOND);
           i = (i + 1) % NUM_CHUNKS;
        }

You could even make the delay a little bit random if you wanted to.

body:
    #include <FastLED.h>

     #define LED_PIN     5
     #define COLOR_ORDER GRB
     #define CHIPSET     WS2811
     #define NUM_LEDS    (kMatrixWidth * kMatrixHeight)
     #define FRAMES_PER_SECOND 60
     //////////////////////////////////////////////////////
     const uint8_t kMatrixWidth  = 15;
     const uint8_t kMatrixHeight = 4;
     const bool    kMatrixSerpentineLayout = true;
     //////////////////
     int BRIGHTNESS = 250;

    //////////////////////////////////////////////////
    bool gReverseDirection = false;

    CRGB leds[NUM_LEDS];

    void setup() {
    Serial.begin(115200);
    Serial.println("*** Inicialization");
    ///////////////////////////////////////////////
    delay(3000); // sanity delay
    FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS);
    FastLED.setBrightness( BRIGHTNESS );
    }
    /////////////////////////////////// end setup

    void loop()
    {

     Fire2012();
     FastLED.show(); // display this frame
     FastLED.delay(1000 / FRAMES_PER_SECOND);
     FastLED.setBrightness( BRIGHTNESS );
     }

     void Fire2012()
     {
      int COOLING = 90;
      int SPARKING = 100;
       // Array of temperature readings at each simulation cell

        static byte heat[kMatrixWidth] [kMatrixHeight];

        // Step 1.  Cool down every cell a little
        for (int n = 0; n< kMatrixHeight; n++)
       {

         for ( int i = 0; i < kMatrixWidth; i++) {
           heat[i][n] = qsub8( heat[i][n],  random8(0,
           ((COOLING * 10) / (kMatrixWidth)) + 2));
           }

           // Step 2.
          for ( int k = (kMatrixWidth- 1); k >= 2; k--) {
          heat[k][n] = (heat[k - 1][n] + heat[k - 2][n] +
          heat[k - 2][n] ) / 3;
          }

           // Step 3.
          if ( random8() < SPARKING ) {
           int y = random8(3);
           heat[y][n] = qadd8( heat[y][n], random8(160, 255) );
          }
         }

      // Step 4.  Map from heat cells to LED colors

    for ( int i= 0; i < kMatrixWidth; i++) {
      for (int j = 0; j < kMatrixHeight; j++) {

        CRGB color = HeatColor(heat[i][j]);
        leds[XY(i, j)] = color;

         }
       }

     }

       /////////////
        uint16_t XY( uint8_t x, uint8_t y)
        {
        uint16_t i;
        if ( kMatrixSerpentineLayout == false) {
        i = (y * kMatrixWidth) + x;
        }
        if ( kMatrixSerpentineLayout == true) {
        if ( y & 0x01) {
         // Odd rows run backwards
         uint8_t reverseX = (kMatrixWidth - 1) - x;
         i = (y * kMatrixWidth) + reverseX;
         } else {
        // Even rows run forwards
          i = (y * kMatrixWidth) + x;
         }
        }

        return i;

       }/////


body:
I am building a timer circuit using Arduino Pro Mini Atmega168p 5v 16MHz (which later supposed to be become to adjustable one).

Here is the current breadboard view.

[![enter image description here][1]][1]
(I am supposed to use SS relay at place of that green thing. I am not sure if that item is correct SS relay in Fritzing)

Here is the program code I wrote.

    #include <PinChangeInterrupt.h>
    #include <PinChangeInterruptBoards.h>
    #include <PinChangeInterruptPins.h>
    #include <PinChangeInterruptSettings.h>

    #include <avr/sleep.h>

    // LED to indicate timer is active.
    const int ON_LED = 5;
    // It should be high when timer is active.
    // Connect to relay.
    const int PUMP_SWITCH = 6;

    // Button to start timer running.
    const int START_BUTTON = 8;
    // Button to stop timer forcefully.
    const int STOP_BUTTON = 9;

    volatile boolean timer_running;
    volatile int timer_start_time;

    // TODO: Make it volatile once timer has mdified as configurable.
    volatile unsigned long timer_time = 0;

    void enter_sleep_mode() {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      sleep_enable();
      sei();
      sleep_mode();
    }

    /**
     * Activate timer.
     */
    void start_timer() {
      if (!timer_running) {
        // Time period in milliseconds.
        timer_time = 30000ul; // 30 seconds

        timer_running = true;
        timer_start_time = millis();
      }
    }

    /**
     * Stop timer.
     */
    void stop_timer() {
      timer_running = false;
      timer_start_time = 0;
    }

    void setup() {
      timer_running = false;
      timer_start_time = 0;

      // Configure output pins.
      pinMode(ON_LED, OUTPUT);
      pinMode(PUMP_SWITCH, OUTPUT);

      // Configure pins for input push buttons.
      pinMode(START_BUTTON, INPUT_PULLUP);
      pinMode(STOP_BUTTON, INPUT_PULLUP);

      // Attach interrupt handlers
      // Buttons are with pull up resistors so listening for 'falling' (voltage).
      attachPCINT(digitalPinToPCINT(START_BUTTON), start_timer, FALLING);
      attachPCINT(digitalPinToPCINT(STOP_BUTTON), stop_timer, FALLING);
    }

    void loop() {
      if (timer_running) {
        digitalWrite(ON_LED, HIGH);
        digitalWrite(PUMP_SWITCH, HIGH);
        // TODO: Handle the case when return value of millis() goes back to start from zero
        if ( (millis() - timer_start_time) >= timer_time ) {
          // Timer elapsed the required time period.
          // So, stop the timer.
          stop_timer();
        }
      }
      else {
        digitalWrite(ON_LED, LOW);
        digitalWrite(PUMP_SWITCH, LOW);
        // Nothing to do If timer is not running.
        // Save power!!
        enter_sleep_mode();

        sleep_disable();
      }
    }

**The problem is timer does not work when pressing START button starting from third click. Two initial clicks works OK and timer functions as it should be. I think it does not wake up properly from sleep mode. However, wondering why it works for two initial clicks??**

Please help me to identify the problem.
I don't have much experience in writing Arduino code.

Thanks

  [1]: https://i.stack.imgur.com/pVU01.png

title: Pin change interrupt does not work properly to wake up arduino from sleep mode

Answers: 2

body:
Start by checking your calculation of time limits. I see you are mixing signed and unsigned arithmetics - not a very good idea. Check the blink-without-delay example for how to do that.

The declaration of timer_start_time should be paid special attention.

Good luck with your project!

body:
> Please help me to identify the problem.

it is always very easy to solve this type of problems, if you just follow some common sense.

1) decompose your functionality  into manageable blocks. for example, one is PCINT - can you blink an led with it - and another is going into sleep - can you put the mcu into sleep - and the next is to walk up from sleep - does your mcu support that? what has to be true for that to happen? ...

2) test individual blocks on their own.

3) integrate them into one functional program.

don't co-mingle them day 1. tackle only what you can manage. no more and no less.


body:
I am following a tutorial online to make a pong game. I have managed to make quiet a lot work apart from my paddles in the game keep on shaking. The buttons do work fine, up and down on both ends.

[Tutorial Link][1]

I am sure, there is something with the power being supplied and not reaching to all points in the breadboard.

I am attaching a picture of my circuit board.[![enter image description here][2]][2] Any advice?

Thank you,
W

  [1]: https://github.com/jerwil/Arduino_Pong
  [2]: https://i.stack.imgur.com/NkYR4.jpg

title: Arduino Pong game Circuit Board Troubleshoot

Answers: 1

body:
The + and - along the bottom of the picture aren't connected to anything.
It also looks like this board has a separate left and right side.

So just make sure everything is connected along the sides.


body:
I am currently trying to create a line tracing robot with my Arduino Uno.

I have an IR Sensor (http://support.robotis.com/en/product/auxdevice/sensor/irsensor_manual.htm) but I am not sure if I can use this for my Arduino.

Can someone please tell me if I can? Thanks in advance.

title: Using an IR sensor from another manufacturer

Answers: 1

body: Yes, you will need to connect the sensor ADC line to an ADC input on the Arduino and calculate the range from the analogread result.  You should be able to use one of the Sharp sensor libraries, although you may need to apply a correction factor to the distance results.


body: How to send data (Hello World) from Arduino Uno to a PC using USB to TTL/UART (PL2303 4 wires)? Why do I need to press the reset button to upload a program using PL2303?

title: Arduino Uno serial communication using USB-to-TTL converter

Answers: 2

body:
> How to send data(Hello World) from Arduino Uno to PC using USB to TTL/UART(PL2303 4 wires)?

    Serial.print("Hello World");

That is, assuming it's connected to pins 0/1. Otherwise you would have to use `SoftwareSerial`.

> why I need to press the reset button during upload a program using PL2303?

Because it lacks a DTR signal to press the reset button for you (resetting runs the bootloader).

body: I think you have a PL2303 board that do not have DTR or RTS line. It is a signal from Arduino IDE to Arduino Board for reset. So you must press reset button before upload.


body:
I'm currently using an Arduino UNO with a raspberry pi 3b. I'm using the USB connector for both power and comms, i.e. the arduino is powered by the RPI via the USB cable, and also i use the same cable for serial communication between the pi and the UNO.

My question is, could i use the same code, and wiring if i were to change the UNO with a NANO or MICRO?

So for example, on the RPI side of things, could i still simply setup the arduino in my python code as

    arduino = serial.Serial('/dev/ttyACM0', 9600)

and send commands with something like

    arduino.write('2')

and on the arduino side of things, just check if there is serial data coming in and read it, like

    if (Serial.available()) {
        command = Serial.read();

I know this may be a very stupid question, but to wrap it up, would anything change other than number of analogues, digitals etc, if i were to switch from an UNO to a MICRO or NANO?

title: Arduino UNO vs NANO or MICRO with RPi3

Answers: 1

body:
The Nano uses the same chip (ATMEGA 328P) that is on the Uno.  So putting the same code on the Nano should work the same as the Uno.

The Micro uses a different chip.  Whether or not the code from your Uno will work on your Micro depends on what is in the code.  You chose not to show anyone the code so that can't be answered yet.


body:
Using Arduino Yun.

My code:

    time_t today;
    time_t now;
    ...
    void setup() {
      time(now);
    ...
      Serial.println( asctime(gmtime(&now)));

What I get is:

> Sat Jan 01 00:00:00 2000

I am expecting something like this:

> 1507572195.825

How do I get the number of seconds and milliseconds since the Linux Epoch?

title: Getting current epoch time in seconds and milliseconds

Answers: 0


body: I want to automate the lights in my house. To do this, I want to use a latching relay, so it will only use current when switching. I found a quite cheap latching relay RT314F12 but I do not know how to wire it up to an Arduino. Can any one please give a wiring example?

title: Wiring a RT314F12 latch relay to an Arduino

Answers: 0


body:
I have 3 standard LEDs (red, yellow and green) connected in parallel to GPIO pins 10, 11 and 12. I also have one resistor, to which they are all three connected.

What's the difference between connecting the resistor to ground (so that the leds are high active) or to the 5V output pin of the arduino (so that the leds are low active)?

Moreover: how many ohms should the resistor have?
My understanding is: each of the 3 standard LEDs needs 20mA, so, if all three are lit, there is 60mA on the circuit. The 3 parallel LEDs need 2 V.
So, the resistor should be chosen such that it has a voltage drop of 3V at 60mA, hence 3V/60mA = 50 Ohm. If only one is lit, I need 3V/20mA = 150 Ohm.

But, if its possible that every possible subset of the LEDs is lit at once, wouldn't it be better, to place a resistor in front of every LED, so that I have 3 LED-resistor pairs in parallel? The value of each resistor is 50 Ohm then, allowing for a voltage drop of 3V in each of the 3 branches, so that each LED only gets the needed 2V?

Well, a lot of thoughts for 3 simple lights...
Thanks for any help.

title: Traffic lights: gpios against 5V or ground

Answers: 1

body:
> I have 3 standard LEDs (red, yellow and green) connected in parallel to GPIO pins 10, 11 and 12. I also have one resistor, to which they are all three connected.

BAD BAD BAD!!!

> What's the difference between connecting the resistor to ground (so that the leds are high active) or to the 5V output pin of the arduino (so that the leds are low active)?

Nothing, other than the reversed logic. AVR GPIOs (and most GPIOs in modern MCUs) are balanced - i.e., they have the same current limit for both sink and source.

> Moreover: how many ohms should the resistor have? My understanding is: each of the 3 standard LEDs needs 20mA, so, if all three are lit, there is 60mA on the circuit. The 3 parallel LEDs need 2 V. So, the resistor should be chosen such that it has a voltage drop of 3V at 60mA, hence 3V/60mA = 50 Ohm. If only one is lit, I need 3V/20mA = 150 Ohm.
>
> But, if its possible that every possible subset of the LEDs is lit at once, wouldn't it be better, to place a resistor in front of every LED, so that I have 3 LED-resistor pairs in parallel? The value of each resistor is 50 Ohm then, allowing for a voltage drop of 3V in each of the 3 branches, so that each LED only gets the needed 2V?

Yes. That is how you *should* wire LEDs - and you have already identified why.

For *each* LED calculate the resistance as R=(5-Vf)/0.02. You need to find the correct Vf for each LED from the datasheet to get the best results - but if you can't then a rule of thumb is: Red, Green and Yellow are about 2V, Blue and White are about 3V.


body:
I have an Arduino Uno connected to Cayenne through the serial connection, currently i am reading the data from a sensor of temperature and humidity DHT12 and showing it in the Dashboard of Cayenne correctly.

I need to know if i can send emails from the Arduino using the connection that cayenne let me use, because i can't stay with the pre-defined alerts that the platform have.

title: Send Email through Cayenne serial connection

Answers: 1

body:
No, the Arduino cannot send emails directly through serial. The communication channel you have set up is a direct connection between the Arduino and Cayenne. It cannot be used for anything else other than communicating with Cayenne.

However that doesn't mean you can't try and see if there is some way of making Cayenne send emails for you. Having never used Cayenne I cannot comment on this aspect. You would be better off consulting directly with Cayenne and their users through their forums.


body:
I have tried getting my Arduino to communicate with another device, to no avail. The command A, when sent via serial to the device, triggers it to respond with 8 binary bytes with the first 4 representing a floating point number, and the final 4 representing a floating point number. The command only has to be sent once a second, and the aim is to store the 8 incoming bytes in an array, and convert them into their respective floats.

    unsigned long previousMillis = 0;
    const long interval = 1000;
    char incomingByteA[8];

    void setup() {
      Serial.begin(9600);
      while(!Serial);
      Serial1.begin(9600);
      while(!Serial1);
    }

    void loop() {
      unsigned long currentMillis = millis();
      if(currentMillis - previousMillis >= interval){
        //1 second timer
        previousMillis = currentMillis;
        Serial1.write('O');
        //Send command 'A' to device *noting Serial1 not Serial
        for(int n = 0; Serial1.available() < 8; n++) {
        incomingByteA[n] = Serial1.read();
        //Add each consecutive byte to an array until all 8 bytes have been added
      }
      float x;
      float y;
      ((byte*)&x)[3] = incomingByteA[0];
      //Convert first four bytes into a float
      ((byte*)&x)[2] = incomingByteA[1];
      ((byte*)&x)[1] = incomingByteA[2];
      ((byte*)&x)[0] = incomingByteA[3];
      ((byte*)&y)[3] = incomingByteA[4];
      //Convert final four bytes into a float
      ((byte*)&y)[2] = incomingByteA[5];
      ((byte*)&y)[1] = incomingByteA[6];
      ((byte*)&y)[0] = incomingByteA[7];
      Serial.println(x, 4);
    }
    }

However, when I do `Serial.println(x);`, it returns "nan". And if I try to do `Serial.println(incomingByteA[2]);`, it returns "?".

The following is the floating point format as per the device protocol:

31: sign of mantissa, 1=negative.
30-23: exponent, biased by 128.
22-0: mantissa, 24 bits, MSB hidden and always=1.

The mantissa is normalized, 24 bits with the MSB hidden. The MSB is always
assumed to be 1, therefore only 23 bits are needed to store the mantissa. The exponent is biased by 128; i.e. a 128 value represents an exponent of zero. A 129 value is an exponent of 1. Example: if the exponent has a 131 value (+3), the number is 2^3 * (mantissa). The mantissa is always less than one, and greater than or equal to 1/2. The number zero is stored as four zero bytes.

I am confident that it is not a fault with the hardware and for what it's worth, I am using a Leonardo. I would like to get the code down pat before I stress about hardware issues. What is this code not doing properly, if at all?

Thanks in advance.

title: Storing byte array from serial and converting to a floating point number

Answers: 2

body:
Two things I see wrong:

> Serial1.write('O');                                            //Send command 'A' to device *noting Serial1 not Serial

No, you send `O` not `A`... ???

> for(int n = 0; Serial1.available() < 8; n++)

While there are less than 8 bytes available in the buffer read one.

Erm...  The buffer starts off empty - empty is less than 8. It remains empty (always less than 8) until a byte *finally* arrives. Then it's still less than 8. I can't really see this ever working, and your array will overflow instantly and clobber the entirety of the rest of your RAM. I guess it finally finished when the serial object itself gets clobbered and `available()` returns some garbage number. In the meantime your array is just full of nothingness.

You need to completely rewrite that whole section. The simplest way is to wait *until* there are 8 bytes in the buffer (which will take some time - serial is *slooooow*):

    while (Serial1.available() < 8);

You now have 8 bytes available to read, so you can go ahead and read them.

A better way is to look to see if there is *at least* one byte available, then read it into the right place in your array - and keep count of how many bytes you have read:

    int n = 0;
    while (n < 8) {
        if (Serial1.available()) {
            incomingByteA[n++] = Serial1.read();
        }
    }

Of course, it's better to add some form of timeout in there too - so if nothing arrives soon enough your program doesn't lock up - or if you miss a byte it doesn't get completely out of sync. Also purging your read buffer before sending the command can help to prevent sync issues:

    // Purge any old data
    while (Serial1.available()) {
        Serial1.read();
    }

    Serial1.write('A');

    int n = 0;
    uint32_t start = millis();
    while (n < 8) {
        // 1 second timeout
        if (millis() - start > 1000) {
            break;
        }
        if (Serial1.available()) {
            incomingByteA[n++] = Serial1.read();
        }
    }

    if (n == 8) {
        // We got the data - do something with it
    } else {
        // It timed out
    }

Now when it comes to converting to a pair of floats there's better ways than your byte-wise manipulation.  For instance, you could use a union:

    union FloatPair {
        struct {
            float a;
            float b;
        };
        char bytes[8];
    } __attribute__((packed));

    FloatPair data;

Now you can use:

    data.bytes[n]

to access the memory directly, and

    data.a;
    data.b;

to access the float values.

You can also do something similar with casting:

    struct FloatPair {
        float a;
        float b;
    };

    FloatPair data;

    char *bytes = (char *)&data;

`bytes` is now a byte-wise view of the memory used by a pair of floats.

You can even work the other way around:

    char data[8] __attribute__((aligned(4)));

The aligned attribute will force the address of the array to be on a 4-byte boundary. Not important for a little 8-bitter, but vital if you ever port to a 32-bit MCU since a float always has to be on a 4-byte boundary, so a good habit to get into.

Now you can map floats into that memory space:

    float *a = (float *)(&data[0]);
    float *b = (float *)(&data[4]);

and access the floats as `*a` and `*b`. The `*` dereferences the pointers back into real numbers.

One thing to note: these methods all depend on the endianness of your data matching the endianness of your MCU - if they differ then you will have no choice but to do it all with manual byte-wise mapping.

body:
Thank you Majenko for your fast help!

I believe that the code is now alright. I will look at using the union method this weekend. For now, however, this is the final code.

     byte incomingByteA[8];

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

     Serial.begin(9600);
     while(!Serial);
     Serial1.begin(9600);
     while(!Serial1);

     }

     void loop() {

     // Purge any old data
     while (Serial1.available()) {
     Serial1.read();
     }

     Serial1.write('A');

     int n = 0;
     uint32_t start = millis();
     while (n < 8) {
     // 1 second timeout
     if (millis() - start > 1000) {
        break;
     }
     if (Serial1.available()) {
        incomingByteA[n++] = Serial1.read();
     }
     }
     float x;
     float y;
     if (n == 8) {
     ((byte*)&x)[3] = incomingByteA[0];                             //Convert first four bytes into a float
     ((byte*)&x)[2] = incomingByteA[1];
     ((byte*)&x)[1] = incomingByteA[2];
     ((byte*)&x)[0] = incomingByteA[3];

     ((byte*)&y)[3] = incomingByteA[4];                             //Convert final four bytes into a float
     ((byte*)&y)[2] = incomingByteA[5];
     ((byte*)&y)[1] = incomingByteA[6];
     ((byte*)&y)[0] = incomingByteA[7];

     Serial.println(x);
     } else {
     // Some timeout response
     }

     }

What I find odd, is that Serial.println(x); returns "8.00" followed by several, random lines of "0.00". Yet Serial.println(x); returns just "0.00". I am simply putting this down to the device I am trying to communicate with though.

Harry


body:
I have an Arduino Mini 05 clone [Wattuino][1], an [Elegoo Mega][2], a [Powerboost 1000c][3], but not access to a USB-to-serial converter. Is there any way to program the Arduino Mini with these devices?

I tried to search it but they only mention using an Arduino uno as the chip can be put out of the board. [Discusion][4]

  [1]: http://www.watterott.com/de/Wattuino-pro-mini-5V-16MHz
  [2]: https://www.amazon.de/Elegoo-Mikrocontroller-ATmega2560-ATMEGA16U2-Kompatibel/dp/B01MA5BLQI
  [3]: https://www.adafruit.com/product/2465
  [4]: https://forum.arduino.cc/index.php?topic=104135.0

title: Programing a Mini 05 without a USB-to-serial converter

Answers: 1

body: You can use the Mega. The only reason for "removing the chip from the board" is to disable it so it doesn't respond to the serial data - you can also disable it by just connecting the RESET pin to GND.


body:
I'm running a Velleman VMA103, which is advertised as a clone of the Leonardo. Both use the 32u4 chip, and the pinout is exactly the same. However, when I plug it in, the drivers do something weird.

For about 5 seconds after pressing reset, the Arduino IDE will recognize the Leonardo on COM9, and the Windows device manager will show "Arduino Leonardo bootloader" then, the COM9 device will disappear and a device will be shown in the Other Devices tab as a LININO ONE, with no drivers installed. How is this possible?

I've reinstalled the IDE, no help there.

[![Immediately after a reset][1]][1]

[![After 5 seconds][2]][2]

[1]: https://i.stack.imgur.com/78Zlp.png

[2]: https://i.stack.imgur.com/B8EAy.png

title: Leonardo clone being recognized by Windows as a broken Linino One - wtf?

Answers: 1

body:
USB associates a driver, and thus what it calls a device, with the VID and PID that the device announces. Arduino PIDs are in a horrible mess, and there are many different devices that use the same PID. On top of that you have other makers also using the same VID/PID pairs and providing their own re-named Arduino driver files for their devices.

And then of course you have the problem that it is down to the firmware ("sketch") installed on the Leonardo that determines what VID and PID is shown to the computer.

So you have a set of possible scenarios - the main two being:

1. You have a driver installed that identifies the VID/PID pair of the Leonardo as something else
2. You have firmware installed in the Leonardo that gives the wrong VID/PID pair for your drivers

Check 2 first by installing the Blink example into the Leonardo (you can still upload firmware since it goes to bootloader mode at first as you have seen). If it changes the shown driver then you had some broken firmware installed. If it doesn't then you may be running a patched installation of the Arduino AVR core that gives a different default VID/PID pair, or you may just have the wrong board selected in the menu.

If you still have trouble then uninstall whatever driver is associated with the detected device and reinstall the official Arduino drivers that come with the IDE.

You can also delete the IDE and its associated downloaded packages and reinstall the latest version to ensure that you don't have strange patches and settings in there corrupting things.


body:
I have a OsiSense™ XMLP pressure sensor that I want to read from my Arduino uno. This is the circuit I am looking at building for measure 4 to 20 milliamp.
[![Reading 4 to 20 milliamps using Arduino][1]][1]

I've read online to find out how to build the circuit.  Can you tell me if it is correct?

Also I dont understand why it works and I'm hoping you can correct my thinking.  Following ohms law we want to leave 5v when 20 milliamps goes through the circuit.  We know the voltage on the circuit is a constant 24 volts (short cable runs) and we know the maximum current is 20 milliamps so my maths says :

Resistance = Voltage  / I (current)

We need to leave 5 volts for the Arduino to read when the sensor is at maximum pressure so we subtract 5 from 24.

Resistance = 19  / 20 milliamp

So the resistor to select to give us a maximum of 5 volts is a 0.95 Kilohms resistor.  I dont see where the 250 ohm resistor comes in? please help.

  [1]: https://i.stack.imgur.com/x8eYa.jpg

title: Reading 4 to 20ma pressure sensor using uno

Answers: 1

body:
To read a current with the Arduino you first have to convert that current to a voltage - and you do that by passing it through a resistance. The voltage dropped across that resistance as the current changes is what interests you.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/uO94I.png)

<!-- End schematic -->

For a 4-20mA current you need to choose a resistance that gives voltages that are within the 5V range that an Arduino can read.

The biggest voltage drop across the resistor will occur when the current is at maximum (20mA) so you can use that to calculate a good resistor value to use:

    R = V/I = 5 / 0.02 = 250

And for the same resistance at minimum current:

    V=IR = 0.004 × 250 = 1

So across the resistor you would get between 1V (4mA) and 5V (20mA).

250Ω resistors aren't that common, so a more common value would be used instead - such as the commonly available 220Ω.  Substituting the 250Ω for a 220Ω would give voltages:

    @20mA: V=IR = 0.02 × 220 = 4.4V
    @4mA:  V=IR = 0.004 × 220 = 0.88V

Both comfortably within the Arduino's range and also gives a bit of wriggle room in case of any small over-current conditions.

It can also be good to protect the analog input of the Arduino with a resistor + zener diode to prevent damage in the case that the resistor fails / becomes disconnected and you get the full output voltage applied direct to the Arduino:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/ppdUh.png)

<!-- End schematic -->


body: What happends if I turn on all LEDs at the same time in an 4 digit 7 segment display? that would be 32 LEDs turned on at once, wouldn't that exceed the 200ma MAX for the arduino output?

title: 4 digit 7-segment display

Answers: 3

body:
These typically use 12 GPIO pins (4 for the digits, 8 for the segments/dot).

Each GPIO pin controls one digit and/or segment at a time.

The normal 'maximum' LED current is 20 mA. For the digits, 8 segments * 20 mA = 160 mA which is below 200 mA.

However, maybe there are LED displayed which use more current. In that case, you have yourself to make sure not all segments are lit at the same time (by fastly alternating the LEDs, or using less current).

body:
They will turn on, likely with slightly uneven brightness - the LEDs internal resistance and the pins limited current drive will act like the current limiter.

The actual current will depend on the supply voltage, led used and the mcus drive capabilities.

For a red 4 digit 7 seg on an atmeha8, I got less than 10ma at 2,5v and 20ma at 3.3v, with the LEDs multiplexed.

Edit: some quick math.

Say that the current through each led segment is I. And the gpio resistance is R.

Each common digit has 8 I current through it, and each segment has 4 I. Some math later,

I = (Vcc - Vf) / (12 R) where Vcc is the supply voltage and Vf is the LEDs forward voltage (1.9v for a typical red led). The gpio resistance varies from 50+ ohm to 30+ ohm, higher at lower voltage.

Plus in 3.3v and 2.7v you get total current of 30 to 75ma for all digits.

I'm going to measure mine later.

edit: about 25ma (total current = mcu + led) at 2.5v and 50ma at 3.3v. the mcu consumes 2-3ma approximately.

the brightness is fairly even amongst the leds if you don't look too closely.

body:
The key point is that if you do that, you're doing it wrong.

Typically a multi digit display is time multiplexed, such that you use a common set of segment lines to activate the pattern on each digit in turn, therefore at any one time only at most 7 (or 8 counting the decimal point) segments should actually be on.

Then in terms of the common connection which selects a given digit, this will indeed typically have to source or sink more current than an MCU I/O pin is typically rated to handle, so it's best if the common connection is driven by an external transistor or FET.

Other options of course include mutli-digit LED display drivers, or lower power display technologies like LCDs.

That said, if a software bug briefly means everything is on, chances are the chip will survive.  But hopefully this only happens to "engineering units" - you do want to make sure that *production* units don't suffer this at some point in the programming process or something like that (though that's not all that likely, as typically all I/Os become inputs with at most a weak pullup).


body:
I am kind of a newbie when it comes to stepper motors so I am hoping I am not asking any stupid questions.

I am trying to run a 3-5v micro stepper motor ([PM15S-020-SKH4][1]) using a [Pololu A4988][2] stepper driver. I know the driver isn't originally meant for low-voltage stepper motors but I had some lying around and from what I understand it should not be a problem as long as the pot-value is set correctly.

Now I've identified the coils on the stepper motor and connected everything with an 12V power supply, Arduino Uno, `100uF` capacitor as described in the [Pololu][2] schematic. I couldn't find the current specification for the stepper motor but if my calculations are correct with `5V / 30 Ohm` it should be `160 mAmp` so per another calculation I've set vRef value for the pot-meter to `0.160 * 0.4 = 0,064`

The code I run on the Arduino is;

    #define PIN_DIR 1
    #define PIN_STEP 3
    #define PIN_ENABLE 5

    void setup()
    {
        pinMode(PIN_DIR, OUTPUT);
        pinMode(PIN_STEP, OUTPUT);
        pinMode(PIN_ENABLE, OUTPUT);

        digitalWrite(PIN_ENABLE,LOW);
    }

    void loop()
    {
        digitalWrite(PIN_DIR,HIGH);

        // 20 pulses of 18 degrees should make one full rotation
        for(int i = 0; i < 20; i++)
        {
            digitalWrite(PIN_STEP,HIGH);
            delayMicroseconds(500);

            digitalWrite(PIN_STEP,LOW);
            delayMicroseconds(500);
        }

        delay(1000);
    }

When running the above code, the shaft is harder to move compared to a disconnected motor so there is resistance between the coils what should indicated that they are powered. But when running this the only thing the motor does is make a whirring noise and struggle/tick when I try to rotate it with my fingers.

I have tried multiple of the same type motors and drivers but all yield the same result.

I have a feeling I am overlooking something very obvious but I have no idea what, or am I being a complete idiot trying to combine the Pololu A4988 and the PM15S-020-SKH4?

  [1]: https://www.amazon.com/NMB-Phase-Stepper-degrees-PM15S-020-SKH4/dp/B01CE79FGG
  [2]: https://www.pololu.com/product/1182

title: 3-5v micro stepper connected to A4988 driver does not move and makes whirring noise

Answers: 0


body:
I have an ADXL355 accelerometer attached to an Adafruit Feather Adalogger.  I can configure and read the sensor.  I can also write binary values to the SD card.  The problem occurs when I try to read from the sensor and then write that data to the SD card.  The only thing I can think of is I'm somehow messing up the SPI communication but I can't see where.  I looked through `pins_arduino.h` for my board and the SD Card (pin 4) is on a different register than pin 10 so I don't see how I'm breaking things.

My operations proceed like this.  Global sensor creation, `Serial.begin`, `SD.begin`, `SPI.begin`, Test sensor connection, Create file for output on SD card, Initialize sensor, Read sensor FIFO, Write to file, repeat last 2 forever.

The file is created but remains at 0 file size, ie nothing is actually written to the card.

The sensor can operate at 4 kHz which was hard to achieve using the `digitalWrite` functions so I switched to using the port registers on the Feather.  I do it like this:

    #include <SM_ADXL355_SPI_fast.h>
    #include <SPI.h>
    #include <SD.h>

    #define cardSelect 4

    ADXL355_SPIF adxl355(&DDRB, &PORTB, _BV(6)); // values taken from pins_arduino.h, tested and working on pin 10
    void setup() {
      Serial.begin(57600);
      while(!Serial){
        // wait for Serial
      }
      SD.begin(cardSelect);
      SPI.begin();
      while(!adxl355.TestConnection()){
        delay(1000);
      }
      adxl355.OpenFile("TestSPI.bin");
      adxl355.Initialize(1, 10, 0); // set range to 2g's, frequency to 4 Hz and filter to off
    }

    void loop() {
      while(true){ // avoid Arduino overhead of their loop function
        adxl355.ReadFIFO();
        adxl355.WriteFIFOToFile();
      }
    }

Here is the ADXL constructor

    ADXL355_SPIF::ADXL355_SPIF(volatile uint8_t * outReg, volatile uint8_t * outPort, uint8_t bitValue) : sensorOutReg(outReg), sensorPort(outPort), sensorBitValue(bitValue){
     *sensorOutReg |= sensorBitValue;
     *sensorPort |= sensorBitValue;
     sensorWriteCount = 0;
    }

`TestConnection` tests that the DeviceID reads `0xAD`.  `Initialize` sets the G range, sample rate in Hz and filter.  I have tested these with serial output and they work properly.

`OpenFile` looks like this:

    bool ADXL355_SPIF::OpenFile(const String& fileName){
     sensorFile = SD.open(fileName, FILE_WRITE);
     if (!sensorFile){
      Serial.print("Could not create file: ");
      Serial.println(fileName);
      return false;
     }
     return true;
    }

After running this a file does get created on the SD card called "TESTSPI.BIN" with 0 file size.

`ReadFIFO` reads the numbers of entries in FIFO, stored as `fifoCount` and then populates a buffer (`sensorFIFO[32][3]`) with the values from the FIFO.  I've printed this buffer to Serial to show that it's working.  Here is that function

    void ADXL355_SPIF::ReadFIFO(){
     ReadRegister(ADXL355_RA_FIFO_ENTRIES, 1);
     fifoCount = buffer[0];
     ReadFIFOInternal();
     return;
    }

    void ADXL355_SPIF::ReadFIFOInternal(){
     SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
     *sensorPort &= ~sensorBitValue;
     uint8_t spiCommand = ADXL355_RA_FIFO_DATA << 1 | ADXL355_READ;
     SPI.transfer(spiCommand);
     int i = 0;
     unsigned long tempV;
     unsigned long value;
     while(i < fifoCount){
      for (int ptr = 0; ptr < 3; ++ptr){
       buffer[0] = SPI.transfer(0x0);
       value = buffer[0];
       value <<= 12;
       tempV = SPI.transfer(0x0);
       tempV <<= 4;
       value |= tempV;
       tempV = SPI.transfer(0x0);
       tempV >>=4;
       value |= tempV;
       if (buffer[0] & 0x80) {
        value |= 0xFFF00000;
       }
       long lValue = static_cast<long>(value);
       sensorFIFO[i][ptr] = scaleFactor * lValue;
      }
      i += 3;
     }
     SPI.endTransaction();
     *sensorPort |= sensorBitValue;
     return;
    }

Here is `WriteFIFOToFile`:

    void ADXL355_SPIF::WriteFIFOToFile(){
     if (fifoCount > 0){
      sensorFile.write(reinterpret_cast<const char *>(&sensorFIFO), 4 * fifoCount);
     }
     sensorWriteCount += fifoCount;
     if (sensorWriteCount >= 100){
      sensorFile.flush();
      sensorWriteCount = 0;
     }
    }

After allowing this to run for a while the file size is always 0.  I tried a simple binary write function just to test the card.  It looks like this and it worked.

    #include <SD.h>

    #define cardSelectPin 4

    const float pi=3.14159;

    File oFile;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      while(!Serial){
        // wait for serial
      }
      SD.begin(cardSelectPin);
      oFile = SD.open("Test.bin", FILE_WRITE);
      Serial.println(sizeof(int));
      Serial.println(sizeof(float));
      float testFloat[32][3];
      for (int i = 0; i < 32; ++i){
        for (int j = 0; j < 3; ++j){
          testFloat[i][j] = pi * (i + 1) + j;
        }
      }
      oFile.write(reinterpret_cast<const char *>(&testFloat), sizeof(float) * 96);
      oFile.close();
      Serial.println("Finished writing file.");
    }

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

    }

title: SD card fails to write when used with another SPI device

Answers: 1

body: The problem here was caused by `flush` never being called within `WriteFIFOToFile`.  The variable `sensorWriteCount` was defined incorrectly.  Changing to call `flush` directly after each `write` statement fixed the problem.  This lead to the debugging of the `if` statement and variable.


body:
**A0 pin not working when full PV system in use**

I am using the [DFRobot Leonardo with Xbee R3][1]. I am using the A0 pin to read a 0-5V voltage from my voltage sensor, which samples and steps down 130VDC from a solar panel, in parallel to 0-5V for my Arduino to read.

[Album with all relevant images][2]

PV Array is 7 Panels in Series, Vpeak 18.7V Apeak: 11.23A
[![Voltage Sensor in Parallel][3]][3]
[![Voltage Divider to step down to 0-5V range][4]][4]
[![Full circuit layout][5]][5]

When the PV system is in open circuit mode (not connected to the grid), A0 can read the voltage without any issues and output's it into my serial monitor.
When the PV system is connected to the grid, A0 seemly shut's itself off and i no longer get any serial output. Testing with multimeter shows that the A0 pin is still getting a voltage in the range of 0-5V.

My assumption is that when a load is applied to the system, either A0 shuts itself down to protect the board for some reason, or the current is not flowing through the voltage sensing circuit due to it's higher resistance.

Current sensor is a 0-20A ACS712 board.

  [1]: https://www.dfrobot.com/product-832.html
  [2]: https://i.stack.imgur.com/bXb3a.jpg
  [3]: https://i.stack.imgur.com/jNEtw.png
  [4]: https://i.stack.imgur.com/ripcP.png
  [5]: https://i.stack.imgur.com/4HeZq.png

title: ADC pin shutting off on its own under certain condition

Answers: 0


body:
I am having a problem with pins of Arduino Uno. I have connected a LED to one of the analog pins (A0), and I want to light up the LED with different intensinty.

    int ledPin = A0;
    void setup() {
     // put your setup code here, to run once:
     pinMode(ledPin,OUTPUT);

    }

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

The point is that even if I change the value of analogWrite, the LED lights up always with the same intensity.

title: Arduino analog pins not working

Answers: 1

body:
analogWrite deals with PWM pins, those are digital pins. See https://www.arduino.cc/en/Reference/AnalogWrite

So connect the LED to one of the PWM pins and change the sketch accordingly. On the Uno those are pins 3, 5, 6, 9, 10, and 11.

The analog pins A0 - A5 are input pins. The value is read using the analogRead(pin) function.


body:
I have a project where we need to create a virtual cane for blind people and it will have 3 functions:

 - Pressure button when pressed will connect to an android phone through HC-06 Bluetooth modulo to an app that I developed and will
   can to someone that I defined

 - Temperature sensor that is attached to a buzzer that will buzz if the
   temperature is higher than 40 Degrees

 - Ultrasonic sensor attached to and vibration motor that will vibrate
   if there is any object less than 70 cm from the person.

When I combine the code from the ultrasonic and the temperature sensor, everything works fine, when I add the bluetooth code, nothing works, anyone see the problem? Or could you show me the problem and solveit?

Code without Bluetooth:

    int DHT11_PIN=8;
    dht DHT;
    int buzzer=6;
    int trigPin=3;
    int echoPin=2;
    int motor=7;

    void setup(){
      Serial.begin(115200);
      pinMode(DHT11_PIN,INPUT);
      pinMode(buzzer, OUTPUT);
      delay(5000);

      Serial.begin(9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(motor, OUTPUT);
      delay(5000);
    }

    void loop(){
      Stemperature();
      Sultrassom();
    }

    // sensor de tempratura e Buzzer-------------------------------
    void Stemperature(){
      digitalWrite(buzzer,LOW);
      DHT.read11(DHT11_PIN);
      float t=DHT.temperature;
      Serial.print("Temperature = ");
      Serial.println(t);

      if (t>40){
        digitalWrite(buzzer,HIGH);
        {tone(6,100,20);
        delay(1);
        noTone(1);
        delay(1);
        }
        delay(1000);
        Serial.print("ON T=");
      }else{
        digitalWrite(buzzer,LOW);
        Serial.print("OF T=");
      }
    }

    //Sensor de Ultrassom e Motor vibração-----------------
    void Sultrassom(){
      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) * 0.0340;
      Serial.println(distance);

      if (distance < 70){ // se a distância for menor que 70 cm o motor vibra
        digitalWrite(motor,HIGH);// quando a distância for menor que 70 cm
        Serial.print("MOTOR ON=");
      }else{
        digitalWrite(motor,LOW);// quando a distância for maior que 70 cm
        Serial.print("MOTOR OFF=");
      }
      delay(5);
    }

Bluetooth Code:

    const int buttonPin = 4;     // the number of the pushbutton pin
    boolean buttonState;         // variable for reading the pushbutton status

    void setup(){
      Serial.begin(9600);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
      buttonState = LOW;
    }

    void loop(){
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);
      // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
      if(buttonState == HIGH) {
        // send char 1 via Bluetooth:
        Serial.println("1");
        delay(20000);
        while (0);
      }
    }

title: Merging arduino code

Answers: 2

body:
In the bluetooth loop you use:

    delay(20000);
    while (0);

This means you first wait 20 seconds, and while(0) does not do anything (unuseful instruction).

Actually, this results when the button is pressed, it starts the loop again, but you have to merge both codes into one.

I would add the sending of the serial command in the code above, remove the while and see what happens. If you need some delay for debouncing reaons for the button, implement a decent deboucing algorithm instead of the delay of 20000.

And why there are two }} at the end?

body:
The following code is not tested in any way. It should give you some help, to detect the problems. First you used the same Serial connection for your PC and the Bluetooth module, which leads to problems. Second, you had some delays, which seemed useless. Third your `noTone()` function didn't matched the right pin. Also I added an Interrupt for the Button. It could be, that your DHT reading need the same Interruptprotection, which I added to the Usonic measurment. Last but not least I replaced your Pin definitions to make it more readable.

    // New Include for the bluetooth connection
    #include <SoftwareSerial.h>
    #include <dht.h>

    #define DHT11PIN        8
    #define BTRXPIN         10                    // Pay attention to your wiring
    #define BTTXPIN         11
    #define BUZZERPIN       6
    #define TRIGGERPIN      5                     // Changed, to keep an interrupt Pin free !!!
    #define ECHOPIN         4                     // Changed, to keep an interrupt Pin free !!!
    #define MOTORPIN        7
    #define BUTTONPIN       2                     // Changed to an interrupt Pin

    dht DHT;
    SoftwareSerial bluetooth(BTRXPIN, BTTXPIN);

    void setup(){
      Serial.begin(9600);                         // Only once
      bluetooth.begin(9600);                      // Serial connection for the bluetooth module
                                                  // Check your needed Baudrate
      pinMode(DHT11PIN,  INPUT);
      pinMode(BUTTONPIN, INPUT);
      pinMode(ECHOPIN,   INPUT);
      pinMode(TRIGGERPIN, OUTPUT);
      pinMode(BUZZERPIN,  OUTPUT);
      pinMode(MOTORPIN,   OUTPUT);
      digitalWrite(BUZZERPIN, LOW);

      attachInterrupt(digitalPinToInterrupt(BUTTONPIN), buttonISR, RISING); // I did not pay attention to bouncing here!!
      // I see no need for 5sec delay, so i cut it out
    }

    void loop(){
      temperatureMeasure();
      ultraSonicMeasure();
      delay(2000);                                  // 2 sec delay, so it won't measure all the time.
    }

    float temperatureMeasure(){                     // Added return types
      DHT.read11(DHT11_PIN);
      float t = DHT.temperature;
      Serial.print("Temperature = ");
      Serial.println(t);

      if (t > 40){
        tone(BUZZERPIN,100);
        delay(20);
        noTone(BUZZERPIN);
        Serial.print("ON");
      }else{
        noTone(BUZZERPIN);
        Serial.print("OFF");
      }
      return temperatureMeasure;
    }

    long ultraSonicMeasure(){
      long duration{0};
      long distance{0};
      noInterrupts();
      digitalWrite(TRIGGERPIN, LOW);
      delayMicroseconds(2);
      digitalWrite(TRIGGERPIN, HIGH);
      delayMicroseconds(10);
      digitalWrite(TRIGGERPIN, LOW);

      duration = pulseIn(ECHOPIN, HIGH);
      interrupts();
      distance = (duration/2) * 0.0340;
      Serial.println(distance);

      if (distance < 70){
        digitalWrite(MOTORPIN, HIGH);
        Serial.print("MOTOR ON");
      }else{
        digitalWrite(MOTORPIN, LOW);
        Serial.print("MOTOR OFF");
      }
      return distance;
    }

    // Called when button is pressed
    void buttonISR(){
      bluetooth.println("1");                         // Would be better, to put this outside of the ISR, but is is only on character.
    }


body:
I'm experimenting with the ESP8266 chip on a Wemos D1 R2 board. I'm trying to write some code which will allow the user to input a username and password in an HTML form then get a response as to what happened with trying to connect to the WiFi as either they connected or the password was wrong. After I've turned setup Access Point and Station mode on the device using:

        // The field here would be global so other functions can access it
        ESP8266WebServer server(80);
        server.on("/connect", handleConnect);
        server.begin();

In my handleConnect function, I check the body of the request and attempt to login:

        if(!server.hasArg("ssid") || !server.hasArg("password")) {
            server.send(200, "text/html", "You didn't submit a ssid and password");
            return;
        }

        auto ssid = server.arg("ssid");
        auto password = server.arg("password");

        WiFi.begin(ssid, password);

        auto status = WiFi.waitForConnectionResult();

        server.send(200, "text/html", String(status));

When the user inputs the correct password, the function returns the request in time and the request responds with 3 (the connection was successful). However, if the password is wrong, the request times out. I've also tried several approaches to either work-around or fix the problem such as:

 - Using a while loop and calling `WiFi.status()` and checking it and responding accordingly. This approach ends with the same request timeout if the password is wrong. An example of this would be:

        while(true) {
          delay(1000);
          auto status = WiFi.status();

          if(status == WL_CONNECTED) {
            server.send(200, "text/html", "You're connected!");
          }

          if(status == WL_CONNECT_FAILED) {
                server.send(200, "text/html", "You inputted the wrong password! Try again!");
          }
        }
 - Registering another resource to specifically only return what state the WiFi is in and in the original connect function to send back HTML with some javascript in it which calls this other resource and do the decision making of what text to display client-side but this approach always returns 0 (when the WiFi is in process of changing between statuses, quoted from the docs)

        server.on("/checkConnection", checkConnection);

        // other code

        void checkConnection() {
          server.send(WiFi.status());
        }
- And finally, I have experimented with using a public field to save the state once it has finished in the main function where the original connection tried to be established and then use the checkConnection function to return this state and this ***SOMEWHAT*** works, however, the code is messy, hacky and there must be a better way of doing this otherwise this will have to be my solution until the libraries are updated to fix this or something like that:

// public field for the status

          int status = 0;

          // other code

          void handleConnect() {

            // checking ssid and password

            WiFi.begin(ssid, password);

            // use an interval with AJAX or this to get the connection state
            server.send(200, "text/html", "Go to to check the connection");

            while(true) {
              delay(1000);
              auto s = WiFi.status();
              status = s;
              if(s = WL_CONNECTED) break;
            }

          }

          void checkConnection() {
            server.send(200, "text/html", status);
          }

Has anyone encountered this problem and if so, is there a better way of solving it apart from using a public variable which just makes it a pain in the bum to work with? Thank you.

title: ESP8266 Soft Access Point: Timeout of request of resource when not responded to in set undocumented time

Answers: 2

body:
Make the WiFi.begin outside the WebServer handler. In the handler store the ssid and password into variables and send a response. In loop() then make the WiFi.begin. For the result, pool from the browser with javascript.

[Example][1]

  [1]: https://github.com/jandrassy/arduino-firmware-wifilink/blob/master/ArduinoFirmwareEsp/WebServer.ino

body:
    WifiMulti wifiMulti;//declare global.
    wifiMulti.addAP(ssid,pass);//instead of WiFi.begin();
    int i = 0;
    //add below to wait for connection.
    while (i < 20)
      {
        if (wifiMulti.run() == WL_CONNECTED)
        {
          return (20);
        }
        delay(500);
        Serial.println(WiFi.status());
        i++;
      }


body:
**Board**: Arduino Leonardo

**IDE version**: 1.6.5(also tried with 1.8.3)

Try **Arduino Web Editor** as well

The problem: after connecting Arduino to PC via USB in 5-7 seconds IDE says that connection is losted.

Everything was OK, but after one deploy happened thing, that I described.

If it help: I connect OLED display and use it with OLED_I2C [library][1]. Sketch contains one `cpp` and one `h` file.

I'm already fully reinstall USB drivers with Arduino USB as well

  [1]: http://www.rinkydinkelectronics.com/resource/OLED_I2C/OLED_I2C.pdf

title: Arduino IDE lost board connection

Answers: 1

body:
> The problem: after connecting Arduino to PC via USB in 5-7 seconds IDE says that connection is losted.

Yes, that's normal. That's the bootloader running, and it's during that 5-7 second window that you can upload a new sketch.

Under normal circumstances the IDE will automatically reboot the board for you so the upload time window coincides with the IDE's attempt to upload a new sketch. However under some circumstances it can't, so you have to do it manually by pressing the reset button at the right time.

Also on Windows you may find that you have a different COM port for programming as you do when a sketch is running (Windows is retarded like that, you see). The IDE tries to do some magic to identify the correct COM port to use, but you have to first have the correct "sketch mode" COM port selected so it can first reboot the board into the bootloader, at which point it tries to do its magic to work out the correct COM port to use by looking to see which COM port (if any) has just appeared since rebooting.

So, in short: if the IDE can't reboot the board for you then do it manually, but note that *timing is vital*. Press the reset button a few moments *before* `avrdude` runs. It may take practice.


body: I have a system which requires me to obtain different duty cycles at different frequencies. But using the analogWrite() does not allow me to obtain a value lower than 1/255 duty cycle. I need to obtain lower duty cycle values for 1Hz

title: Is it possible to obtain %0.05 duty cycle at 1hz in arduino?(a 500us square pulse at 1 sec period)

Answers: 3

body:
Sure - if you program it to.

1. Turn on an output.
2. Wait for 500µs less the amount of time it took to turn on the output
3. Turn off the output
4. Wait for 0.9995 seconds minus the amount of time it took to turn off the output
5. Go to 1.

You would probably find using the `micros()` function easiest to get the timing right - in exactly the same way as the `BlinkWithoutDelay` example in the IDE.

Also [direct port manipulation](https://www.arduino.cc/en/Reference/PortManipulation) may be of benefit to make things as fast as possible.

body:
Expanding from my comment. This is an attempt to generate that signal with Timer 1. <s>No time to test it now...</s> **Edit**: tested, works as advertised.

    /*
     * Configure Timer 1 to generate a slow, low duty cycle PWM signal.
     * Output pin = digital 9 = PB1 = OC1A.
     */

    const float PWM_PERIOD  = 1.0;     // 1 s
    const float PULSE_WIDTH = 500e-6;  // 500 us

    /*
     * With a 16 MHz clock and this prescaler, the resolution is 16 us and
     * the maximum period is 1.048576 s.
     */
    const uint16_t TIMER_PRESCALER = 256;
    const float F_TIMER = F_CPU / TIMER_PRESCALER;

    void setup()
    {
        // Configure Timer 1.
        DDRB  |= _BV(PB1);    // set PB1 = OC1A as output
        ICR1   = round(PWM_PERIOD * F_TIMER) - 1;
        OCR1A  = round(PULSE_WIDTH * F_TIMER) - 1;
        TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
               | _BV(WGM11);  // fast PWM mode, TOP = ICR1
        TCCR1B = _BV(WGM12)   // ditto
               | _BV(WGM13)   // ditto
               | _BV(CS12);   // clock at F_CPU/256 = 62.5 kHz
    }

    void loop() {}

body:
Sure. Two easy way to do it.

1. 0,05 percent is 1:2000. So modify timer settings to produce a pen of the desired frequency and duty cycle.

2. Use timer interrupt: either the overflow or compare match interrupt. In the first case, load the timer with -duty cycle and -(period - duty) to produce a wave form of duty cycle / period.

The same can be done using compare match as well: just advance the match point alternately.

edit: to show how it can be done with compare match, here is what I have:

    #define PR_PWM    (F_CPU / 256 / 10)  //period for the pwm waveform
    #define PR_ON   (PR_PWM * 25 / 100)   //prescaler at 256:1, 25% duty cycle
    #define PR_OFF   (PR_PWM - PR_ON)   //pin off period, to achieve 1Hz
    //end hardware configuration

    //global defines

    //global variables

    //timer1 ch a compare match isr
    ISR(TIMER1_COMPA_vect) {
     static char pr_index=0;  //0->PR_ON, 1->PR_OFF

     //clear the flag  -  done automatically
     //advance to the next match point
     if ((pr_index++ & 0x01) == 0) {
      OCR1A += PR_ON;
      IO_SET(PWM_PORT, PWM); //set the pin on
     } else {
      OCR1A += PR_OFF;
      IO_CLR(PWM_PORT, PWM); //clear the pin
     }

    }

for this demo, we tried to generate a 25% duty cycle pwm with a period of 100ms. Here is the output of that code.

[![enter image description here][1]][1]

The follow changes the duty cycle to 0.05%:

    #define PR_ON   (PR_PWM * 0.05 / 100)   //prescaler at 256:1, 0.05% duty cycle

and the corresponding output is:

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/Erw9v.png
  [2]: https://i.stack.imgur.com/ty4Bk.png

Now, there are other ways to do it, for example, with higher resolution, or more precision, ..., but at the cost of more coding.

But the basic concept is the same.

hope it helps.

edit2: for those brave souls, the isr can be simplified to:

    OCR1A += (pr_index++&0x01)?PR_OFF:PR_ON;  //advance the match point
    IO_FLP(PWM_PORT, PWM);  //flip the pwm pin


body:
I want to use an Arduino Yun as ISP to program an Attiny85. I have soldered a shield following the circuit that is depicted in many sites. You can see it in [this][1] page.

I have included a LED with a 1k resistor in series connected between pin 5 (PB0) and ground so that I can monitor.

I have setup my sketch environment (Arduino 1.6.12) with the definitions of the Attiny so that I can select this board (Attiny85) with it's associated parameters.

I have defined in Arduino 1.6.12 the board in this way:

- Board: "ATtiny25/45/85"
- Processor: "ATtiny85"
- Clock: "Internal 1MHz"
- Port: "192.168.1.109 (Arduino Yún)"

I use this port instead of the serial USB port as I had many issues with the serial USB port.

I have started with the Blink sketch modifying it to use pin0
The sketch is this one:

    // the setup function runs once when you press reset or power the board
    int LED = 0;  //0 para Attiny
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED, OUTPUT);
    }

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

The output of the sketch loading in verbose mode is this one:

    El Sketch usa 672 bytes (8%) del espacio de almacenamiento de programa. El máximo es 8.192 bytes.
    Las variables Globales usan 9 bytes (1%) de la memoria dinámica, dejando 503 bytes para las variables locales. El máximo es 512 bytes.
    /usr/bin/run-avrdude /tmp/sketch.hex -v -pattiny85

    avrdude: Version 6.1, compiled on Apr  8 2016 at 15:56:17
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "/etc/avrdude.conf"
             User configuration file is "/root/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : unknown
             Using Programmer              : linuxgpio
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    10     8    0 no       1024    8      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : linuxgpio
             Description     : Use the Linux sysfs interface to bitbang GPIO lines
             Pin assignment  : /sys/class/gpio/gpio{n}
               RESET   = ~18
               SCK     =  11
               MOSI    =  27
               MISO    =  8

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e9587
    avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
             To disable this feature, specify the -D option.
    avrdude: erasing chip
    avrdude: reading input file "0xFF"
    avrdude: writing lfuse (1 bytes):

    Writing | ################################################## | 100% 0.00s

    avrdude: 1 bytes of lfuse written
    avrdude: verifying lfuse memory against 0xFF:
    avrdude: load data lfuse data from input file 0xFF:
    avrdude: input file 0xFF contains 1 bytes
    avrdude: reading on-chip lfuse data:

    Reading | ################################################## | 100% 0.00s

    avrdude: verifying ...
    avrdude: 1 bytes of lfuse verified
    avrdude: reading input file "0xD8"
    avrdude: writing hfuse (1 bytes):

    Writing | ################################################## | 100% 0.00s

    avrdude: 1 bytes of hfuse written
    avrdude: verifying hfuse memory against 0xD8:
    avrdude: load data hfuse data from input file 0xD8:
    avrdude: input file 0xD8 contains 1 bytes
    avrdude: reading on-chip hfuse data:

    Reading | ################################################## | 100% 0.00s

    avrdude: verifying ...
    avrdude: 1 bytes of hfuse verified
    avrdude: reading input file "0xFB"
    avrdude: writing efuse (1 bytes):

    Writing | ################################################## | 100% 0.00s

    avrdude: 1 bytes of efuse written
    avrdude: verifying efuse memory against 0xFB:
    avrdude: load data efuse data from input file 0xFB:
    avrdude: input file 0xFB contains 1 bytes
    avrdude: reading on-chip efuse data:

    Reading | ################################################## | 100% 0.00s

    avrdude: verifying ...
    avrdude: 1 bytes of efuse verified
    avrdude: reading input file "/tmp/sketch.hex"
    avrdude: writing flash (672 bytes):

    Writing | ################################################## | 100% 0.40s

    avrdude: 672 bytes of flash written
    avrdude: verifying flash memory against /tmp/sketch.hex:
    avrdude: load data flash data from input file /tmp/sketch.hex:
    avrdude: input file /tmp/sketch.hex contains 672 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 0.57s

    avrdude: verifying ...
    avrdude: 672 bytes of flash verified

    avrdude done.  Thank you.

What looks pretty normal for me. When the load is ongoing, I see the 1st thing that puzzles me: LED connected to pin 5 (PWM0) doesn't blink quickly. I have tested the polarity of the LED with a +5V connected to the physical pin of the chip and 0V connected to GND and it lights.

The second thing that puzzles me is that I get exactly the same output when I remove the programming shield (no Attiny at all) and I click on upload and the output is the same.  Is the Arduino IDE caching this output?

When I put the "programmed" Attiny in a breadboard and I power it and connect one LED to port 5, it doesn't blink as per the Blink sketch.

I am quite a newby with Arduino and ATtiny85. I only wan to be able to program this ATtiny85 with my Arduino Yún

What am I doing wrong?
Could you give some light to this darkness?

  [1]: https://arduinodiy.wordpress.com/2012/02/28/program-an-attiny-with-an-arduino-nano

title: Arduino Yún as ISP to program Attiny - why is the sketch not working after successful upload?

Answers: 1

body:
It's not programming a non-existent ATtiny, it's quite explicitly stating in the output that it is programming an ATmega32u4 - and that would be the "Arduino" part of the YUN.

It's not clear that the YUN is really intended to ISP other targets.

If you can get serial communication to the ATmega32U4, you could try to find a compatible variation of the ISP sketch to load on that, and in turn use it to program an ATtiny.

Or you could try to define a different set of programming pins, but this may be tricky.

Essentially, what you are trying to do is a bit unusual, and will likely require investing some real time in understanding the existing / available mechanisms enough to adapt them to a fairly unique goal.

Otherwise, just get an Uno or similar and use that to ISP your ATtiny.


body:
I'm trying to get two arduino uno to communicate. The slave reads a temp sensor as an analog value, then converts it to degrees C, then sends that value to the master, the master then prints the value to the serial monitor. This is the code I have thus far.

for the slave

    const int tempPin = A0;

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

      void loop() {

       //read sensor data to a variable
       float volt = analogRead(tempPin) * 0.004882814;
       float degC = (volt - 0.5) * 100.0;
       Serial.println(degC);

       delay(2000); //Not to flood serial port
      }

this is the code for the master

    float tempC;
    void setup(){
      Serial.begin(9600);
      delay(2000);
     }

      void loop() {
     /**  check if data has been sent from the computer: */
     while (Serial.available()) {
     /* read the most recent byte */
        tempC = Serial.read();     //now byteRead will have latest sensor
                                  // data sent from Arduino1

        Serial.println(tempC);
      }
    }

My issue is that I am reading on the serial monitor 4 different 2 integer values

title: Arduino Serial Communication Between 2 Uno

Answers: 1

body:
Your slave is sending an array of characters and your master is reading the ASCII values of those characters.

If you send 25.43, `Serial.println` will send 7 characters `2`, `5`, `.`, `4`, `3`, carriage return and a newline.

The master will read them as 50, 53, 46, 52, 51, 13 and 10. Your code then prints:

<!-- language: none -->

    50.00
    53.00
    46.00
    52.00
    51.00
    13.00
    10.00

On your master, the `loop()` should look like:

    void loop() {
      if (Serial.available()) {
        char c = Serial.peek(); // just look at the next character on the serial buffer
        if (c == '\r' || c == '\n') // ignore the carriage return and newline characters
          Serial.read(); // remove the character from serial buffer by reading it
        else {
          tempC = Serial.parseFloat(); // read and parse the string representing the float value
          Serial.println(tempC);
        }
      }
    }


body:
For my program I have to sense 3 inputs (`A1`, `A2` and `A3` in Arduino). If any one or two or more signals become zero (low), it goes in different case as per below program.

However, I want to reset the Arduino when all signals become high again. Therefore I have to again write another program `loop2()`.

So how can I exit from one loop and get into another loop. If I have to use `goto`, please tell me how to use it?

The Arduino program given below.

    const int analogPin1 = A1;
    const int analogPin2 = A2;
    const int analogPin3 = A3;
    const int ledPin = 13;
    const int ledPin2 = 7;
    const int  thresold = 400;
    unsigned int x1,x2,x3,fault = 0;

    void setup()
    {
        pinMode(ledPin, OUTPUT);
        Serial.begin(9600);
    }

    void Config()
    {
        delay(1000);
        Serial.print("ATE0r");
        Response();
        Serial.print("ATr");
        Response();
        Serial.print("AT+CMGF=1r");
        Response();
        Serial.print("AT+CNMI=1,2,0,0,0r");
        Response();
    }

    void Response()
    {
        int count = 0;
        Serial.println();
        while(1)
        {
            if(Serial.available())
            {
                char data =Serial.read();
                if(data == 'K'){Serial.println("OK");break;}
                if(data == 'R'){Serial.println("GSM Not Working");break;}
            }
            count++;
            delay(10);
            if(count == 1000){Serial.println("GSM not Found");break;}

        }
    }

    void loop()
    {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);

        if (analogValue1 < thresold)
        { x1=1;
            fault=x1;
        }
        if (analogValue2 < thresold)
        {  x2=x1+3;
            fault=x2;
        }
        if (analogValue3 < thresold)
        {  x3=x1+x2+5;
            fault=x3;
        }

        switch(fault)
        {
        case 1:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919512700997\"\r");
            delay(1000);
            Serial.print("PHASE 1 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            loop2();
            break;

        case 3:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919512700997\"\r");
            delay(1000);
            Serial.print("2 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            break;

        case 4:
            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919512700997\"\r");
            delay(1000);
            Serial.print("1 AND 2 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            break;

        case 5:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919512700997\"\r");
            delay(1000);
            Serial.print("3 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            Serial.print("AT+CNMI=2,2,0,0,0");
            break;

        case 6:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919512700997\"\r");
            delay(1000);
            Serial.print("1 AND 3 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            break;

        case 8:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919512700997\"\r");
            delay(1000);
            Serial.print("2 AND 3 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            break;

        case 10:

            digitalWrite(ledPin, HIGH);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919512700997\"\r");
            delay(1000);
            Serial.print("ALL 3 HAS GONE");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            break;

        default:
            x1,x2,x3,fault=0;
            digitalWrite(ledPin, LOW);
            break;

        }

        x1,x2,x3,fault=0;
        digitalWrite(ledPin, LOW);
        do
        {
            int analogValue1 = analogRead(analogPin1);
            int analogValue2 = analogRead(analogPin2);
            int analogValue3 = analogRead(analogPin3);
        }
        while ( analogValue1 < thresold || analogValue2 < thresold || analogValue3 < thresold );

    }

    do
    {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);
    }
    while (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));

    }

    void loop2()
    {
        if (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th))
        {

            digitalWrite(ledPin, HIGH);
            Serial.begin(9600);
            Serial.print("\r");
            delay(1000);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919512700997\"\r");
            delay(1000);
            Serial.print("Nikunjsinh2");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);
            Serial.print("\r");
            delay(1000);
            Serial.print("AT+CMGF=1\r");
            delay(1000);
            Serial.print("AT+CMGS=\"+919712554766\"\r");
            delay(1000);
            Serial.print("Nikunjsinh2");
            delay(1000);
            Serial.write(0x1A);
            delay(1000);

            do
            {
                int analogValue1 = analogRead(analogPin1);
                int analogValue2 = analogRead(analogPin2);
                int analogValue3 = analogRead(analogPin3);
            }
            while (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
        }
    }

title: How to Jump from one loop to another while executing

Answers: 1

body:
It is clear from your question you intuitively know this program will not perform as desired.  Simply put, if you do not check all states during every loop, you can not possibly react to all possibilities.  Therefore you can only have 1 loop.  Get rid of the other loops.

> ...but i want to reset arduino when all signal becomes again high...

This statement identifies what is missing.  You need a temporal aspect to the loop in order to "remember" that all signal(s) were not high on the previous loop and now in the current loop they are all high.

Programmers commonly refer to this feature as a [Finite State Machine][1].  A way to "remember" what state the loop was in the last time it was executed.  And a way to know what state(s) is(are) next possible.

If all you need to remember is that not all 3 inputs were high the last time through the loop, your state machine only needs the one value.  And that value only needs to be a zero or one.

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine


body:
I got an Arduino Uno set up as an I2C master to an ATtiny85 slave, using the Wire (Master) and TinyWireS (Slave) libraries.

Communication works well. I have been able to keep the network running correctly for hours. However, I have not been able to let the master request more than a single byte from the slave.

Using the code below the master asks for 4 bytes from the slave, but in my serial console I get only an actual value for the first bytes. The next three bytes read 255.

How can I request multiple bytes from the slave, using the Wire library?

---

Master (Arduino Uno)

    #include <Wire.h>

    #define I2C_MASTER_ADDR 0x04
    #define I2C_SLAVE_ADDR 0x05

    int pollInterval = 700;//Milliseconds
    unsigned long lastPoll = 0;

    void setup()
    {
      Wire.begin(I2C_MASTER_ADDR);  // join i2c bus
      Serial.begin(115200);
      Serial.println("Setup complete");
    }

    /*
     * The main loop
     */
    int i = 0;

    void loop()
    {

      //Writing to the slave
      if( (millis()-lastPoll) > pollInterval)
      {
        Wire.beginTransmission(I2C_SLAVE_ADDR);
        Wire.write(0x01);//Register to start at
        switch(i)
        {
          case 0:
            Wire.write(255);
            Wire.write(0);
            Wire.write(0);
            i++;
            break;
          case 1:
            Wire.write(0);
            Wire.write(255);
            Wire.write(0);
            i++;
            break;
          case 2:
            Wire.write(0);
            Wire.write(0);
            Wire.write(255);
            i = 0;
            break;
        }
        Wire.endTransmission();

        delay(1);//Dont let the slave panic

        //Set the register pointer back to 0x01, preparing for a read
        Wire.beginTransmission(I2C_SLAVE_ADDR);
        Wire.write(0x00);//Register to start at
        Wire.endTransmission();
        delay(1);//Dont let the slave panic

        //Get values from the three registers up from 0x01
        Wire.requestFrom(I2C_SLAVE_ADDR, 4);//Request N bytes
        while (Wire.available())
        {
          uint8_t next_byte = Wire.read();
          Serial.print(next_byte);Serial.print(" ");
        }
        Serial.println("\n");

        lastPoll = millis();
      }//End if time to poll again

    }//End loop

Slave - ATTiny85

    #include <EEPROM.h>
    #include <TinyWireS.h>
    #include <Bounce2.h>
    #include <WS2812.h>
    #ifdef __AVR__ //Which will be true for ATtiny85
      #include <avr/power.h>
    #endif

    #define I2C_SLAVE_DEFAULT_ADDR 0x05
    #define BUTTON_DEBOUNCE 5//Debounce milliseconds

    #define NEOPIXEL_PIN  1
    #define BUTTON_PIN    3

    #define NUMPIXELS     1

    /*
     * I2C Registers
     *
     * Register map:
     * 0x00 - Button state
     * 0x01 - led value red
     * 0x02 - led value green
     * 0x03 - led value blue
     *
     * Total size: 4
     */
    const byte reg_size = 4;
    volatile uint16_t i2c_regs[reg_size];

    /*
     * Internal variables
     */
    cRGB value;
    volatile boolean led_needs_update = false;
    volatile byte reg_position;

    /*
     * Initialize instances/classes
     */
    Bounce button = Bounce();
    WS2812 led(NUMPIXELS);

    void setup()
    {
      //Start I2C
      //uint8_t _device_addr = EEPROM_DATA::get_device_addr();
      TinyWireS.begin(I2C_SLAVE_DEFAULT_ADDR);
      TinyWireS.onReceive(i2cReceiveEvent);
      TinyWireS.onRequest(i2cRequestEvent);

      //Start Led
      led.setOutput(NEOPIXEL_PIN);
      value.b = 255; value.g = 0; value.r = 0;
      led.set_crgb_at(0, value); //Set value at LED found at index 0
      led.sync(); // Sends the value to the LED

      //Start Button
      pinMode(BUTTON_PIN, INPUT_PULLUP);
      button.attach(BUTTON_PIN);
      button.interval(BUTTON_DEBOUNCE);

    }

    void loop()
    {
      button.update();

      if(led_needs_update)
      {
        led_update();
        led_needs_update = false;
      }

      if(button.fell())
      {
        i2c_regs[0x00] = true;
      }
      if(button.rose())
      {
        i2c_regs[0x00] = false;
      }

      // This needs to be here for the TinyWireS lib
      TinyWireS_stop_check();

    }

    /*
     * I2C Handelers
     */
    void i2cReceiveEvent(uint8_t howMany)
    {
        if (howMany < 1)
        {
            return;// Sanity-check
        }

        reg_position = TinyWireS.receive();
        howMany--;
        if (!howMany)
        {
            return;// This write was only to set the buffer for next read
        }

        while(howMany--)
        {
            //Store the recieved data in the currently selected register
            i2c_regs[reg_position] = TinyWireS.receive();

            //Proceed to the next register
            reg_position++;
            if (reg_position >= reg_size)
            {
                reg_position = 0;
            }
        }
        led_needs_update = true;
    }//End i2cReceiveEvent()

    void i2cRequestEvent()
    {
        //Send the value on the current register position
        TinyWireS.send(i2c_regs[reg_position]);

        // Increment the reg position on each read, and loop back to zero
        reg_position++;
        if (reg_position >= reg_size)
        {
            reg_position = 0;
        }
    }//End i2cRequestEvent

    /*
     * Helper functions
     */
    void led_update()
    {
      cRGB val;
      val.r = i2c_regs[0x01];
      val.g = i2c_regs[0x02];
      val.b = i2c_regs[0x03];
      led.set_crgb_at(0, val);
      led.sync(); // Sends the value to the LED
    }

title: I2C requesting more than one byte

Answers: 1

body:
This is another case where the Arduino documentation is horribly incomplete to the point of being useless, and you must refer to the source code itself.

Presuming your TinyWire library works like the ordinary Arduino Wire, you need to use the two-argument form of the write method:

    size_t TwoWire::write(const uint8_t *data, size_t quantity)

So your handler would probably look like this

    void i2cRequestEvent()
    {
        TinyWireS.write(i2c_regs, sizeof(i2c_regs));
    }

However, you're also going to need to change your definition to an 8-bit type, rather than the 16-bit one you surprisingly had

    volatile uint8_t i2c_regs[reg_size];

If you really do need to use a 16-bit type, then you'll need to either double the transfer size (since both processors are AVRs you won't hit any byte order issues) or first copy the values that you care about to a byte buffer.


body:
Can I send data using nRF24L01 with Arduino through multiple pipes?
As by using the RF24 library, I can send data through just one pipe and receive on the 6 pipes that nRF24L01 has.

title: Sending data by nRF24L01 with Arduino

Answers: 1

body:
Yes, but the nRF24L01 can only transmit one message at at time, since it only has one buffer.

So roughly speaking, for each message

 1. Set the transmit pipe address (if different than the last one)
 2. Send data
 3. Wait for completion (and ack or failure, if in that mode)