body:
I really want to understand how can I use this library for my purposes.

I'm trying to encrypt a message that comes through the serial port of the Arduino, and send it through another serial port. But I'm having issues understanding how to use the library.
I have read the documentation of the library, but I still get errors, I need a little help with this.

This is the code I have (without involving the serial ports), initially I wanted to check if I could define my strings and use them in another way instead of using the TestVector Function:

     #include <Crypto.h>
     #include <Speck.h>
     #include <SpeckSmall.h>
     #include <SpeckTiny.h>
     #include <string.h>

     struct EncryptText
     {
         const char *name;
         byte key[32];
         byte plaintext[16];
         byte ciphertext[16];
     };

     EncryptText test ;

       static TestCipher {

       test.name = "Speck-128-ECB";
       test.key = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                         0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00};
       test.plaintext = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                         0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20};
      test.ciphertext = {0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                         0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18};
       }

    Speck speck;
    SpeckSmall speckSmall;
    SpeckTiny speckTiny;

    byte buffer[16];

    //void testCipher(BlockCipher *cipher, const struct TestVector *test, size_t keySize, bool decryption = true)
    void testCipher(BlockCipher *cipher, size_t keySize, bool decryption = true)

    {

        Serial.print(" Encryption ... ");
        cipher->setKey(key, keySize);
        cipher->encryptBlock(buffer, plaintext);

        for(byte b=0; b<16; b++)
       {
          Serial.print(buffer[b], HEX);
       }

        if (memcmp(buffer, ciphertext, 16) == 0)
            Serial.println("Passed");
        else
            Serial.println("Failed");

        if (!decryption)
            return;

        Serial.print(" Decryption ... ");
        cipher->decryptBlock(buffer, ciphertext);

        for(byte b=0; b<16; b++)
       {
          Serial.print(buffer[b], HEX);
       }
        if (memcmp(buffer, plaintext, 16) == 0)
            Serial.println("Passed");
        else
            Serial.println("Failed");
    }

I'm getting the error: "exit status 1 'TestCipher' does not name a type"

EDIT: The full error that I get is:

     Speck_4-08-2017:27: error: 'TestCipher' does not name a type    static
     TestCipher {
               ^ Speck_4-08-2017.ino: In function 'void testCipher(BlockCipher*, size_t, bool)': Speck_4-08-2017:62: error:
     'key' was not declared in this scope
          cipher->setKey(key, keySize);
                         ^ Speck_4-08-2017:63: error: 'plaintext' was not declared in this scope
          cipher->encryptBlock(buffer, plaintext);
                                       ^ Speck_4-08-2017:70: error: 'ciphertext' was not declared in this scope
          if (memcmp(buffer, ciphertext, 16) == 0)
                             ^ Speck_4-08-2017:80: error: 'ciphertext' was not declared in this scope
          cipher->decryptBlock(buffer, ciphertext);
                                       ^ Speck_4-08-2017.ino: In function 'void perfCipher(BlockCipher*, const TestVector*, size_t, bool)':
     Speck_4-08-2017:104: error: 'key2' was not declared in this scope
              cipher->setKey(key2, keySize);
                             ^ Speck_4-08-2017.ino: In function 'void setup()': Speck_4-08-2017:158: error: 'testVectorSpeck128' was not
     declared in this scope
          testCipher(&speck, &testVectorSpeck128, 16);
                              ^ exit status 1 'TestCipher' does not name a type

Any guidance would be very helpful.

title: Usage of Crypto Library (Speck)

Answers: 2

body:
It looks like you want to create a struct and initialize it. Like this:

    struct EncryptText
    {
        const char *name;
        byte key[32];
        byte plaintext[16];
        byte ciphertext[16];
    };

    EncryptText test = {
        "Speck-128-ECB",
        {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                         0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
        {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                         0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
        {0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                         0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18}
    };

Then it appears you want to use that object. Note that to access each member of the struct you have to use dot notation (ex: `test.key`):

    void testCipher(BlockCipher *cipher, size_t keySize, bool decryption = true)
    {
        Serial.print(" Encryption ... ");
        cipher->setKey(test.key, keySize);
        cipher->encryptBlock(buffer, test.plaintext);

        for(byte b=0; b<16; b++)
        {
            Serial.print(buffer[b], HEX);
        }

        if (memcmp(buffer, test.ciphertext, 16) == 0)
            Serial.println("Passed");
        else
            Serial.println("Failed");

        if (!decryption)
            return;

        Serial.print(" Decryption ... ");
        cipher->decryptBlock(buffer, test.ciphertext);

        for(byte b=0; b<16; b++)
        {
            Serial.print(buffer[b], HEX);
        }
        if (memcmp(buffer, test.plaintext, 16) == 0)
            Serial.println("Passed");
        else
            Serial.println("Failed");
    }

body:
The first error looks like this

     Speck_4-08-2017:27: error: 'TestCipher' does not name a type    static
     TestCipher {

Further errors are basically all caused by that one wrongly written declaration. It could be fixed by declaring the first struct properly.
Compare this example code you have

    struct TestVector
    {
        const char *name;
        byte key[32];
        byte plaintext[16];
        byte ciphertext[16];
    };

    static TestVector const testVectorSpeck256 = {
        .name        = "Speck-256-ECB",
        .key         = {0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18,
                        0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
                        0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                        0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
        .plaintext   = {0x65, 0x73, 0x6f, 0x68, 0x74, 0x20, 0x6e, 0x49,
                        0x20, 0x2e, 0x72, 0x65, 0x6e, 0x6f, 0x6f, 0x70},
        .ciphertext  = {0x41, 0x09, 0x01, 0x04, 0x05, 0xc0, 0xf5, 0x3e,
                        0x4e, 0xee, 0xb4, 0x8d, 0x9c, 0x18, 0x8f, 0x43}
    };

and your code

    struct EncryptText
     {
         const char *name;
         byte key[32];
         byte plaintext[16];
         byte ciphertext[16];
     };

     EncryptText test ;
       static TestCipher {

       test.name = "Speck-128-ECB";
       test.key = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                         0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00};
       test.plaintext = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                         0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20};
      test.ciphertext = {0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                         0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18};
       }

You wrote `EncryptText test;` by specifying the type `EncryptText` you defined before and a name `test`, but now, you can assign to test by just using `test.` + variable name and nothing else (no `static TestCipher{}`). Or you could use what the example does, it basically just skips the `EncryptText test;` part and puts it on one line, like `static TestVector const testVectorSpeck128 = {` and assigns inside the curly brackets just using `.` + variable name (without `test` or `testVectorSpeck128`).

Now, the second error

     'key' was not declared in this scope
          cipher->setKey(key, keySize);

is that the variable `key` is not defined in the function `testCipher` just like the error says, you have to define that variable or use the right one, in the example it was done using a function parameter (you commented out) `TestVector *test`, it was dereferenced and accessed with `test->key`. I assume you've properly defined that struct now, there's no need to deal with pointers and with direct reference to the data you can use it elsewhere by just using something like this

    cipher->setKey(test.key, keySize);

rest of the errors are of similar fashion and can be fixed by just adding `test.` like I showed. If you fix those errors rest should be simple already.

As you are just learning, take small steps modifying the examples and use the `Verify` button as often as possible, Arduino IDE also has a button to autoformat code, use it, makes your code more readable for you and everyone else.


body:
I have an ultrasonic sensor that came with a couple of images about the pin-out and wiring diagram.

I am used to the popular ultrasonic sensors that have lots of documentation about how to connect to an Arduino - but I am wondering about to connect this sensor to an Arduino.

The Power Supply is 5V DC, with an operating current less than or equal to 12mA.

Any support or similar tutorials that will help me connect this to an Arduino, to see the output in the Serial monitor, would be great!

VCC and GND are self-explanatory, but how should I connect the Output 1 and Output 2 to the Arduino?

Thanks!

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

  [1]: https://i.stack.imgur.com/HLe6Y.jpg
  [2]: https://i.stack.imgur.com/BHcma.jpg

title: Connecting an Ultrasonic Sensor to Arduino (4-Wire)

Answers: 0


body:
I have a Blueduino Rev2 board that I would like to have communicating with a web app ([running the chrome bluetooth software][1]) but I'm having trouble sorting out the service UUIDs that the web bluetooth library requires.

According to the wiki, it uses the service UUID 0xFFF0, write characteristic UUID 0xFFF1 and read characteristic UUID 0xFFF2 ([source][2]) but when I scan for the device through the web app filtering for that service UUID it doesn't appear, but does when I remove the service UUID filter.

Code used to scan for the blueduino:

    navigator.bluetooth.requestDevice({
        filters: [{
            name: 'ZeroBeacon',
            services: [0xFFF0]
        }]
    })

Does anyone know what the UUIDs are that I should be using? The documentation is quite unclear and lacking.

  [1]: https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web
  [2]: http://wiki.aprbrother.com/wiki/Firmware/ZeroBeacon#Features

title: Blueduino Rev2 service UUID for web bluetooth

Answers: 1

body:
If the 0xFFF0 Bluetooth Service is not advertised by the Blueduino Rev2 board, you should not include it in the "services" key. It should be in "optionalServices. See https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web#request_bluetooth_devices

I think your code should look like:

    navigator.bluetooth.requestDevice({
      filters: [{ name: 'ZeroBeacon' }],
      optionalServices: [0xFFF0]
    });


body: I have created a LoRa gateway using a Pi3; I have used a RFM95 module for it. So, it is a single channel gateway, and I'm operating it at 868.1Mhz. But my LoRa node(also a RFM95, on an Arduino Uno), whenever transmits data, does so on various frequencies at random, and there seems to be no pattern to it. Hence a lot of data gets lost. How can i transmit data on a particular frequency only?

title: How can I configure the RFM95 LoRa module to emit packets at only 'one' particular frequency?

Answers: 0


body:
I have a brushless motor what is hooked up to a external power supply and I'm using an arduino with a potentiometer to control it. I know that the motor has power but whenever I turn the potentiometer nothing happens. I'm wondering if my wiring is wrong. Here's the wires is connected:

First pin of the potentometer to arduino GND
Second pin of the potentometer to arduino A0
Third pin of the potentiometer to arduino 5V

Black wire of the ESC to arduino GND
Red wire of the ESC to VIN
White wire of the ESC to D8

I'm also using a switch to give both the arduino and motor power and they both seem to turn on fine.

Motor has external power and does twitch very slightly when powered on with this circuit but I can't get is to actually move substantially using the potentiometer.

Here's my code:

    #include <Servo.h>//Using servo library to control ESC
    Servo esc; //Creating a servo class with name as esc
    void setup()
    {
    esc.attach(8); //Specify the esc signal pin,Here as D8
    esc.writeMicroseconds(1000); //initialize the signal to 1000
    Serial.begin(9600);
    }
    void loop()
    {
    int val; //Creating a variable val
    val= analogRead(A0); //Read input from analog pin a0 and store in val
    val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(Change if needed)
    esc.writeMicroseconds(val); //using val as the signal to esc
    }

title: Arduino ESC controlled motor has issues

Answers: 1

body:
It would seem you are attempting to power the motor's coils from VIN of the Arduino. If you are powering the whole system from USB or from the barrel connector on the Arduino, then it's likely that the small voltage regulator on the Arduino cannot supply sufficient current to the motor.

You should connect the black and red wires of the ESC directly to a high-current power supply, and ensure the black (GND) wires of the ESC, power supply, and Arduino are tied together.


body:
The following image is my connection of l298 with Arduino.
[![enter image description here][1]][1]

This is the program.

    int ENA = 10; // MCU PWM Pin 10 to ENA on L298n Board
    int IN1 = 9;  // MCU Digital Pin 9 to IN1 on L298n Board
    int IN2 = 8;  // MCU Digital Pin 8 to IN2 on L298n Board

    int ENB = 5;  // MCU PWM Pin 5 to ENB on L298n Board
    int IN3 = 7;  // MCU Digital pin 7 to IN3 on L298n Board
    int IN4 = 6;  // MCU Digital pin 6 to IN4 on L298n Board

    void setup()
    {

    pinMode(ENA, OUTPUT); //Set all the L298n Pin to output
    pinMode(ENB, OUTPUT);
    pinMode(IN1, OUTPUT);
    pinMode(IN2, OUTPUT);
    pinMode(IN3, OUTPUT);
    pinMode(IN4, OUTPUT);
    }
    void DRIVEONE()
    {
    // Run the motors on both direction at fixed speed
    digitalWrite(IN1, HIGH); // Turn HIGH motor A
    digitalWrite(IN2, LOW);
    analogWrite(ENA, 200); // TO set the turning speed to 200 out of possible
    range 0 to 255

    digitalWrite(IN3, HIGH); // turn HIGH motor B
    digitalWrite(IN4, LOW);  // To set the turning speed to 200 out of possible
    range 0 to 255
    analogWrite(ENB, 200);
    delay(2000);  // Delay to 2 seconds
    void loop()
    {
    DRIVEONE();
    delay(100);
    }

The program seems to work fine but the motors run only when I touch all the 15 pins in L298 as shown in the second image.
I don't understand why the motors aren't running without touching those 15 pins.

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

I have connected the L298 to a 12V rechargeable battery and Arduino to a 9V battery.
Please help me understand what is wrong here.
Thank you.

  [1]: https://i.stack.imgur.com/XLkDg.png
  [2]: https://i.stack.imgur.com/aD4iP.jpg

title: L298 works only when touched

Answers: 1

body: Your schematic does not show a connection from the ground line of the 12V battery to the GND connection on the Arduino.  This is required.


body:
The question seems simple, but there's more to it:

I'm connecting 4 74HC595 shift-registers to an arduino pro micro.
28 of the 32 outputs will be used to control LED segments of numbers.
Each segment uses 14-20 LEDs and so I will be using a transistor for each segment.
Now here's my problem: With the maximum amount of LEDs activated (at time 08:08), the LEDs will draw nearly 10A. How can I use another transistor to make the shift-registors work with the arduino even though it shouldn't be drawing all current from the arduino, but from an external power source. I have found a suitable adapter from 230V to 5V 12A. The 12A is just to ensure that nothing goes wrong. The LEDs alone will draw 9.76A.

I know how to connect the arduino to the power source, but how do I run extra wires from the power source around the arduino to provide the LEDs their power?

title: How can I connect nearly 450 LEDs to an arduino without drawing too much current?

Answers: 2

body:
First you should consider changing your whole idea so that your LEDs don't draw nearly 10A.

I am assuming that for each segment you have 14-20 LEDs wired in parallel, each with its own current limiting resistor. That is very wasteful.

Instead you should be grouping the LEDs in chains of series LEDs which you then place in parallel.

Assuming you have normal red LEDs with a forward voltage of around 2V and a typical current draw for maximum brightness of 20mA, you can connect them up in chains of, say, 5 LEDs with one current limiting resistor, and power them from 12V not 5V.

3 chains of 5 LEDs (15 LEDs) would be 3x20mA = 60mA per segment. 4 chains of 5 LEDs (20 LEDs) would be 4x20mA = 80mA.

With 08:08 displaying that's 26 segments plus dots. Assuming each segment has 20 LEDs that's a total of 26x4 = 104 chains of 5 LEDs, totalling 520mA.

And then you should do away with the resistors as well, and use constant current LED sinks, such as the TLC59116, which can handle the higher input voltage.

If you don't want to do that, then more transistors will be needed:

<!-- 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/kuVWR.png)

<!-- End schematic -->

I have only showed 2 digits, 2 segments, 2 chains per segment, and 2 LEDs per chain to save space.

To drive it you need 1 GPIO per segment in one digit and 1 GPIO per digit. So for 4 digits at 7 segments that's 11 GPIO.

body:
<!-- 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/sFxXf.png)

<!-- End schematic -->

Change the 74HC595 to TPIC6B595. Each output can sink 150mA from up to a 50V source. Strings of 3 LEDs in parallel powered from a 12V source (with current limit resistor per string) are easily handled, no extra transistors are needed. The 12V positive goes to the + of each string (the top anode), the - (bottom cathode) goes to the TPIC6B595 output.  Here is a video of 8 TPIC6B595s running displays made two strings of 3 LEDs in parallel for the large digits, one string of 3 LEDs for the small digit.
https://www.youtube.com/watch?v=6HZ0Mr51jUY
Each string draws 25 or so mA.
The board that drives the display holds up to 12 shift register chips and is controlled by an Atmega328P set up like an Arduino.

The shift registers are easy to use as well. I use SPI.transfer to send data to them.
Create an array to map the shift register outputs to the segments:

    byte fontArray[] = {
        0b00111111, // 0 with the bits mapped to segments DP-g-f-e-d-c-b-a
        0b00000110, // 1   0 = segment off, 1 = segment on
        etc.
    }

The digit layout:

        a
    f       b
        g
    e       c
        d       and DP if used.

Then to update the display, say you have 4 shift registers all daisy chained:

    digitalWrite (ssPin, LOW);
    SPI.transfter(fontArray[digit0]);
    SPI.transfter(fontArray[digit1]);
    SPI.transfter(fontArray[digit2]);
    SPI.transfter(fontArray[digit3]);
    digitalWrite (ssPin, HIGH); // all outputs update on this rising edge

Dirt simple really. No need for a Mega.


body:
I'm playing around with this [udp-example][1]. Both this and the blink-example work perfectly. Now I would like to use the LED to indicate what the ESP is currently doing, as well as reading some data over Serial. My code looks like this:

    void setup(){
      Serial.begin(115200);
      Serial.setTimeout(500);
      while(Serial.available()==0){
      }
      String password = Serial.readStringUntil('.');
      Serial.println(password);
      WiFi.begin(ssid.c_str(), password.c_str());
      //pinMode(LED_BUILTIN, OUTPUT);
      while (WiFi.status() != WL_CONNECTED){
        //digitalWrite(LED_BUILTIN, LOW);
        delay(250);
        //digitalWrite(LED_BUILTIN, HIGH);
        delay (250);
      }
      Serial.println("connected");
      Udp.begin(localUdpPort);
    }

It works fine, but if I uncomment the led-lines the serial communication doesn't seem to work anymore. All the stuff that is printed on the Serial Monitor is now messed up (missing characters, ...). Is there a problem with my code or what else could be possible going wrong here?

EDIT: I recently tried the same code again, but used an additional power supply (3.3V, 500mA) for the chip. However, this didn't resolve the problem.

  [1]: https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/udp-examples.rst

title: EPS8266 ESP-01: LED manipulation seems to interfere with serial communication

Answers: 1

body:
I would bet that the built-in LED pin is also the TX pin for the serial interface.

Check here, **LED Pin** section: http://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations

> LED Pin
>
> GPIO1, which is also TX, is wired to the blue LED on many devices.
> Note that the LED is active low (connected to Vcc and sinks through
> the chip to ground) so setting a logical value of 0 will light it up.
> Since GPIO1 is also the TX pin, you won't be able to blink the LED and
> perform Serial communications at thew same time unless you switch
> TX/RX pins.

This would be confirmed if the LED blinks when serial communication is active.

If this is the case you would have to add your own LED on a different pin, or switch the RX/TX pins.


body:
I´m using a Wemos D1 mini board to control a RGB LED Strip and programmed a simple code with the Arduino IDE. The Wemos conects to my Internet just fine and with the IP adress I can change the RGB values of the Strip. Everything works but after a few minutes the board freezes and nothing works. After a reset it works again.

I also conected a simple circuit to the board just to controle a RGB-LED Strip with a few transistors nothing that should cause an issue and also if i conect nothing to the board the problem occurs.

I also tested a example from the Wemos Library but there is the same problem.
Here is my code I used (And sorry if the code isn´t that well programmed I´m a beginner ;)):
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>

    const char* ssid = "my SSID";
    const char* pass = "my password";

    void setup() {
      pinMode(D1, OUTPUT);
      pinMode(D2, OUTPUT);
      pinMode(D5, OUTPUT);

      WiFi.begin(ssid, pass);
      while (WiFi.status() != WL_CONNECTED) delay(500);

      Serial.begin(9600);
      //Serial.println(WiFi.localIP());
      server.begin();
    }
    void setColor(String rgb)
    {
      String rgb_val = rgb.substring(4, rgb.lastIndexOf('H'));
      String red_val = rgb_val.substring(1,rgb_val.indexOf(':'));
      String green_val = rgb_val.substring(rgb_val.indexOf(':') + 1,rgb_val.indexOf(':',rgb_val.indexOf(':') + 1));
      String blue_val = rgb_val.substring(rgb_val.lastIndexOf(':') + 1);
      int redval = red_val.toInt();
      int greenval = green_val.toInt();
      int blueval = blue_val.toInt();
      analogWrite(D5, redval);
      analogWrite(D2, greenval);
      analogWrite(D1, blueval);

      redval = redval >= 1023 ? 1023 : redval <= 0 ? 0 : redval;
      if (redval == 0)
        analogWrite(D5, 0);

      greenval = greenval >= 1023 ? 1023 : greenval <= 0 ? 0 : greenval;
      if (greenval == 0)
        analogWrite(D1, 0);

      blueval = blueval >= 1023 ? 1023 : blueval <= 0 ? 0 : blueval;
      if (blueval == 0)
        analogWrite(D2, 0);

      return;
    }

    void loop() {
      //delay(50) //just a test if there are not so many updates
      WiFiClient client = server.available();
      if (!client) return;

      while (!client.available()) delay(1);

      String request = client.readStringUntil('\r');
      client.flush();

      //Serial.print(request);
      setColor(request);
      client.stop();

      client.print("HTTP/1.1 200 OK\r\n");
      client.flush();
      return;
    }

Is there someone who know what I have done wrong?

title: Wemos D1 mini freezing after a few minutes

Answers: 1

body:
I doubt this is the problem, but this code looks wrong.

      int redval = red_val.toInt();
      analogWrite(D5, redval);
      redval = redval >= 1023 ? 1023 : redval <= 0 ? 0 : redval;
      if (redval == 0)
        analogWrite(D5, 0);

I think it should be more like this:

      int redval = red_val.toInt();
      if (redval > 1023)  // If its =1023 you do need to set it to 1023.
        redval= 1023;
      else if (redval < 0)
        redval = 0;
      analogWrite(D5, redval);

The inline if statement is too ugly and doesn't really add anything.

To be honest I would look at pulling this code into functions to make it easier to read and I suspect you will find the problem.

When these microprocessors stop after a while its usually memory, heat or electrical.  If you have checked the electrics and its stopping quite quickly its probably a memory leak.  So refactoring your code might help people spot the problem easier.

You might want to replace you call to `setColour()`  with a call to `Serial.println()` and see if that cure the problem.  If it doesn't then your problem is with the way you are calling client.


body:
There is a special, non-standard Arduino data type called "boolean".

How does it compare with the standard C++ data type "bool", and what are the reasons to use one or the other?

If they are identical in usage, why do both exist, and which one is preferred in Arduino code?

title: Using special Arduino "boolean" Data Type instead of standard "bool" data type

Answers: 3

body:
A Boolean variable type is one that has only 2 possible values, `true` or `false`.
Internally, it is created as an `int` (16-bit integer) or a `uint8_t` type (8-bit integer).

You can assign the "values" of `true` or `false` using the assignment operator:

    bool foo;
    foo = true;
    if (foo) {
      do_something();
    }

Internally, a `true` is a `1` and a `false` is a `0`, and the number values could be equally substituted.

Boolean types in Arduino and C++ mostly exist for readability, and not for any particular efficiency over `int` type.

body:
The official reference can be found [here][1]

It is best to always use true and false, and not use numbers.

Below some examples are given

Assign false resp true to a Boolean:

    bool a = true;
    bool b = false;

Check the Boolean value:

    if (b)
    {
       // Executed when b is true
    }
    else
    {
       // Executed when b is false
    }

    if (a && b)
    {
       // Executed when a is true and b is true
    }

    if (a || b)
    {
       // Executed when a is true or b is true
    }

If b is false, a will be false, otherwise a will stay as it was

    a &= b;

If b is true, a will be true, otherwise a will stay as it was

    a |= b;

// If a is true it will be false and vice versa.

    a = !a;

  [1]: https://www.arduino.cc/en/Reference/BooleanVariables

body:
While the other answers give generally useful information, the authors seem to have not read the question very carefully because they are talking about the **bool** type rather than the **boolean** type. In the Arduino API, `boolean` is a type alias for `bool`, as defined in Arduino.h:

https://github.com/arduino/Arduino/blob/1.8.3/hardware/arduino/avr/cores/arduino/Arduino.h#L125

    typedef bool boolean;

So you can use the `boolean` type just as you would `bool` and any standard C++ programming reference will instruct you in the use of `bool`. For this reason the other answers which mistakenly refer to `bool` are still somewhat useful.

Apparently at some point in the past the Arduino folks decided the name `boolean` would be more beginner friendly than `bool`, perhaps to be [consistent with the Processing language](https://processing.org/reference/boolean.html). However, as discussed here:

https://github.com/arduino/Arduino/issues/4673

the unnecessary use of a non-standard type is now considered by some to be a poor decision as its use makes code less portable and really doesn't provide any clear advantage over `bool`. A proposal is in the works to remove the use of `boolean` from all official Arduino code and document `bool` in the Arduino reference and some even wish to formally deprecate `boolean`. Therefore my advice is to use `bool` instead of `boolean` in your code.


body:
I have an application where I need 4 serial ports - 3 will be sending and receiving.  The packet size will be up to 255 bytes on these 3 "main" ports.  The 4th port will be receive only, and its packet size will be 6 bytes. There is no flow control. The data rate on all ports is 115,200 baud. The 3 main ports will send or receive data packets approximately once per second. Most data will be half-duplex, although occasionally it will be necessary to send and receive simultaneously from a port . The 4th port (the one that handles 6 bytes), will get packets at an approx 50 packets/second rate.

The TEENSY will have to calculate CRCs on all ports, and will have to do a small amount of data manipulation as well.

I was planning to use the hardware serial ports for the 3 main ports, and software serial for the port that has to deal with only 6 bytes.  It is important that the 3 main ports be able to not miss any incoming data.  The 4th port is less important and can "miss" a packet now and then with no ill effects.

Will a TEENSY 3.2 running 90MHz be able to keep up?

title: TEENSY 3.2 RS-232 throughput

Answers: 1

body:
Once per second? I don't see any problem, I will try to calculate:

3 ports: send + receive 255 bytes, let's say 270 bytes (with start/stop bits, probably way too much) per message:

3 * 2 (send + receive) * 270 = 1620 bytes
4th port: 50 * 6 bytes = 300 bytes

Total: 1920 bps

The serials can easily keep up with this, so that is not a problem.

90 MHz is 90 million instructions per second. As you can see, handling 1620 bytes is nothing ... it could do many more, a factor of multiple thousands more.

Unless of course you want to do heavily calculations for the received/sent data.


body:
I was wondering if I am legally allowed to sell an Arduino based product.  I also want to know if it is easy for people to retrieve code from an Arduino based circuit (reverse engineer it) or upload code from Arduino microcontrollers.

If I'm posting in the wrong please, please let me know. If there is better place to redirect my question, letting me know would be helpful too.

title: Selling a product using Arduino microcontroller or bootloader

Answers: 1

body:
The Arduino hardware is released under the creative commons license.

https://www.arduino.cc/en/Main/FAQ#toc3

"which allows for both personal and commercial derivative works, as long as they credit Arduino and release their designs under the same license"

It's possible for someone to retrieve the instructions from the MCU but they would be looking at assembly rather than the c code you wrote your sketch in.

This is a similar question and answer:
https://electronics.stackexchange.com/questions/67030/can-arduino-be-used-in-commercial-products


body:
i have 3 arduino uno r3 out of which 1 is not detected in any of my Pc's,

i was working and must have accidentally short circuited some how , the power led and 5v regulator on uno is burnt out but,i replaced both of them, but then again, windows was unable to detect it,but if i remove and plug the atmega328p in another uno it works fine.am able to upload sketch and do work,and put back the atmega in the non functioning uno.

the uploaded sketch runs fine but not detected, its kinda tiring removing the atmega and uploading a sketch through another uno and putting it back and the pins are so delicate each time i pull carefully somehow the pins getting bent.

 i also checked other components on the board but everything seems to be in good shape and not heating or anything, hope some has better solution...

title: Arduino uno R3 Not detected in windows 7 64

Answers: 0


body:
     #define LED 1//This pin goes to the LED
     #define SWITCH 7//From Switch$

    void setup() {
          pinMode(LED,OUTPUT);
          pinMode(SWITCH,INPUT);
    }
    int state=0;//Initializing values of all three
    int val;
    int lastval=LOW;

    void loop(){
          val=digitalRead(SWITCH);//Reads if switch is on or off
          if(val==HIGH&&lastval==LOW){//Basically activates if the button was just pressed
            state=1-state;//Changes state after button is pressed
            digitalWrite(LED,state);//Enforces changed state to LED on or off
            delay(50);//Just a simplistic debouncing
          }
          lastval=val;//Store last value
    }

title: PushButton as LED Switch (does not work)

Answers: 2

body:
I think the problem is in the lastval assignment and checking. During the bouncing, lastval will probably change several times. Within these changes the if statement is checked. If an even amount of changes are detected, the LED will change 4 times (being OFF again if it was OFF and On when On). Even if the user clicked possibly only one time. When an uneven amount of changes are detected it will be ok. So it's kind of luck when it works.

Use a proper debouncing technique (checking for some time if the switch is high or low and act on that directly).

Also do not use a boolean to flip that way, if you want it use a proper boolean:

    boolean state;

    ...

    state = !state;

However, I suggest using something like:

    digitalWrite(LED, state ? HIGH : LOW); // HIGH if state is true, else LOW

And change the if condition in a proper debouncing check (plenty of examples, e.g. [Arduino debouncing switch][1]).

  [1]: https://playground.arduino.cc/Learning/SoftwareDebounce

body:
Based on your response to my comment, it sounds like you have a floating input.  When the button is NOT pressed, the pin isn't connected to ground or 5V so it is floating and picking up whatever stray electrical signals happen to be bouncing around the room.

The easiest way to handle buttons on an Arduino is to wire them between the pin and ground.  Then in the code you use INPUT_PULLUP instead of INPUT for the pinMode call.  Once you've done that then the pin will reliably read HIGH when the button is NOT pushed and will read LOW when the button IS pushed.  Note that this is backwards of how newbies tend to think, but is really the more common way to handle a button.


body:
I wonder whats ARM build for Linux? Do we really need ARM build when we work with arduino? I need to integrate arduino and raspberry pi over wi-fi, I don't know whether I need ARM in this case. Also any quick learning tutorial for interfacing two of these hardware is appreciable

A newbie to Arduino. I hope fun learning with it

title: Do we need ARM build for arduino while interfacing R-pi and arduino

Answers: 1

body:
The ARM build of the IDE is for running the IDE on ARM systems. If you want to run the IDE on the pi then you need the arm build. However if you want to run the IDE on your PC then you need the IDE build that matches the architecture of your pc.

There are a million and one ways of communicating wirelessly between an Arduino and a pi.


body:
 I want to connect Ethernet board `(W5100 HR911105A)` to `Arduino Leonardo` with SPI and I also want to connect SD reader.
When I test these boards separately everything working. But when I connect them  on the same board the program fails at `Ethernet.begin();`

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

    #define SS_SD_CARD  4
    #define SS_ETHERNET 10

    const char CONFIG_FILE[] = "system.cfg";

    byte C_MAC[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress S_IP(192,168,0,19);
    IPAddress C_IP(192, 168, 0, 177);
    const uint16_t  S_PORT = 8090;

    EthernetClient client;

    void setup() {
      Serial.begin(9600);
        while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
        pinMode(SS_SD_CARD, OUTPUT);
        pinMode(SS_ETHERNET, OUTPUT);

        digitalWrite(SS_SD_CARD, HIGH);
        digitalWrite(SS_ETHERNET, HIGH);

        digitalWrite(SS_SD_CARD, LOW);
        SD.begin(SS_SD_CARD);
        digitalWrite(SS_SD_CARD, HIGH);

        Serial.println("Setup ethernet");
        digitalWrite(SS_ETHERNET, LOW);
        if (Ethernet.begin(C_MAC) == 0) {
          Serial.println("Failed to configure Ethernet using DHCP");
          Ethernet.begin(C_MAC, C_IP);
        }
        delay(100);
        Serial.println("connectin...");
        bool result = client.connect(S_IP, S_PORT);
        Serial.println("connected");
        digitalWrite(SS_ETHERNET, HIGH);
    }

    void loop() {
      Serial.println("loop...");
      delay(1000);
    }

I tried on Leonardo and Mega 2560.

title: Multiple SPI device

Answers: 3

body:
If you have a similar SD card reader like below (or same but with micro SD card), than I had exactly the same problem.

It works as single device on SPI, but not together with another SPI device.

You can either use a SD recorder proto board, or use a microcontroller that has multiple SPIs.

[![SD breakout][1]][1]

An example of the SD recorder I used and works with another SPI device on one SPI port.

Cons: bigger, more expensive
Pro: has a RTC and proto space.

[![SD Recorder][2]][2]

  [1]: https://i.stack.imgur.com/SBM4Q.jpg
  [2]: https://i.stack.imgur.com/a85YY.jpg

body:
Some card reaaders (as well as display boards with built-in sd socket) use 10-kOhm resistors in series to the CS, DIN and CLK lines, to perform a cheap 5V to 3.3V level translation. This is really not the best solution, especially in terms of speed (we verified that typically this limits the maximum SPI speed to about 1 MHz).

Other cards readers (such as this one http://modtronix.com/mod-sdcard-l5.html), just use 10 k-Ohm resistors as pull-up to 3.3V. Therefore you're connecting all the SD card lines to the Leonardo board, which is 5V level.
This will cause serious issues to the SD card or to the leonardo board. If your card reader falls in this second case, I suggest you to insert a resistor divider (1k + 1.5k) in series to each input lines of the SD card: DIN, CLK, CS.
In the following schematics I just show for the CLK line, of course you have to repeat this three times. A much better idea would be a level translator IC.

<!-- 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/2qdRG.png)

<!-- End schematic -->

body:
i suspect the reason is due to how the inputs/outputs are designed, the W5100 appears to be a 3v3 board with 5V compatible inputs, as does the link you posted to the SD reader, however depending on how these inputs/outputs are designed can mean they won't "play nice" with other boards on the same bus even though SPI is designed to do that.

depending on where the problem lies there are a few potential solutions, if (as i suspect) the problem is the output from the devices back to the arduino (ie you can write to them but not read from them) which you could confirm by connecting all lines in parallel, but only connecting one of the serial lines back to the arduino and check that it works, then swap the serial to the other device and check that. assuming that both devices work in this configuration you only need to fix the return signal. the simplest way of doing this would be to use two tri state buffers.

so the return signal is only connected to the arduino when that devices select line is active. and high impedance (disconnected) otherwise, programatically disconnecting one device from the bus.


body:
I am trying to flesh out my ideas for an electronics project and this question seems to be the main hangup. Is it possible, in the I2C protocol, to figure out the order in which the slaves are chained to the host? For example if I have 5 arduinos strung together by their serial and clock lines I want the master to be able to see that Arduino 1 is in position 1, Arduino 2 is in position 2... And so on. But if I switch Arduino 1 and 2 I want the master to know that Arduino 1 is in position 2 and Arduino 2 is in position 1.

I assume this isn't possible because all of the arduinos are connected to the same data and clock. So does anyone have any other protocols or algorithms in mind where I could do this. I was thinking I could have one Arduino talk to it's neighbors somehow and waterfall data down the line until it gets to it's destination. But I'm curious to see what y'all come up with.

title: Using I2C to keep track of position of slaves

Answers: 1

body:
This is indeed not possible.  I2C was meant for short on-the-same-board communications and though it's sometimes also extended to near-board communications, it still has no facility for position sensing.  Each slave  simply listens for an address and then responds to commands sent for that address.

Slaves can "stretch the clock" to slow down things, but cannot otherwise make themselves known so long as they are not mastering the bus.  In any case, even if bus mastering is assigned round-robin, only presence can be determined, not the position in any chain.


body:
Connecting my ESP8266 device to an IOT cloud service. When I push a button in the dashboard, it sends either 1 or 0. Then my ESP should turn a pin HIGH if signal received was 1 or Low if it was 0. Here is the code of the method in question:

    void callback(char* topic, byte* payload, unsigned int length) {
      Serial.print("Message received[");
      Serial.print(topic);
      Serial.print("] ");
      for (int i=0;i<length;i++) {
         Serial.print((char)payload[i]);
      }
      Serial.println();

      if ( (byte)payload[0] == 0) {
        digitalWrite(13, LOW);
        Serial.println("Setting PIN on to LOW");
      } else {
         digitalWrite(13, HIGH);
         Serial.println("Setting PIN off to HIGH");
      }

    }

When sending a 1 signal, serial monitor displays:

> Message arrived [/v1.6/devices/esp8266/relay/lv] 1
> Setting PIN off to HIGH

When sending a 0 signal, serial monitor displays:

> Message arrived [/v1.6/devices/esp8266/relay/lv] 0
> Setting PIN off to HIGH

So it seems like it always goes into the `else` clause. Similarly, if casting the value as char:

    if ( (char *)payload[0] == 0)

Then it will always go into the first condition `payload[0] == 0` regardless of the value received.

title: How to compare payload value?

Answers: 1

body:
You receive the character `0` or `1` but compare it to the value `0` or `1`. The two things are very different.

You are sending ASCII but comparing it to decimal.

Instead you need to compare like for like.  Either:

    if (payload[0] == '0') {

Or:

    if (payload[0] == 48) {

You can find an easy reference for the full ASCII table [here](http://asciitable.com).


body:
I have a new Mac OS Sierra installed. I just installed the Arduino IDE and the serial drivers for Mac OS X to make the serial USB port available for esp8266 device

When I try to flash the device through the IDE I have these errors:

    Arduino:1.8.3 (Mac OS X), Scheda:"NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

    Archiving built core (caching) in: /var/folders/vz/qxry2ffs3rnd2xtd557pgcf00000gp/T/arduino_cache_169716/core/core_esp8266_esp8266_nodemcuv2_CpuFrequency_80,UploadSpeed_115200,FlashSize_4M3M_244c37a477ed4ef8a63952f7a6e6a50b.a
    Lo sketch usa 222149 byte (21%) dello spazio disponibile per i programmi. Il massimo è 1044464 byte.
    Le variabili globali usano 31524 byte (38%) di memoria dinamica, lasciando altri 50396 byte liberi per le variabili locali. Il massimo è 81920 byte.
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: unslip sequence wrong
    warning: espcomm_send_command: can't receive command response header
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed

What can I do?

title: Problem uploading Arduino sketch on ESP8266-12e

Answers: 2

body: I installed another version of the driver from silabs' website and now it's working.

body:
**3.x version of ESP8266 libraries**

If you're using the most updated version of the ESP8266 "NodeMCU 1.0 (ESP-12E Module)" board then all you need to do is update your Silabs library.

**2.x version of ESP8266 libraries**

If you're using a 2.x version of the ESP8266 "NodeMCU 1.0 (ESP-12E Module)" board, it is more involved. It comes with a packaged version of pyserial which resolves the wrong versions of the IOKit and CoreFoundation libraries. You will need to edit the pyserial script for your board version manually following the instructions here: https://forum.arduino.cc/t/pyserial-and-esptools-directory-error/671804/5.

An alternative is use the Windows version of the flashing tool provided by Espressif by running it through a Windows emulator or VM. You can find instructions for that here: https://blog.squix.org/2015/05/esp8266-flashing-nodemcu-v10-on-mac-os.html.


body:
I use ESP8266-12 with an Arduino Uno as a USB-serial adapter.

When I upload any sketch to the ESP8266 it works fine until I reset the ESP8266.

    uint32_t realSize = ESP.getFlashChipRealSize();
    uint32_t ideSize = ESP.getFlashChipSize();
    FlashMode_t ideMode = ESP.getFlashChipMode();

    Serial.printf("Flash real id:   X\n", ESP.getFlashChipId());
    Serial.printf("Flash real size: %u\n\n", realSize);

    Serial.printf("Flash ide  size: %u\n", ideSize);
    Serial.printf("Flash ide speed: %u\n", ESP.getFlashChipSpeed());
    Serial.printf("Flash ide mode:  %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN"));

    if(ideSize != realSize) {
        Serial.println("Flash Chip configuration wrong!\n");
    } else {
        Serial.println("Flash Chip configuration ok.\n");
    }

    delay(5000);

If I ground reset button, garbage values are being shown.

Connections details:

EN  - 3.3V of Uno

VCC - 3.3V of Uno

RST - GND Of Uno(If needed)

TX - TX of Uno

RX - RX of Uno

GPO15 - GND of Uno

GPO01 - GND of Uno

GND - GND of Uno

title: ESP8266-12 is showing garbage when RST is given

Answers: 1

body:
Espressif says it can not be disabled.

Ref.: https://github.com/esp8266/Arduino/issues/3047


body:
Try SD SPI code and ADXL345 SPI code separately and both are fine. When merge the codes, ADXL345 reading okay (not plug in MicroSD Adapter). Pin should bo okay.

Every time MicroSD is plugged (the same pin working with above code), ADXL345 reading suddenly becomes 0g, 0g, 0g. Pull it out then reading is good.

See https://forum.arduino.cc/index.php?topic=360718.0 and not sure if this is due to a hardware defect on MicroSD Adapter.

Already read many post like https://forum.sparkfun.com/viewtopic.php?f=14&t=38072 and the code produce 0g result, too.

Is it purely a hardware problem? Anyone suggest another one?
Is there any way to fix in software?

More details: I am using Nodemcu v1. and arduino library. The connected pins for SD and ADXL345 both at HSPI pins. I understand Nodemcu has another SPI (or even for SD card (SD0, SD1, ...etc), but I did not see any example by using those two and integrate with ADXL345 on HSPI.

title: ADXL345 becomes 0g when plugin MicroSD Adapter using SPI

Answers: 1

body:
You may have the same problem as my answer in [Multiple SPI device answer][1] ... not all devices supports another SPI device on the same port

That is (one of the) reasons I use STM32 instead of Arduino, since the Arduinos have 'only' one SPI port.

  [1]: https://arduino.stackexchange.com/questions/43707/multiple-spi-device/43709#43709


body:
Maybe is to easy to answer but i don't know it. I know IEEE-754 is for float values and double but i don't know if is exclusive for those type.

I use this to convert float and works fine i have another code in javascript to revert it.
But when used it with integer values it just gives some values and the revert doesn't work as supposed to.

So, this definitely doesn't work for integer values?, i can parse it to float and pass it to IEE754 but i just want to know.

this is the code i use in arduino.

    void IEEE754( float val, int pos)
    {
      byte* array = (byte*) &val;
      for (int i = 0 ; i < 4 ; i++) {
          payload[pos + i] = array[i];
      }
    }

also, does anyone has the revert code for arduino?..

title: IEEE 754 for integer

Answers: 1

body:
IEEE 754 is the specification for floating point values. Integers aren't floating point values so this function of yours can have nothing to do with integers.

On an Arduino (8-bit):

* A float value is 4 bytes in IEEE-754 format.
* A long value is 4 bytes in little-endian format.
* An int value is 2 bytes in little-endian format.
* A byte is a byte.

To convert 4 bytes into a long you can use:

    long val = (payload[3] << 24) | (payload[2] << 16) | (payload[1] << 8) | payload[0];

An int value is just the lower two bytes of the same kind of conversion:

    int val = (payload[1] << 8) | payload[0];

You can use the same method (albeit backwards) to get the bytes to put in your payload:

    long val = 12345678L
    payload[0] = val & 0xFF;
    payload[1] = (val >> 8) & 0xFF;
    payload[2] = (val >> 16) & 0xFF;
    payload[3] = (val >> 24) & 0xFF;

You can also use the same technique as your existing function with different datatypes, since all you care about is the byte content not the format or meaning of the bits within it:

    void int2payload( int val, int pos) {
      byte* array = (byte*) &val;
      for (int i = 0 ; i < 2 ; i++) {
          payload[pos + i] = array[i];
      }
    }

    void long2payload( long val, int pos) {
      byte* array = (byte*) &val;
      for (int i = 0 ; i < 4 ; i++) {
          payload[pos + i] = array[i];
      }
    }


body:
I want to write a simple program that waits for an X amount of time (hours) then activates my components (LED and release mechanism) when time has elapsed. I have it so that once I press a button interrupt (pin2) it will put the Arduino in power-down sleep mode when I am not using the device.

What I want it to do next is when another button interrupt (pin3) is pushed, it will wake it up but **instead of resuming where it left off in the loop, I want it to reset the program to the start of the loop.** I am having trouble getting it to reset after it has woken. Is the code actually putting the Arduino in sleep mode? I'm not sure because after the if statement I make the variable false.

Here is my simple code so far:

    #include <avr/interrupt.h>
    #include <avr/sleep.h>
    //Pin set up
    int ledPin =12;
    int wakePin = 3;
    int sleepPin =2;
    volatile boolean flag;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(sleepPin, INPUT_PULLUP);
      pinMode(wakePin, INPUT_PULLUP );
      attachInterrupt(0, sleepy, LOW);
      attachInterrupt(1,EMPTY,LOW);
    }

    void EMPTY(){
      detachInterrupt(1);
    }

    void sleepy(){
      flag = true;
    }

    void sleepNow() {
      digitalWrite(ledPin, LOW);
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      sleep_enable();
      attachInterrupt(1,EMPTY,LOW);
      sleep_mode();
    }

    void loop() {
      digitalWrite(ledPin, HIGH);
      delay(1000);
      digitalWrite (ledPin, LOW);
      delay(1000);
      digitalWrite(ledPin, HIGH);
      delay(1000);
      if (flag) {
        sleepNow();
      }
      flag = false;
    }

title: Arduino interrupt sleep mode/reset problem

Answers: 0


body:
I have a 7 segment clock with 4 digits, and 2 push buttons to control time (hours seconds days month etc). What is the best way to manage the settings of each sub menu when the user wants to change the time? Is coding it myself or using a menu library such as this one better for the task? https://playground.arduino.cc/Code/Menu

Thanks

title: Menu libaries for a clock

Answers: 1

body:
I would make it myself.

One way to do it:

- Create an enum with all states, like Normal, ChangeMonth, ChangeDay, ChangeHour, ChangeMinute };
- Use one button to increase the item you are changing with 1
- Use the other button go to go the next enum

You can make it fancier by using longer/shorter presses (e.g. to increase faster)

Don't forget to debounce button inputs.


body:
So i'm building my own quadcopter at this moment and I have designed a flight controller board for it using two atmega328p's. I've programmed it so that the first atmega receives al the data from sensors and the radio transmitter and then calculates the values for the motors, LEDs and servos. To have it run smooth, the motor controller (ESC) gets updated 250 times per second (250Hz). So the first atmega sends all the data via i2c to the second atmega 250 times per second. When the second atmega receives the data it causes an interrupt via Wire.onReceive(event);. This then sets a flag so the main loop starts when there is new data. Here is a really simplified version of my code:

atmega 1:

    #include <Wire.h>
    #include <CapacitiveSensor.h>

    int servo1;
    int val, i;

    int escLR;
    int escRR;
    int escLF;
    int escRF;

    byte send_array[11];
    byte error;

    unsigned long int loop_timer;

    void setup() {

      Wire.begin();                                                    //joins the i2c bus
      TWBR = 12;                                                      //set i2c clock to 400kHz

      GyroAccelInit();

      delay(3000);

      loop_timer = micros();                                     //set the timer for the loop
    }

    /*************************************************************************************************************************/

    void loop() {

      //ReadGyro();                                                              //commented out because not relevant
      //ReadAccel();
      //PPM_get();

      if (error == 1) {
        send_array[10] &= B11111000;
        send_array[10] |= B00000001;                                   //set led bits to red
      }

      SendData();                                                                //send the data

      if (micros() - loop_timer > 4050) {                               //set error if the loop takes too long
        error = 1;
      }

      while (micros() - loop_timer < 4000) {}                          //wait until 4 milliseconds have passed
      loop_timer = micros();
    }

    /*************************************************************************************************************************/

    void SendData() {                                                  //sends the data to second atmega

      send_array[1] = escLR & 0xFF;                                    //isolates the low bits
      send_array[0] = escLR >> 8;                                      //shifts high bits to the right

      send_array[3] = escRR & 0xFF;                                    //isolates the low bits
      send_array[2] = escRR >> 8;                                      //shifts high bits to the right

      send_array[5] = escLF & 0xFF;                                    //isolates the low bits
      send_array[4] = escLF >> 8;                                      //shifts high bits to the right

      send_array[7] = escRF & 0xFF;                                    //isolates the low bits
      send_array[6] = escRF >> 8;                                      //shifts high bits to the right

      send_array[9] = servo1 & 0xFF;                                   //isolates the low bits
      send_array[8] = servo1 >> 8;                                     //shifts high bits to the right

      Wire.beginTransmission(42);                                      //begins the transmission to device 42

      for (int n = 0; n < 11; n++) {
        Wire.write(send_array[n]);
      }

      Wire.endTransmission();                                          //sends the buffer to the slave
    }

atmega 2:

    include <ServoTimer2.h>
    include <Wire.h>

    int count;
    int servo1_val;

    int escLR_val;
    int escRR_val;
    int escLF_val;
    int escRF_val;

    byte state;
    byte new_data;

    byte buff[11];

    unsigned long int loop_count;

    ServoTimer2 escLR, escRR, escLF, escRF, servo1, servo2;           //initialize ESCs
    WS2812 LED(1);                                                    //one LED
    cRGB value;

    /*************************************************************************************************************************/

    void setup() {

      Wire.begin(42);                                                 //joins the i2c bus as a slave with an adress of 42
      Wire.onReceive(event);                                          //sets up the handler that gets activated when there is data coming in

      Serial.begin(57600);

      escLR.attach(8);                                                //set ESC output to pin 8
      escRR.attach(7);                                                //set ESC output to pin 7
      escLF.attach(6);                                                //set ESC output to pin 6
      escRF.attach(5);                                                //set ESC output to pin 5
    }

    /*************************************************************************************************************************/

    void loop() {

      if (new_data == 1) {                                            //start loop if there is new data

        escLR_val = buff[0] << 8 | buff[1];                           //get the two bytes to make a 16 bit integer
        escRR_val = buff[2] << 8 | buff[3];                           //get the two bytes to make a 16 bit integer
        escLF_val = buff[4] << 8 | buff[5];                           //get the two bytes to make a 16 bit integer
        escRF_val = buff[6] << 8 | buff[7];                           //get the two bytes to make a 16 bit integer
        servo1_val = buff[8] << 8 | buff[9];                          //get the two bytes to make a 16 bit integer
        state = buff[10];                                             //get the state byte

        escLR.write(escLR_val);                                       //write to all the ESCs
        escRR.write(escRR_val);
        escLF.write(escLF_val);
        escRF.write(escRF_val);

        new_data = 0;
        loop_count++;
      }
    }

    /*************************************************************************************************************************/

    void event(int howMany) {                                         //handler that gets activated when there is data coming in
      byte count = 0;

      while (Wire.available()) {                                      //wait until all bytes are in

        buff[count] = Wire.read();
        count++;
      }

      new_data = 1;
    }

Now here's the problem: because of the interrupt that is activated when there is data coming in, the signal for the servos and motor controller is really unstable and the servos jitter all the time. I know this because when I disable the interrupt, the servos and motors behave perfectly normal. Other forums have suggested to use the servoTimer2 library (which I do) but that didn't change a thing. Also the servos only turn 90 degrees instead of 180 but that could be because I'm running them on 250Hz instead of 50Hz. So if anyone knows how to write to the servos at 50Hz and the motor controllers at 250Hz please let me know.

So does anyone have suggestions? I'm happy with all suggestions so if I have to I will rearrange my entire code to solve this problem. I was thinking about using the using the mills() function, using requestFrom() or disabling interrupt for a while and even using hardware PWM. So maybe that brings you an idea. I'm really stuck here and I have to have it finished in less than a week so any help would be more than welcome!

by the way, english isn't my first language and am really bad at explaining things so if things are not clear I'll be happy to explain!

title: Servo jitter with two atmegas

Answers: 1

body:
The core problem is that servo control on an Arduino is done using timer interrupts and not hardware PWM. And of course your I2C reception is also using interrupts.

Since the Arduino only has one level of interrupts you can't interrupt an interrupt, so when you are receiving I2C data the interrupts for the servos cannot trigger and so they get confused with bad timing signals.

You can tackle it in one of three ways (that spring to mind):

1. Don't use interrupts for receiving your data
2. Use hardware PWM instead of timer interrupts for the servos
3. Use a more advanced microcontroller with multiple interrupt priority levels where the timer interrupt can interrupt the I2C interrupt.


body:
I'd like to make a musical harp that utilizes break beam sensors.

I'd really appreciate guidance on these two questions:

 - How should I go about listening for multiple beam breaks at the same time? I'd like the box to be able to play cords, so I'd need to listen for the break beams while simultaneously taking the action do to other previous break beams. Are there any links to similar projects for guidance on handling multiple inputs (possibly multiple interrupts) at the same time, as well is multiple outputs?

 - Where is a good place to start to understand how to output non-buzzer sound with an Arduino? I bought a Adafruit Wave Shield to do the trick, but I'd appreciate advice on using this, or possibly taking an easier route.

My major concern is the first question however, and it makes me think I may need a Pi possibly? But I've never worked with those, so I'd like to avoid it if possible.

Thanks!  :)

title: How do I handle multiple interrupts and outputs simultaneously?

Answers: 3

body:
> How should I go about listening for multiple beam breaks at the same time?

use interrupts. it can be done with external interrupts, pin change interrupts, comparator interrupts, analog interrupts, or even timer interrupts, depending on how you intend to approach it.

body:
Most of the examples for that shield seem to suffer from what could be called `delay`itis. If you first convert the piano example to a more state-based approach then the loop you want becomes much simpler:

    #define NUM_BEAMS 12
    // a single octave

    char filename[NUM_BEAMS+5]; //init the last 5 chars to ".wav\0"
    int previousInputs; //flag variable where each bit is a single beam

    void loop(){
        int inputs = readBeams();

        if(inputs != previousInputs){
          previousInputs = inputs;
          if (wave.isplaying) {// already playing something, so stop it!
            wave.stop(); // stop it
          }
          if(inputs == 0){
            return;
          }
          for(int i = 0; i< NUM_BEAMS; i++){
              filename[i] = inputs &(1<<i)?'1':'0';
          }

          if (!f.open(root, filename)) {
            putstring("Couldn't open file "); Serial.print(name); return;
          }
          if (!wave.create(f)) {
            putstring_nl("Not a valid WAV"); return;
          }
          // ok time to play!
          wave.play();
        }

    }

The SD card in the shield will need 4095 files, each containing the chord that must be played.

No need for interrupts, no messy interrupt based IO. Just a simple `loop()` where you read the input and if different from last time start playing a new file.

If you have a shield that can actually do sound mixing then, instead of needing a file for *every possible chord*, you can start playing the note when the corresponding bit in `started = inputs & ~previousInputs;` is 1 and stop playing the note when the corresponding bit in `ended = ~inputs & previousInputs;` is 1.

body:
I quite like rachet freaks's idea, however whilst making an example for you his answer hadn't been posted. SO i'll chip in anyway!

In general it is possible to control and measure more than one input and output at the same time by the use of millis(). millis() is an arduino function that returns the number of milliseconds since the arduino fired up.

This probably doesnt sound overly useful to you straight away. But millis can be used in place of delay() if used correctly. Essentially you create a long variable to hold the beginning of an event and check the time since that event started with an if statement. If the difference in the current time and the start time is equal to the time you want the event to occur. Stop the event.

I appreciate my explanation might not be overly clear. So I wrote an example sketch. The sketch has two button inputs. And two button outputs. If one of the buttons is pressed one led will blink for 10 seconds, pressing the button mid blink will extend the time the led blinks by another 10 seconds. Whilst this is happening if you press the second button the other led will turn on, but only when the button is pressed. Using delay() to achieve this would not work nearly as well.

    //Setup led and button pins
    int ledPin1 = 3;
    int ledPin2 = 4;
    int butPin1 = 5;
    int butPin2 = 6;

    //Setup timers
    unsigned long currentMillis = 0;
    unsigned long blinkStartMillis = 0;
    unsigned long ledOnMillis1 = 0;
    unsigned long ledOffMillis1 =0;

    //Setup variables to store input and output states.
    int ledState1 = 0, ledState2 = 0; //State 1 for on, 0 for off;
    int butState1 = 0, butState2 = 0; //State 1 for trigger, 0 for off;

    //Setup trigger for event
    int blinkTrigger = 0;

    void setup() {
      pinMode(ledPin1, OUTPUT);
      pinMode(ledPin2, OUTPUT);
      pinMode(butPin1, INPUT);
      pinMode(butPin2, INPUT);

      delay(500);
    }

    void loop() {
        //Sets current millis for this loop
        currentMillis = millis();

        //Reads Button States
        butState1 = digitalRead(butPin1);
        butState2 = digitalRead(butPin2);

        //Setup to start blink if button 1 input is high
        if(butState1) {
          blinkTrigger = 1;
          blinkStartMillis = currentMillis;
        }

        //Handles Blinking
        if(blinkTrigger) {

          //If led1 off, and has been off for 500 milliseconds. led 1 on
          if(ledState1 == 0 && currentMillis - LedOffMillis >= 500) {
            digitalWrite(ledPin1, HIGH);
            ledState1 = 1;
            ledOnMillis = currentMillis;
          }

          //If led1 on, and has been on for 500 milliseconds. led 1 off
          if(ledState1 == 1 && currentMillis - LedOnMillis >= 500) {
            digitalWrite(ledPin1, LOW);
            ledState1 = 0;
            ledOffMillis = currentMillis;
          }

          //If led1 has been blinking for more than 10 seconds
          //Stop blinking
          if(currentMillis - blinkStartMillis > 10000) {
            digitalWrite(ledPin1, LOW);
            ledState1 = 0;
            blinkTrigger = 0;
          }
        }

        //While Button 2 pressed led 2 on
        if(butState2) digitalWrite(ledPin2, HIGH);
        if(!butState2) digitalWrite(ledPin2, LOW);

    }

Note: The code style is a bit off because i rushed it, I would also usually use structs to hold the timers and event triggers.

Now for the Wave module rachet is bang on the money, you would need a file for every single note and every single chord.

I hope I helped, if not for your project maybe you may have learnt how to handle more than one event using event timings.


body:
I would like to measure the amount of power used by a 3w bulb. I am using a 9v battery to power the bulb and an acs712 current sensor to get current usage. However, i get no change in values after i connect the load and it light up.
Is my current sensor faulty or? I'm confused.[![The image describes how i have set up my connection][1]][1]

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

title: No change in acs 712 readings after connection to load

Answers: 1

body:
For such light and low-voltage loads you wouldn't normally use a mains rated high current amplifier like this.

Instead you would just use a simple shunt resistor in the low-side of the circuit:

<!-- 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/EbNkH.png)

<!-- End schematic -->

The voltage dropped across the resistor (and hence the voltage you will read on A0) is proportional to the resistance of the resistor and the current flowing round the circuit.

You want the resistor to be small enough that it doesn't overly affect the operation of the circuit, yet large enough that it drops a voltage you are able to sense at enough resolution.

For example the 1Ω resistor above, with 333mA round the circuit (3W at 9V) would drop (V=IR) `0.3 * 1 = 0.3V`.

While that's not a very high voltage it's small enough to not really affect the circuit, and you can increase the sensitivity of the Arduino by using the 1.1V internal reference instead of relying on the default 5V external Vcc voltage:

    analogReference(INTERNAL);

Or on the Mega2560:

    analogReference(INTERNAL1V1);


body:
I am new to Arduino and have tried all kinds of code for attempting to achieve this. None with any luck, however. I feel that it should be a relatively easy task and therefore, figured that someone out there with more proficiency with an Arduino than me, would be able to help.

Essentially, I have two commands sent to a device via the Leonardo serial port. One is the single character "R", and the other is the single character "O". The device then sends back 8 binary bytes (non ASCII) in floating point format per command. So if I send O, it will return 8 binary bytes, and then the same goes for if I sent R.

The commands O and R need to be simultaneously sent via the serial every 250ms and wait for their respective responses before sending the next command.

I also need to store the device's response to O and the device's response to R in respective variables that will have a new value every 250ms. I am not familiar with single point format and therefore am unaware of what variable system to use.

Here is my best, yet unsuccessful attempt:

    unsigned long previousMillis = 0;
    const long interval = 250;
    int responseO;
    int responseR;

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

     while(!Serial);
    }

    void loop()
    {
     unsigned long currentMillis = millis();

     if(currentMillis - previousMillis >= interval) { //timer for every 250ms
      previousMillis = currentMillis;
      Serial.println("R");               //Figured that "println" with a string for the character R should be ok

      if(Serial.available() > 0) {          //Don't know if I am correct here, I was hoping that the serial would only be read if the device responded to the command R
       responseR = Serial.read();       //Read serial for device's response to command R and save it in a variable
      }

      Serial.println("O");               //Do the same thing for the command O

      if(Serial.available() >0) {
        responseO = Serial.read();
        }
     }
    }

However, whenever I test this, it appears that the program is unable to differentiate between which responses are due to one command, and treats one response as if both commands requested it when only one did. Also is a floating point format variable just a float?

Thank you so so much, I really need some help this has been burning away at me for days........

Cheers, Harry

title: Send serial command and wait for reply

Answers: 4

body:
After printing a char in the Serial, you have to wait until some response is received. For that, you use a `while`

    void loop()
    {
     unsigned long currentMillis = millis();

     if(currentMillis - previousMillis >= interval) { //timer for every 250ms
      previousMillis = currentMillis;

      Serial.println("R");               //Figured that "println" with a string for the character R should be ok
      while(!Serial.available());
      responseR = Serial.read();       //Read serial for device's response to command R and save it in a variable

      Serial.println("O");               //Do the same thing for the command O
      while(!Serial.available());
      responseO = Serial.read();
     }
    }

Now, you have to tell us which *floating point format* are you using.

body:
each call to Serial.read will read a single byte. So to read multiple bytes it needs to be called multiple times.

    int bytesToReadFromR;
    int bytesToReadFromO;

    void loop()
    {
        unsigned long currentMillis = millis();

        if(currentMillis - previousMillis >= interval) { //timer for every 250ms
            previousMillis = currentMillis;

            Serial.println("R");
            bytesToReadFromR = 8;              //mark that there is data to read from Serial for R

            Serial.println("O");
            bytesToReadFromO = 8;              //Do the same thing for the command O
        }

        if(bytesToReadFromR){
            while(bytesToReadFromR && Serial.available()){
               responseR[--bytesToReadFromR] = Serial.read();       //Read serial for device's response to command R and save it in a char array
            }
            if(bytesToReadFromR){
                 //finished transfer, trigger what you need
            }
        }
        if(bytesToReadFromO){
            while(bytesToReadFromO && Serial.available()){
               responseO[--bytesToReadFromR] = Serial.read();       //Read serial for device's response to command O and save it in a char array
            }
            if(bytesToReadFromO){
                 //finished transfer, trigger what you need
            }
        }
    }

body:
The code shown in two previous answers is problematic.

For example, in Look Alterno's code, `Serial.println("R")` will trigger an `R` response.  The `while(!Serial.available());` construct will wait for the first byte of the response.  Then `responseR = Serial.read();` will read one byte.  Next, `Serial.println("O")` will attempt to trigger an `O` response.  The second `while(!Serial.available());` will wait for a byte to be available, which should happen when the second byte of the `R` response arrives.  Then `responseO = Serial.read()` will read that byte.

In ratchet freak's code, each quarter second `bytesToReadFromR` and `bytesToReadFromO` are set to 8.  In the next several passes through `loop()`, `if(bytesToReadFromR)` and `if(bytesToReadFromO)` are satisfied, so `while(bytesToReadFromR && Serial.available())` and `while(bytesToReadFromO && Serial.available())` will be controlled by whether a character is available.  At 9600 bps, about one character per millisecond will become available, so most of the time we are just spinning through `loop()` dozens of times per millisecond, waiting for characters.  The `if` statement for `bytesToReadFromR` has a slightly higher chance of catching fresh characters, but which buffer (`responseR` or `responseO`) gets any given character still is left to chance.

Instead of the code previously shown, consider something like the following:

    enum { dataBytes = 8, interval=250 };

    float getResult (char trigger) {
      union { byte d[dataBytes], float f[2] } u;
      byte rin=0;
      Serial.print(trigger);
      while (rin < dataBytes) {
        if(Serial.available())
          u.d[rin++] = Serial.read();
      }
      return u.f[0];  // Assumes bytes in forward order
    }

    unsigned long prevMillis = millis();
    float RValue, OValue;

    void loop() {
      if(millis() - prevMillis >= interval) {
        prevMillis = millis();
        RValue = getResult ('R');
        OValue = getResult ('O');
        // put code here to consume the results
        // ...
      }
    }

Note, this code will get stuck if too-few characters arrive from the R&O device, or if some characters get lost for any reason.  One could add a timeout to the loop in `getResult()`; it could check for `millis() - prevMillis >= interval` and if so, break the loop and return a NAN.

Note, this code assumes the byte-order of floats from the R&O device matches that of the Arduino.  That will be so if both are big-endian, or if both are little-endian.  If they differ, store bytes in reverse order into the `u.d` array, and return `u.f[1]` instead of `u.f[0]`.

Note, [`union`](https://www.tutorialspoint.com/cprogramming/c_unions.htm) is a C / C++ technique for accessing data multiple ways.  The declaration `union { byte d[dataBytes], float f[2] } u` says that `u` is a structure where the array `d` starts at the same address as the array `f`.  Thus, the float `u.f[0]` corresponds to the first four bytes of `u.d`, and `u.f[1]` to the next four.

Note, if the R&O device requires an end-of-line character, change  `Serial.print(trigger)` to `Serial.println(trigger)`.

body:
As others have mentioned, you have to read the serial input byte by byte. 4 bytes means you have to read it four times and store the values in an array. Then do your calculations with the array.

After a little googling I found this: https://stackoverflow.com/questions/3991478/building-a-32bit-float-out-of-its-4-composite-bytes-c

Which is basically what you want to do. Try this code:

    unsigned long previousMillis = 0;
    const long interval = 250;

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

    void loop() {

      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) //timer for every 250ms
      {

        previousMillis = currentMillis;

        Serial.println("R");               //maybe substitute with
        if(Serial.available() >0)          //Serial.println('R'); or
        {                                  //Serial.write("R");   or
          byte buff1[4];                   //Serial.write('R');
          byte buff2[4];
          float firstNumber;
          float secondNumber;

          for(int i=3; i>=0; i--){
            buff1[i] = Serial.read();
          }
          for(int i=3; i>=0; i--){
            buff2[i] = Serial.read();
          }

          memcpy(&firstNumber, &buff1, sizeof(firstNumber));
          memcpy(&secondNumber, &buff2, sizeof(secondNumber));

          Serial.print("first number is: ");
          Serial.println(firstNumber);
          Serial.print("second number is: ");
          Serial.println(secondNumber);

        }

        //do the same thing with your "O" command, or write a function

      }

    }

There are two things to consider though:

-  As you can see I am looping the `buff1` and `buff2` arrays backwards. This is because the endianness of the float depends on how your device sends them. If you were receiving gibberish change the loops to count from 0 to 4.

- You said your device expects a single 'R' **character** but what you are doing is sending a "R" **string** and then a new line character after that(because you are using **println()**). It's possible that you will have to substitute that with one of the options I mentioned in the code comment.


body:
I have two different Vernier science probes connected to a Vernier shield that connects to an Arduino Uno. I have the Uno connected to an ESP8266 via the Tx.

Here is my Uno code:

    String sensor1 ="Conductivity Probe ";
    float interceptSensor1 = 0.0;
    float slopeSensor1 = 960;
    String sensor2 ="pH Probe ";
    float interceptSensor2 = 13.720;
    float slopeSensor2 = -3.838;
    int timeBetweenReadings = 2000; // in ms

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

    void loop() {
      float analogSensor1 = analogRead(A0);
      float voltageSensor1 = analogSensor1 / 1023 * 5.0;
      // convert from count to raw voltage
      float sensor1Reading= interceptSensor1 + voltageSensor1 * slopeSensor1;
      //converts voltage to sensor reading
      String sensor1Output = sensor1 + sensor1Reading;
      Serial.println(sensor1Output);
      delay(timeBetweenReadings);
      // delay in between reads for stability
      float analogSensor2 = analogRead(A1);
      float voltageSensor2 = analogSensor2 / 1023 * 5.0;
      // convert from count to raw voltage
      float sensor2Reading= interceptSensor2 + voltageSensor2 * slopeSensor2; //converts voltage to sensor reading
      String sensor2Output = sensor2 + sensor2Reading;
      Serial.println(sensor2Output);
      delay(timeBetweenReadings);
      // delay in between reads for stability
    }

On the serial monitor every two seconds I get one line of output and it alternates back and forth between the sensors:

    Conductivity Probe 807.04

    pH Probe 4.12

    Conductivity Probe 802.35

    pH Probe 4.13

    Conductivity Probe 802.35

    pH Probe 4.12

Since I've only got a simple serial line to work with but I need to send multiple, different types of data to the ESP8266, my strategy is to send one line (ex. `Conductivity Probe 807.04`) and use logic on the ESP8226 to parse the string, isolate the float number (`807.04`), and  use `Conductivity Probe` to determine how that number gets further used (in my case, to publish to an MQTT feed called `ElectroConductivity`).

The Tx of the Uno + sensors is wired to the Rx of the ESP8266, and here's the ESP8266 code:

      while (Serial.available() == 0) {
      }
      sensorReading = Serial.readString();
      Serial.println(sensorReading);

The data comes in large groups instead of line by line:

    pH Probe 4.12
    Conductivity Probe 807.04
    pH Probe 4.12
    Conductivity Probe 807.04

I'm new to serial comms and Arduino in general. I'm guessing that there's an issue with how serial is read by the ESP8266.

**EDIT**

When I use `sensorReading = Serial.readStringUntil('\n');` instead my output looks like this:

    Conductivity PrpH Probe 4.12

    Conductivity Probe 816.42

    pH Probe 4.12

    Conductivity Probe 825.8Conductivity Probe 821.11

    Conductivity Probe 821.11

    pH Probe pH Probe 4.12

    ConductivitypH Probe 4.12

title: Receiving serial data in groups instead of individually

Answers: 1

body: `readString()` will keep reading until it times out. Instead try `readStringUntil('\n')` to read until you get a new line character.


body:
I am trying to use port manipulation in interrupts to read a rotary encoder. I found code for a Uno, so the port call for pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively. My code is not working. Do I have my ports wrong? I've tried reading up on this and I'm not fully understanding the Bxxxxxxxx part. I think that might be what's incorrect. Here is part of my code with one of the interrupts.

    static int pinA = 2;
    // Our first hardware interrupt pin is digital pin 2
    static int pinB = 3;
    // Our second hardware interrupt pin is digital pin 3
    volatile byte aFlag = 0;
    // let us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent
    volatile byte bFlag = 0;
    // let us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set)
    volatile byte encoderPos = 0;
    //this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
    volatile byte oldEncPos = 0;
    //stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)
    volatile byte reading = 0;

    void setup () {
      pinMode(pinA, INPUT);
      // set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
      pinMode(pinB, INPUT);
      attachInterrupt(0, PinA, RISING);
      // set an interrupt on PinA,
      //looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below)
      attachInterrupt(1, PinB, RISING);
      // set an interrupt on PinB,
      //looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below)
    }

    void PinA() {
      //CCW
      cli();
      //stop interrupts happening before we read pin values
      reading = PORTH & 0xC;
      // read all eight pin values then strip away all but pinA and pinB's values
      if (reading == B00001100 && aFlag) {
        //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
        encoderPos --; //decrement the encoder's position count
        bFlag = 0; //reset flags for the next turn
        aFlag = 0; //reset flags for the next turn
      } else if (reading == B00000100) bFlag = 1;
      //signal that we're expecting pinB to signal the transition to detent from free rotation
      sei(); //restart interrupts
    }

title: Arduino Mega 2560 interrupt pins and port mapping with rotary encoder

Answers: 2

body:
Re “pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively”, it's true that Arduino digital pins 2 and 3 belong to different ports on Uno vs Mega2560 boards.

Mega2560's have six INTx pins, vs two such on Uno's.  On the Mega, INT0...INT3 are PD0...PD3, and INT4,INT5 are PE4,PE5.  On the Uno, INT0,INT1 are PD2,PD3.  Note, in an answer at [Can external interrupts be OR'd together on the '328 (Uno)?](https://arduino.stackexchange.com/a/19109/3917) I show a couple of routines that will display appropriate masks for pins on different Arduinos.  See the sections “Using other pins for PCIs” and “ISR-framework-generating Sketch”.

---

Here are a few problems with the code shown in the question:

1. `aFlag` is initialized to zero, and is never set nonzero in the code shown.  So the first `if` condition in `PinA()` is never met.

2. `PinA()` is an interrupt handler, connected to interrupts by your `attachInterrupt()` calls.  Because hardware disables interrupts before it enters an interrupt handler, there is no need for the interrupt handler to turn off interrupts.  That is, delete `cli()` in `PinA()`.  Similarly, delete the `sei()` at the end of `PinA()` because hardware restores interrupt status when a RETI instruction executes.

3. The Arduino software environment defines constants like `B00001100` with binary values that match the name.  That is, in the Arduino software environment, constant `B00001100` has the value `0B00001100`.  In my opinion, that's a stupid and unnecessary feature; I suggest that in your code you use standard C notation like `0B00001100` when you want to use binary constant values.

4. I regard writing `encoderPos --` instead of `encoderPos--` as a perversion and suggest deleting that unnecessary space.

5. As you haven't shown the `PinB()` interrupt handler, I don't know how you were going to handle the `encoderPos++` case.  Judging from the code shown, you are using a method that won't correctly handle bounce and intermittent errors.  I suggest using pin-change interrupts and a state-machine method, as illustrated in answers to:
• [Reading from a KY-040 rotary encoder with Digispark](https://arduino.stackexchange.com/a/16420/3917)
• [How to read RPS for fast rotation with status change method in Arduino?](https://arduino.stackexchange.com/a/32043/3917)
• [Read RC receiver channels using Interrupt instead of PulseIn](https://arduino.stackexchange.com/a/18221/3917)
• [Can external interrupts be OR'd together on the '328 (Uno)?](https://arduino.stackexchange.com/a/19109/3917)

body:
On the mega, you'd read the pins with PINE.

So your code in PinA would change to:

```c++
reading = PINE & 0b00110000;

  if(reading == 0b00110000 && aFlag)

  {  encoderPos --;
    bFlag = 0;
    aFlag = 0;
  }
  else if (reading == 0b00010000) bFlag = 1;
```

I found a great discussion talking about the masking required here: https://forum.arduino.cc/index.php?topic=561741.0


body:
Facing difficulty connecting arduino ethernet(w5100) with PC using a switch (Dlink). When both are connected directly(p2p) using ethernet cable, arduino device can be pinged. However, when connected via switch - ping doesn't work, and both devices can't communicate with each other; updated the MAC addr. several times, nothing worked. How can this be resolved?

The same setup works when connected via a router instead of switch. But we need it to work with switch only.

Static ip has been assigned to both PC and arduino uno ethernet shield.

title: Difficulty connecting arduino ethernet with PC using a switch

Answers: 0


body:
I want to develop a soil fertility testing device and need an electro chemical sensor to do so.
I searched the online available sensors but didn't get any source. Does anyone knows anybody in development of such sensors ?

title: Are there any electro-chemical sensors available to measure nutrient contents of soil?

Answers: 1

body:
You have pH and humidity sensors for Arduino, but "soil fertility" is an unprecise term.

If you do a web search, you will find results for a number of devices that claim to measure soil fertility. I am highly suspect of these devices. Even laboratory testing cannot tell you accurately how fertile your soils are because of the methods used. Most labs test for the presence of inorganic chemals, including nitrogen, potassium, phosphorous and an array of other nutrients plants need. What most of them do not or cannot measure is the amount of plant-available nutrients in the soil. It takes a host of soil organisms to make nutrients in the soil available to plants. If those organisms are not present or are low in numbers, it is difficult for plants to take up nutrients. Fertilizers only exacerbate the problem because they kill off soil organisms, especially mycorrhizal fungi, throwing the entire ecology of the soil out of kilter. There are a couple of laboritories out there that test for soil biology and some nutrients.

Soil is hard. There is a lot of things in soil (compactness, unwanted chemicals/elements, microbes) that can affect the *fertility*, even if you have the right nutrients in it.

For hydroponic (not your case), you have cheap handheld EC/TDS meters. The pH and EC of your reservoir is all you need to measure the *fertility* of your water solution.

Go hydro and stop worrying about your tomatoes.


body:
I am working on a project which requires use of 16bit timer . I am using Arduino Uno (Atmega 328p) board and Timer_1 (16 bit timer ) in Overflow mode. i want to use 1024 prescaler settings.

According to the datasheet of the controller i have to set [b]CS10 and CS12[/b] bits to use 1024 prescaler but the problem is OverFlow interrupt routine is never fired when 1024 or 256 prescaler is selected .

The Following code works just fine with Prescaler set to 8 or 64.

    #include <inttypes.h>

    volatile uint8_t sCount = 0;

    void setup()
    {
       Timer_one_16_init(); // configure the timer

       pinMode(13,OUTPUT);

    }

    void loop()
    {
     // do nothing
    }

    void Timer_one_16_init(){

     TCCR1A = 0;

     // set the pre-scaler to 1024 (slowest)

     TCCR1B |= (1<<CS12)|(1<<CS10);

     // set the bottom / starting value

     TCNT1 = 0x00;

     // set Overflow interrupt

     TIMSK1 |= (1<<TOIE1);

     // enable global interrupt
     sei();

    }

    ISR(TIMER1_OVF_vect){

     sCount++;

     if (sCount == 60)
     {
      digitalWrite(13,!digitalRead(13));
      sCount = 0;

     }

    }

i have no idea why this is happening. i have done everything which is given in the datasheet .

Am i doing something wrong ?

Thanks in advance

title: Timer Prescaler problem

Answers: 2

body:
You must write the clock-select bits to the correct value. The simplest
way to do it is to write the proper configuration into the `TCCR1B`
register:

    TCCR1B = (1<<CS12)|(1<<CS10);

In your program, you used `|=` instead of `=`. This doesn't write the
bits appropriately: it only sets (writes to 1) the bits `CS12` and
`CS10` but doesn't clear `CS11`. Since the Arduino core library sets the
prescaler to 64 (`CS11` and `CS10` set), you end up with all the
clock-select bits sets, in which case the timer is clocked by an
external signal on the T1 pin. Not what you want.

------------------------------------------------------------------------

**Edit**: Judging from the comments, it appears that at least dannyf did
not understand my answer, I am therefore adding a clarification. There
are two scenarios when you may want to tweak the control registers of a
peripheral:

1. The peripheral is normally controlled by the Arduino core library,
   and you want to use it through that library. Typical case: you want
   to use a timer to `analogWrite()`, or the ADC to `analogRead()`, but
   you want to clock the peripheral at a frequency which is not the
   core's default.

2. You want to use a peripheral directly rather than through the Arduino
   core. Either you are going to “take it over” from the core, or it's a
   peripheral the core doesn't use in the first place.

In the first case, you should only touch those bits of the control
registers that you must change. The other bits should be left alone, at
whatever values the core has set them to. This is the approach of
dannyf's answer.

In the second case, it is wiser to _not_ rely on the core's default
setting, and instead write _every single bit_ of the control registers
to the values appropriate for your application. This is the scenario of
the original question, and the solution proposed in my answer.

For the particular case of this question, the `TCCR1B` register would
be set to: ICNC1 = 0†, ICES1 = 0, reserved bit = 0, WGM13
= 0, WGM12 = 0, CS12 = 1, CS11 = 0 and CS10 = 1. Combining those bits
together gives the setting `TCCR1B = 0x05;`. However, for readability
reasons, I prefer to write that value `(1<<CS12)|(1<<CS10)`, as in the
question and in my original answer. Some people may prefer to explicitly
write every bit, like

    TCCR1B = (0<<ICNC1) | (0<<ICES1) | (0<<5)    | (0<<WGM13)
           | (0<<WGM12) | (1<<CS12)  | (0<<CS11) | (1<<CS10);

Whichever version you prefer is up to you. I personally don't find this
latter version any easier to read.

†: The values of `ICNC1` and `ICES1` are actually
irrelevant in this case.

body:
    // set the pre-scaler to 1024 (slowest)

    TCCR1B |= (1<<CS12)|(1<<CS10);

that approach presumes for the CS11 bit. in this case, if CS11 is set, the clock source is routed to the CKI pin, and if you don't apply a clock to that pin, the timer will never overflow.

Two options:

1) do it via two steps: set CS12/CS10 and clear CS11; or
2) do it in one step:

    TCCR1B = (TCCR1B &~0x07) | (ps & 0x07);

ps would be whatever prescaler setting you wish to use.

the proposed solution below,

    TCCR1B = (1<<CS12)|(1<<CS10);

is a typical beginner mistake, and a very dangerous one, as it clears other TCCR1B bits without the programmer even realizing it.