text:
Usage of Crypto Library (Speck)
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.

Hello and welcome to Arduino SE! Could you please provide the full error message?

I just made an edit adding the full error message I get.

Which version of the library are you using? (Github link would do just fine)

Sorry, I should have included it: https://github.com/rweather/arduinolibs/tree/master/libraries/Crypto

Does the TestSpeck example included with the library compile without errors?

Yes, it does, and the encryption is done correctly, but I wanted to try a way of manipulating the strings that will be encrypted. This way I could read a serial port and make the encryption.

Okay, that proves the library and IDE is installed correctly. You don't want to spend time debugging your code when the library or IDE itself is broken. Please see my answer how to start fixing your code.

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.

I managed to compile my code without errors, but now the encryption is not working as it should. Should I create another question for that or edit this one?

@LuzA I guess you can ask a new question, but maybe you can fit it here into the comments?

I think I will ask a new question, because I would need to include the code I have right now and well, it's also a different situation that the one I asked in this one.

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");
}


text:
Connecting an Ultrasonic Sensor to Arduino (4-Wire)
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!

First, identify the sensor, and where you found. A snapshot would help as well.

Maybe this can help: http://www.instructables.com/id/Ultrasonic-Range-detector-using-Arduino-and-the-SR/

source: Stack Exchange

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

sort: votes


text:
Blueduino Rev2 service UUID for web bluetooth
I have a Blueduino Rev2 board that I would like to have communicating with a web app (running the chrome bluetooth software) 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) 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.

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]
});

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


text:
How can I configure the RFM95 LoRa module to emit packets at only 'one' particular frequency?
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?


text:
Arduino ESC controlled motor has issues
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
}

In addition to supply issues, ESC's usually require an arming sequence to demonstrate that there is a prepared pilot at the controls.  Sensor-less motor startup algorithms may also be designed with the dynamics of a propeller in mind, not a bare shaft - though do be very careful of clearance and motor mounting if you fit one.  Do not, for example, try to clamp the motor in a vise for a test run, as it's likely to work itself loose.

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.

So the big red and black wires on the ESC should be to the power supply, but where should the small three ones go? This is the one I'm using: https://www.amazon.com/Hobbypower-Brushless-Controller-Multicopter-Helicopter/dp/B00XKX5TBE

Sorry, I did not see earlier you noted the motor has external power. The ESC you linked to provides power out via the small black and red wires, so it would seem you have the connections correct. However the amazon reviews for that product often note the same issue you did (twitching) and say it's a poor quality unit. Is there another you can try?

One more thought: The small red wire supplies 5V, but VIN expects something a bit higher because of the voltage drop. What happens if you power the Arduino via the 5V pin, rather than Vin?

I actually read some information on the motor and noted that I'm using a phone charger to run the circuit. Is it possible that it's not running because the amperage is too low?

What is your motor info, and what are the specs of your phone charger circuit. Without details, we are just guessing mainly.

Charger is 5v 2.0a, motor: https://www.amazon.com/Hobbypower-1000kv-Brushless-Multicopter-Quadcopter/dp/B00E7LG85O/ref=sr_1_8?ie=UTF8&qid=1502322435&sr=8-8&keywords=brushless+motor+and+esc

The specs on the motor say "No Load Current @ 10V: 0.5A" So 5V is going to be on the very low end of getting it to move. Try a higher input voltage.

It's not so much that 5v is insufficient for the motor, as that it's insufficient for the regulator in the ESC, which list a 5.5v minimum right on it.


text:
L298 works only when touched
The following image is my connection of l298 with Arduino.

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.

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.

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.


text:
How can I connect nearly 450 LEDs to an arduino without drawing too much current?
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?

Consider using MOSFET as transistor of TTL type.

I don't know but I would support nothing. Not even a guess

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:

simulate this circuit – Schematic created using CircuitLab
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.

This is a very good Idea! I actually hadn't thought of the difficulty of the programming. Every minute, I need to change one digit and therefore the arduino somehow needs to know what bitcode to write for the new time outcome. Those shift-registers are fun, but not simple. I might consider using an arduino MEGA instead, so I have enough ports to control every segment without complicated code.

simulate this circuit – Schematic created using CircuitLab
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.

Hmm, spacing in didn't turn on code view mode. Is that supported in this forum?

Just paste in your properly indented code, select it all, and click the '{}' symbol on the exit-box toolbar. That will tell the editor to respect your formatting and highlight the section in light-gray.

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


text:
EPS8266 ESP-01: LED manipulation seems to interfere with serial communication
I'm playing around with this udp-example. 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.

Turn the baud rate down to 9600 and see if that helps.  Also not sure about the setTimeout call.

Setting the baud rate to 9600 has no effect when the led stuff is commented out, but if it's not commented I cant see anything on SerialMonitor at all ( setTimeout is also commented out)

Do you have a drivers to the LEDs or are they directly attached to the ESP-01? And have you a extra capacitor as power stabilizer over Vcc and GND?

It is the built in led on the esp I am using. I just connected VCC to VCC of my usb/ftdi- chip (which is plugged in on my notebook).

I'm using this chip from AzDelivery  FTDI Adapter FT232RL

i would suggest you add something to the body of that while loop, just to allow the background activities to continue, even if it's just a short delay or a yield

Do you mean the first one? Why should this change something?

Do you get the same results with another module? Did you enter anything through the serial monitor? Can you place a while (1); after the Serial.println(password) to see if that at least is printed? Maybe also place a yield()  in the while (Serial.available() == 0) { } loop.

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.

I agree, ref. https://github.com/esp8266/Arduino/issues/3165


text:
Wemos D1 mini freezing after a few minutes
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 ;)):

#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?

Are you certain that is the actual code you are using? It doesn't compile because  you call server.begin(), but haven't declared server.

First you stop the client, then you continue writing to it. I have no idea how exactly the client is implemented, but you can imagine how this could lead to memory problems.

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.

Ok I just edited the code like you said and also replaced the call function with the Serial.println() but the issue occured after a few seconds again

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


text:
Using special Arduino "boolean" Data Type instead of standard "bool" data type
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?

This is a basic programming question, not specific to Arduino. The Definitive C++ Book Guide and List. Or Google

Welcome to Arduino Stack Exchange.  Please take the tour at https://arduino.stackexchange.com/Tour to get the most out of this site.  Boolean means binary, like true/false.  Do a Google search on "Arduino data types" to find out about it.

I disagree that this is not an Arduino specific question. boolean is a non-standard type alias for bool set in the Arduino core library and therefore is very much Arduino specific. See my answer for details.

Renaming something doesn't mean it's then specific to Arduino.

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. 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.

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.

The official reference can be found here
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;

That last one should be a = !a shouldn't it?  ~ is a bitwise not.  Depending on how true is defined ~true may still be true.


text:
TEENSY 3.2 RS-232 throughput
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?

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.


text:
Selling a product using Arduino microcontroller or bootloader
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.

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

And what of the Arduino software ?  Also, your comment about retrieving information from the MCU is only conditionally accurate.


text:
Arduino uno R3 Not detected in windows 7 64
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...

It's dead, Jim.  A common issue when you short circuit seems to be that the ATMega16U2 chip dies in some way and the USB never works again.

Maybe you can check the answer in the following question to prevent it next time: https://arduino.stackexchange.com/questions/43188/burning-arduinos-one-after-another/43190#43190

hi, i tried uploading the sketch using an FTDI breakout board with 5V selected connecting as
GND       GND
CTS       not connected
VCC       5V
TxD       D0 (RX)
RxD       D1 (TX)
DTR       To RESET  after hitting upload the progress bar gets struct at 100% after taking too long i get this error :programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x83
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x83
goes about 10 attempts, is there anything wrong in my connection?


text:
PushButton as LED Switch (does not work)
 #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
}

SO basically, it does turn on and off sometimes, but not always on the button press. It seems a wee bit arbitrary. I wait for a second between presses.
Any help at all is apprecaited

Can you please post that code in a more readable format?   I notice that you don't have any code to deal with switch bounce.  That's something you should look up.  Google "Arduino debounce".  I also notice that you're not using the internal pull-up resistors.  Do you have pull-up or pull-down resistors on your button?  How is it wired?

Hey Delta_G, thank you for taking the time to respond. I have tried to redo the code on the question, but could not get the indents to work properly, sorry.
I have used a delay to deal with the bouncing, in a very rudimentary fashion.
I have it wired to a 10kOhm resistor in series with the LED between 1 and GND.
Finally I have a wire going to a pushbutton from the 5V supply, and from the button to the Pin 7 (Input pin, or SWITCH in the code).

Sounds like your input is floating. Read the Arduino tutorial on buttons.

Thank you Mr. Majenko. I will read up on this and see what I can do about it. Would you have any suggestions about dealing with such an input, as I see several on google and was wondering which would be recommended.

Just wanted to update on the fact that adding _PULLUP next to my switch input in pinMode, and connecting the switch to ground did the trick. I am not 100% sure on why this is true, but thank you very much for your help, Mr. Majenko, and Mr. Keijzers.

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.

Thank you very much Delta_G, the explanation was really helpful. Can the floating cause stray signals to interfere on the scale of a few volts as well?

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).

In the lastval assignment, I have pushed the assignment of the last val out by 50ms by delaying the running of the rest of the code. Shouldn't that mean that lastval only changes 50ms later? You are probably exactly right, as it does seem to be luck when it works, but I can't grasp why the delay wouldn't avoid it.
Also, I will change the state as prescribed. Thanks a bunch Mr. Keijzers.

You are right ... probably Majenko has the real reason: your input might be floating ... try adding a pullup or pull down resistor (as a test, print the state continuously, remove the delay temporarily and check if the button really shows false or true when you depress and press it).


text:
Do we need ARM build for arduino while interfacing R-pi and arduino
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

The arm build contains arm binaries for the compiler. Are you running the IDE on the pi?

To interface the two grasp the usb cable firmly by the plug and insert into the usb socket.

please tell me why we need ARM while working with arduino. I have to get the logs of arduino based sensor nodes on raspberry pi. in this case, do i need ARM ?

I need to interface over the wireless medium

And I asked a question. ARE YOU RUNNING THE IDE ON THE PI?

Nope. Not running on pi

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.

Thanks for the clarification. Now i am at ease. R pi is ARM system and we need ARM build for that. right>

Only if you want to compile Arduino sketches using the pi.


text:
Multiple SPI device
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.

So are you saying that if you have only the W5100 connected to the Leonardo it works fine but once you connect the SD reader it doesn't work? Also, it's SPI, not ISP. ISP stands for In-System Programmer, which is something completely different.

Yes this is what I am saying. When I connect both device to SPI only the card reader working and read data from the card, and the ethernet fail at the mentioned point. But if I only connect the ethernet it is working.

When you test individually as you describe, are the SS pin numbers the same (4 and 10)?

What SD reader are you using? Can you describe the exact wiring?

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.

simulate this circuit – Schematic created using CircuitLab

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.

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.

Yes, I have similar card reader as you showed. I hope there is a solution for this problem. http://www.ebay.com/itm/SPI-Reader-Micro-SD-Memory-Card-TF-Memory-Card-Shield-Module-for-Arduino-AD-/112173309871?hash=item1a1e0cdfaf:g:1-EAAOSwJ7RYT2jV

I used until recently the SD recorder shield, but I'm moving to STM32 which has multiple SPI ports, so I can cannot probably (no tried) a simple SD card reader as you have to one port, and other peripherals (like a RF radio) to another SPI.

@MichelKeijzers - I've never used an SPI device (always been an I2C child) but I thought the idea was you used the CS lead to control what gets the message.  From what you have said I assume there is more to it than that.

@CodeGorilla you are right, the CS (Chip Select, or SS: Slave Select) decides who gets the message. Normally one of the CS pins is low and the others are high. The SPI device with CS low pin can communicate with the master. All MISOs and MOSIs have to be coupled, and some devices (like the cheap SD card reader) does not support it ... I don't know the reason.

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.


text:
Using I2C to keep track of position of slaves
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.

Please tell what your project is. Why do you want to know the order ? How long is the maximum total length of the wires for the I2C bus ? What kind of cable will you use ? Perhaps it is possible with jumpers for the I2C address or with the Serial bus in a daisy chain configuration. Perhaps the I2C bus can be daisy chained by using the hardware I2C for the Arduino as a slave and a software I2C for the next I2C bus. That will probably be too complex and unreliable. I can think of more possibilities with extra hardware, but they all will get you into trouble.

I'm trying to make something like little bits or Legos where the user is able to stack the pices in whatever order and it runs sequentially from device to device.

That is typically a daisy chain with the Serial bus.

@jot please explain... As far as I understand it serial really only works for two devices

Suppose you want to send data down and up the chain, then each Arduino should have two serial busses. It can be a software serial bus, but not the standard Arduino SoftwareSerial. One bus connects up and the other bus connects downward the chain. The Arduino boards mainly passes on the information between the serial busses (changing one byte to indicate that it has become one level further down the chain), and the Arduino only takes the command that is for the current Arduino. Each Arduino will know how far it is down the chain. You need a well described and preferably fault-tolerant protocol.

With a single serial bus, each TX is connected to the RX of the next one. The last TX can be connected to the RX of the first one. That creates a round daisy-chain. Maybe what I describe is a cascade ?

Ok, so that allows data in one direction but unless I have a wire connecting the transmit of the bottom of the chain to the receive of the top of the chain there is no way to transmit data back up the chain.

If you don't have a closed round loop of communication and you need data to go up and down the linked chain, then you need two serial ports.

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.


text:
How to compare payload value?
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.

Is the character you are receiving the number 0 or 1?  Or is it the ascii code for the character '0' or '1'?

I also can't help but notice that the code you posted is NOT the code that produced the output you posted.  Can you please post code and output that actually go together?

Please, print the length of the payload.

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.

It may be worth noting that the PubSubClient library that appears to be in use here works with strings for payload data, even though the MQTT protocol sends data un-typed (bitstream). (This is not a criticism of the library, as there is quite limited codespace in Arduinos!)

if (payload[0] == '0') worked out well. Thanks.


text:
Problem uploading Arduino sketch on ESP8266-12e
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?

i also try with esptool.py
with this line:
esptool.py --port /dev/tty.SLAB_USBtoUART write_flash 0x00000 /var/folders/vz/qxry2ffs3rnd2xtd557pgcf00000gp/T/arduino_build_657411/Blink.ino.bin 0x40000 /var/folders/vz/qxry2ffs3rnd2xtd557pgcf00000gp/T/arduino_build_657411/Blink.ino.bin
but it keeps "connecting..." forever
then i can't even stop the process

Just curious but what version of Arduino IDE are you running? I think there may be an issue with newer IDE versions and certain libraries.
Also if you found a solution in another Library it would be nice to post a link to it for others.

the problem was just the silabs library. i downloaded the latest version and it's working

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

Accept your own answer to close this question.

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.


text:
ESP8266-12 is showing garbage when RST is given
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:   %08X\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

Possible duplicate of ESP8266 + Arduino Uno: Can't send AT Commands

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.

Espressif says it can not be disabled.
Ref.: https://github.com/esp8266/Arduino/issues/3047


text:
ADXL345 becomes 0g when plugin MicroSD Adapter using SPI
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.

You may have the same problem as my answer in Multiple SPI device answer ... 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.

And one of the many reasons I use PIC32 instead of Arduino ;)

I actually use Nodemcu, but coding on Arduino library, not lua. And YES, I did use the MicroSD card adapter mentioned your link. It does not work with other SPI device. I will try the other SD Recorder (the bigger one) and I can take a look at STM32 and PIC32.

I found some other posts stating about this type of micro sd card adapter has a design flaw.


text:
IEEE 754 for integer
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?..

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];
  }
}

Although rather than shifting it's probably more effective to cast to a byte array there too.

On an 8 bit system it makes no difference. It's all bytewise access either way. On 16 and 32 bit systems it can make a difference if the architecture has bytewise access operators.


text:
Arduino interrupt sleep mode/reset problem
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;
}

Why does sleepNow() call detachInterupt(1)?

Here is my new code I got it to work on accident by using a boolean. But Now i need to get it to reset when waken.


text:
Menu libaries for a clock
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

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.

Good idea, I like it. What is your recommendation on recognizing pushbutton presses for getting into the menu when in a for loop in another function?

You have to be very carefully with long running for loops ... It's better to not use a for loop but keep an index and keep checking in the main loop, increasing the index when you did one iteration of the loop. Or keep the for loops very short.

Great suggestions, thanks! I've eliminated all for-loops with incrementing counters and push buttons are recognized immediately!

@MarianoElia Good to hear and good luck with your project


text:
Servo jitter with two atmegas
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!

This seems like a fairly unwise design overall.  If your aircraft is large enough to use ESCs rather than pager motors hanging on tiny MOSFETs, it's probably unsafe to be flying with buggy Arduino code.  If your translator must use soft PWM (another bad idea), then it probably should use polled rather than interrupt based i2c receive.

At the very least, you must get rid of the while() loop in the ISR.

if I use polling, I'd have to use an interrupt on the other atmega right? So when you call the requestfrom() function the program on the first atmega must be interrupted to send the data to the second. Or is this not how polling works? I can't have an interrupt on the first atmega because there I am using another interrupt to read the PPM data.

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):

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

thanks for your answer! I solved it now. I used the micros() function to time  the pulses manually. If you (or someone else) wants to see the code just send a message to nemobondt@gmail.com.

Here are two libraries the resolve the problem by using PWM.
https://learn.adafruit.com/neopixels-and-servos/the-ticoservo-library
https://github.com/dadul96/Arduino-Servo-Hardware-PWM-Library


text:
How do I handle multiple interrupts and outputs simultaneously?
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!  :)

Why do you need to use interrupts? Will the MCU ever be doing anything other than waiting for beam breaks and playing notes?

You may be right, right off the bat, but it leads to another question that I don't have the knowledge to know quite yet.... after I sense the break beam and start a 'C note' for x seconds, will I be able to simultaneously  sense another break beam while the 'C note' is playing and superpose another 'D note'?

That depends on how you're handling notes.

Do you have an example where you send a command to run in the background of an arduino, while the void loop continues on it's way? I'll go look for example on the Google too.

You still haven't explained how you're playing notes.

How many individual notes do you want to support?

It doesn't appear that the shield can mix sounds so chords will need to be hardcoded in the SD card

Awesome note, I think I'll have to find a new audio device to support my project.

Most of the examples for that shield seem to suffer from what could be called delayitis. 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.

This is a great solution to avoid interrupts. I'm realizing that my shield isn't going to be able to do the trick cleanly, and that I'm going to need to find a shield that can do some level of mixing so individual sounds can come and go more naturally.

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.

This is a great solution to the first problem. Thank you. I'm realizing that I'll hopefully be able to send the play command to the separate device, but my current choice for second device is questionable but functional.

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.

I think I like this approach, but can an Arduino complete the interupt commands in the background while the void loop continues in the foreground? For example, I'd like to continue playing the 'C-note' while the arduino looks to see if a 'D-note' is played, and if so, I'd like to superpose these two 'notes', while looking to see if the 'C-note' was played again.


text:
No change in acs 712 readings after connection to load
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.

Which sensitivity of ACS712 do you have? If your bulb is really running at 3W off your 9V battery you will only be pulling about 300mA. A 30A ACS712 won't even notice it. A 5A one might see a little change.

Can a 20A ACS712 sensor detect the current going through a 12V and 3W light bulb?

Based on the previous comment it is unlikely that it is sensitive enough.

The 30Amp version will read 66mV/A, the 20A will read 100mV/A and the 5A version will output 185 mV/A.  So even if the sensor does detect the change in the reading you will see on Analog In will be in the region of 5 to 20, which is less probably less than the noise you see anyway.

Sensitivity is very low for low wattage load.

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:

simulate this circuit – Schematic created using CircuitLab
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);

Hi, so what do i use to measure the voltage drop? So that i can feed my Arduino with this data?

The Arduino. As shown in the circuit.

What if i use a 220 ohms resistor? 0.333 * 220 = 73.2v (V= I * R) Does that make any sense?

You will get a lower current with a higher shunt resistor. Shunt resistors need to be small enough to not really affect the circuit

Ok. So i will then take the voltage from my analog output and then multiply it to the 0.333mA so as to get the power? Forgive me, i am relatively new to electronics stuff

No, you take the voltage you read using the analog input, divide it by the value of the shunt resistor, and it tells you what the current is. The 0.333 is an example of what it might give you as an answer.

Ok. So once i have the current, how do i calculate power? I know its I * V but which voltage should i use for power calculation?

It depends what power you want to calculate. The overall power is the overall voltage (the battery voltage) multiplied by the overall current. The power of just the bulb is the voltage across the bulb (which happens to be the battery voltage minus the voltage you measured across your resistor) multiplied by the current.

Ok. I have now grasped the concepts well enough. Thank you very much for sharing your knowledge and patience. You are a very good teacher :)

HI, in your circuit, i have seen you've grounded the circuit twice, once to the power source and the second to the arduino board. Is this necessary? Cause i am short on ground pins in my arduino

https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/


text:
Send serial command and wait for reply
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

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 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).

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.

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
        }
    }
}

Cheers for the quick reply! The floating point format is IEEE. The device essentially sends 8 bytes in response. 4 bytes of which equal a number, and the other 4 equal another number. (For what it's worth, it's just returning coordinates as 8 bytes). Can I somehow interpret those 8 bytes into the two numbers, which would likely be decimals?

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.