text:
One ISR should be called, but both ISR has been called on Arduino UNO
I experimenting with the interrupt ISR using Arduino Uno. In my circuit, I am taking two mechanical switches that are connected with Uno's interrupt pins, pins 2 and 3, and also taking a built-in LED to confirm the ISR call.
My logic is when I press switch1 (which is connected to pin 3) or I press switch2 (which is connected to pin 2) LEDs should be turned on/off by the interrupt service routine.
My problem is that when I pressed switch1 and both ISR are called multiple times.
Here's my code:
const int mechanicalSwitchUpPin = 2, mechanicalSwitchDownPin = 3;

volatile byte stateSwitchUp = HIGH, stateSwitchDown = HIGH;

inline void upCallback()
{

  Serial.println("u");

  stateSwitchUp = digitalRead(mechanicalSwitchUpPin);

}

inline void downCallback()
{

  Serial.println("d");

  stateSwitchDown = digitalRead(mechanicalSwitchDownPin);

}

void setup()
{

  Serial.begin(115200);

  pinMode(13, OUTPUT);

  pinMode(mechanicalSwitchUpPin, INPUT);

  pinMode(mechanicalSwitchDownPin, INPUT);

  digitalWrite(mechanicalSwitchUpPin, HIGH); //Enable Pull-Up resistor to this pin

  digitalWrite(mechanicalSwitchDownPin, HIGH);//Enable Pull-Up resistor to this pin

  attachInterrupt(digitalPinToInterrupt(mechanicalSwitchUpPin), upCallback, RISING);

  attachInterrupt(digitalPinToInterrupt(mechanicalSwitchDownPin), downCallback, RISING);

}

void loop()
{

  !stateSwitchUp ? digitalWrite(13, HIGH) : digitalWrite(13, LOW);

  !stateSwitchDown ? digitalWrite(13, HIGH) : digitalWrite(13, LOW);

  delay(1);

}

Here is the output during one short press/release of the button connected to pin 2:
17:10:06.231 -> d

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> d

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> d

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> d

17:10:06.231 -> u

17:10:06.264 -> u

simulate this circuit – Schematic created using CircuitLab

you can use pinMode(mechanicalSwitchUpPin, INPUT_PULLUP);

Your switches are bouncing.  You need to debounce them.  You can do that in software or you can put a small capacitor across the button.  Google the term "debounce" for more information.

you can also use digitalWrite(13, ((!stateSwitchUp) ? HIGH : LOW))

You shouldn't have serial printing in your ISR.

First of all the bouncing phenomenon are really disturbing, there is A Guide to Debouncing by Jack G. Ganssle https://my.eng.utah.edu/~cs5780/debouncing.pdf. Second issue that contributes to the abnormal behaviour is the fact that this is the same interruptable. Doesn't matter SW1 is pressed or SW2 is pressed, both ISR going to be called. Am I right?


text:
Will 5V to input pin damage the Arduino board?
I am fairly new to Arduino. When I am experimenting with circuits, do i need to worry about shorting out a pin if I accidentally connect the +5V pin on Arduino to an input pin on Arduino without a resistor? I just want to make sure I avoid destroying the board when learning how to create circuits.

No, no short. Arduino (Atmega) pins default to inputs. Pins configured this way are said to be in a high-impedance state. Input pins make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 megohm in front of the pin.
Answer provided by Look Alterno and converted from a comment.

However be careful that your code does not set any such pins to outputs.

source: Stack Exchange

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

sort: votes


text:
Controlling JX PDI-6221MG Digital Servo with Arduino
So, I naively bought two of these JX PDI-6221MG Digital Servos thought they would work with the Arduino straight out of the box, just like MG996R did, for instance, but it seems they won't. However, I hear some clicking noise when the motor is connected, tho.
These are the Servo specs:
Dead band: 2μs
Working frequence: 1520μs / 330hz
Operating Speed (4.8V): 0.18 sec/60°
Operating Speed (6V): 0.16 sec/60°
Stall Torque (4.8V): 17.25 kg/cm
Stall Torque (6V):  20.32 kg/cm
Dimensions: 40.5X20.2X38mm
Weight:  62 g
Connector Wire Length: JR  265 mm
Bearing: 2BB

Manufacturer site: http://www.jx-servo.com/English/Product/49513727.html
Additionally, I used 5V 2.4A power input alongside with the Arduino Nano running just some sample code:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(3);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Wiring:

I tested the same configuration with MG996R and SG90 and it worked. So what am I missing here?

Care to share your wiring?

Added wiring :)

Maybe these serves move slower and you are changing position too quickly. Try a simple sketch where you give one position and hold it for 1 second.

Thanks, good guess, but it didn't work. I also tried to increase voltage up to 7.4V but no progress. Only a clicky noise is to be heard.

i have same problem. i found that they not work with a tester. But gear is very good, sow i did take them a part and use them as gear motor, sow it is not totaly lost, but as normal servo is NO GO!!!!

can u tell to me about the supply ? im using the battery 6,8 volt with 6800 mAh but still cant use the servo,im stuck right now please help me

Check answer. @tommy

I managed to get servos running with 6 V and 3 A powered from lab power supply (GOPHERT CPS-1620 0-16V 0-20A). I guess, at the end, it was power supply which was crucial.

If you connect the servo to the same power supply as the MPU make sure you have a robust amperage rating.  As soon as the servo tries to move, the current draw shoots way up and your MPU will hit a brownout state and reboot.  At the very least you will need a capacitor at the power input to the MPU.

this servo is an absolute power hog.  You can run it off 5V (6V is not needed!), but it's drawing 0.44 amps of power

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

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


text:
Programming ATMEGA328p via AVR Pocket Programmer
I have a ATMEGA328p on a breadboard with the following connections to the 2x3 ICSP connector and its connected to AVR Pocket Programmer.

While running AVRDUDE utility, i get the following error,
avrdude -c usbtiny -p m328p

The controller is powered by the AVR and i have made certain about the pinout. Anyone run into the above error?
Adding more verbose output from the terminal.

please do not post pictures of text

Is the chip wired to receive the correct clock that it is configured for?

There is no mention of any external clk needed or required.

Hi, which text to be specific so I can remove that.

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


text:
HC-05 receives only first few bytes
I have an android device and stm32f103 + HC-05 bt dongle. I'm sending 10 bytes "0123456789" string from android to stm32, but I'm receiving only random 1-5 bytes. code on stm32 side:
long received = 0;
const unsigned long buffer_size = 128;
uint8_t buffer[buffer_size];

void setup() {
    Serial1.begin(9600);
}

[...]
void loop() {
    [...]
    if(Serial1.available()){
        received += Serial1.readBytes(buffer + received, bufferSize-received);
    }
}

So, if will send "0123456789" from android, let say, 3 times every 1 second, on stm32 i will receive 3 portions like this:
"0", "0567", "047"
or something like this, i.e. I always receive first byte and it's always correct, but it looks like the rest bytes could be randomly lost.
any idea what am I doing wrong?
P.S.> On stm32 side I'm using Arduino STM32 library. Serial1 is a UART interface, which is located on stm32f103's PA9 and PA10 pins.
I tried to use other bod rate (19200, 38400), but in this case the data is completely corrupted, i.e. just random bytes.
When I'm sending data from stm32 to Android everything works just fine, i.e. I'm receiving all the data on android side.
I'm using standard BluetoothSocket on android side. So, code looks like this:
BluetoothSocket socket;
OutputStream outStream;
[...]

void init(...) {
    socket = ConnectToSTM32(...);
    [...]
    outStream = socket.getOutputStream();
}

void send(byte[] bytes) {
    outStream.write(bytes);
}

[...]
String strToSend = "0123456789";
send(strToSend.getBytes());

Without seeing the rest of your code we can't help you. There's nothing obviously wrong from that snippet, so the problem is likely elsewhere.

Indeed without the rest of the code we can't tell, but I bet £1 you're assuming that all the data will arrive in one lump and that when Serial1.available() returns false you've got it all, which is a bad assumption. Still, edit the question so that it's useful for others.

Have you set values to your HC-05? Meaning changing the rate? Android send data at about 115200 bauds. So if you try to receive them at 9600 and display at this speed, this can explain whay's happening. Also, on Android side, performing a Log("info") must be a good idea to be really sure of what you send. Also, from where came "Serial1"?

@Majenko Added some extra details

@MarkSmith I don't assume anything - I just read available data from Serial1. I don't know how many bytes are available - just read them all and write this data continuously to a buffer

@Peter I've added some extra information. I've tried to use different speed, but not 115200 - will try it today. I didn't find any information how can I setup bluetooth speed on android side (actually, I thought it should be negotiated automatically). What exactly can I log to ensure of what I'm sending? I use Java OutputStream's write method to send data.

I think you'll get much better quality help if you post a minimal, complete, verifiable example of the problem.

@MarkSmith Will do it today, but I doubt you could repro it because of hardware specific. I suspect that problem is on android side and it, probably, related to stm32 serial stream implementation.

@Tutankhamen I've found nothing on Android to set Bluetooth speed. My App use it at 115200 as it seems to be the "basic speed". The problem came from from the fact this speed is not avaible with the SerialSoftware lib  on the Arduino (higher than 19500, the lib start to loose bits). On Arduino I use the basic RX and TX pin with Serial.begin(115200).

@Tutankhamen Contact me via my profil and I'll send you the Android code from my App, for Bluetooth. Maybe this would help;

@Peter I don't think there is a way to send private message in StackExchange

Just tried the same code with the same HC-05 module, but with Arduino Nano - everything works just perfect

Try adding a delay (10) inside if (serial1.available())

@MITURAJ For what?

Cz UART data reception is slower than microcontroller execution

And how delay could help? The logic now is: if (data_available) read_data();

https://stackoverflow.com/questions/9901058/arduino-cant-read-serial-properly

@MITURAJ It shouldn't work like this, but anyway it's not the case. I'm polling data from the local buffer, not from remote device.

So, the problem was in disabled interrupts. I just remove a library which is forcibly disabling interrupts and everything is working now.

Okay. You have not posted the full code. So we can only assume based on current code snipping.


text:
ledkeypad shield not responsive
I recently purchased several of the DFRobot ledkeypad shields: https://www.dfrobot.com/product-1407.html
I have Arduino Leonardo (which also had some problems in the beginning, being recognized as modems).
My OS is Linux Mint, and I'm using the last Arduino IDE.
The library I use is the one recommended on the website of the vendor, LedKeypad.h, and works fine with the other shields of the same model from the same batch.
Some shields worked fine but I am now having trouble with one of them, which seems unresponsive. I can load for instance the blink program in the arduino, and it works, but the shield does not work. When it is plugged in, the fours dots are slightly red, and I cannot turn them off.
I tried displaying something on the serial monitor when the buttons are pushed, and only one of the 5 buttons works (the KEY_DOWN one).
Is there anything I can attempt to fix the problem ? Or should I just give up on this shield ?

the information that you have posted is incomplete. ... there is no mention of software ... please include all info in the question ... do not use comments to add info

@jsotola added software info, is all the relevant information there ?

what i am talking about is that you made no mention of any libraries for the arduino. there is no way to tell if you downloaded the correct libraries.

@jsotola oh sorry I added info about the library

... and works fine with the other shields of the same model from the same batch.

So had you considered that the shield might be faulty? Have you contacted the manufacturer or vendor for support?

The schematic seems to show that it uses the actual SDA/SCL pins on the digital header (next to Aref) instead of A4/A5, so it should be compatible with other boards as well. The buttons are just a voltage divider connected to an analog input, so that should work with the Leonardo as well.

I had not seen that.


text:
Problem with interrupts and 4x encoders on Nano 33 BLE
I have a Pololu 4x encoder and am trying to write some code to make it work on my Nano 33 BLE. (Interestingly enough, the issue preventing some pre-existing libraries from working for me is the same issue that I'm about to describe here...)
When I turn the motor shaft clockwise, these are the signals that I get (first bit in each pair is channel A, second bit channel B):
11 -> 10 -> 11 -> 10 -> 11 -> 10
Note how channel A's value never changes, and B's value toggles back and forth.
Likewise, for the counterclockwise direction:
01 -> 11 -> 01 -> 11 -> 01 -> 11
This is of course wrong, as the channels' values should be something like 00 -> 10 -> 11 -> 01 -> 00 as the shaft turns. As a matter of fact, that is exactly what I get when I run the exact same code on a regular Arduino Nano.
Does anyone know what's going on? Here's my code. AFAIK I'm not using interrupts incorrectly or anything, at least for the regular Nano.
#define PIN_A 2
#define PIN_B 3

volatile int val = 0;
volatile bool newVal = true;

void encoder() {
  int a = digitalRead(PIN_A);
  int b = digitalRead(PIN_B);
  val = ((a << 1) | b);
  newVal = true;
}

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

  pinMode(PIN_A, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_A), encoder, CHANGE);

  pinMode(PIN_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_B), encoder, CHANGE);
}

void loop() {
  if (newVal) {
    Serial.print(bool(val & 0b10));
    Serial.print(bool(val & 0b01));
    Serial.println();
    newVal = false;
  }
}

EDIT: After taking a look at the following diagram, it appears that the erroneous encoder patterns match those in which only rising edges are detected. So for some reason, attachInterrupt() is acting as if the CHANGE argument were RISING instead for the Nano BLE.

Probably not the source of your issue, but change val from a volatile int to a volatile byte.  You only need one byte and with int you're technically doing a multi-byte read of a volatile variable with all that entails.

So it turns out the cause of the issue was that attachInterrupt()'s implementation in the nRF528x Mbed core does not properly support rising/falling edge detection as required for mode CHANGE. I've opened a pull request implementing the changes required and tested them with my encoder, and I can confirm that everything works properly now.
If you'd like to test the updated core yourself, you can follow the installation instructions from the repo's README or from this very well-written forum post.

Best practice would be to use a single interrupt for the encoder.  BLE has a faster processor and your code is not frame-based so that just might affect it also.  This code doesn't do exactly what your code did but it will use val to track position as a number.
It can also be made a bit finer using CHANGE instead of RISING, but for debugging bare bones means less that can go wrong.
#define PIN_A 2
#define PIN_B 3

volatile int val = 0;
int oldVal;
//volatile bool newVal = true;

void encoder() {
  if(digitalRead(PIN_B)) ++val;
  else --val;
}

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

  pinMode(PIN_A, INPUT_PULLUP);
  pinMode(PIN_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_A), encoder, RISING);
}

void loop() {
  if (val != oldVal) {
    oldVal = val;
    Serial.println(oldVal);
  }
  delay(500);
}

Welcome to Arduino:SE.  Please don't post multiple answers to the same question.  Just edit the information into your original answer.

Please evaluate answers as answers without bias for who posted them.

I'm not bothered by who posts the answers, but SE is a Q&A site, rather than the forums you might be used to.  There is rarely any need for anyone to post more than one answer to a given question.  You might find it helpful to review the site tour and Help Centre and, in particular, How do I write a good answer?.


text:
Arduino Uno "if" statement is ignored in code and halts execution when using Serial.ReadString()
I'm having a weird issue with my Uno trying to power on a PWM fan using a MOSFET.
I'm setting a simple power on/off code using commands sent over the Serial Monitor, and although this code worked before, after I tried to add some code to control the speed of the PWM fan, my if statements do not work anymore, even with the simple power on/off code:
    String command;           //Define the string variable "command"

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

  pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
  pinMode(13, OUTPUT);    //Set pin 13 to use onboard LED as a waiting for command status LED
  digitalWrite(5, LOW);   //Start with MOSFET off
  digitalWrite(13, LOW);  //Star with status LED off
  Serial.begin(9600);     //Start Serial comm for sending commands

}

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

  Serial.println("What's your command?"); //Ask for a command in the Serial Monitor

  while (Serial.available()==0) {        //Wait for user input stopping the code
    digitalWrite(13, HIGH);               //Blink the onboard LED indicating that the code is waiting for user input
    delay(100);
    digitalWrite(13, LOW);
    delay(100);
  }

  command=Serial.readString();          //Save the Serial Monitor String command to the "command" variable as a String
  Serial.println("data read");          //Confirm Serial Monitor input
  Serial.println(command);              //Print the command sent over the Serial Monitor to confirm the data received

  if (command=="On") {                  //Turn the MOSFET on
    digitalWrite(5, HIGH);
  } else if (command=="Off") {                  //Turn the MOSFET off
    digitalWrite(5, LOW);
  }
  else {                                 //Provide feedback for a wrong command
    Serial.println("Wrong command!");
  }
}

This is my Serial Monitor output after sending "On":
What's your command?
data read
On

Wrong command!
What's your command?

To check if the pin works, I tested a simple code that worked fine:
void setup() {
  // put your setup code here, to run once:

  pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
  digitalWrite(5, LOW);   //Start with MOSFET off
  Serial.begin(9600);     //Start Serial comm for sending commands

}

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

    digitalWrite(5, HIGH);
    delay(2000);
    digitalWrite(5, LOW);
    delay(2000);

}

Does anyone have any idea why the if statements are not working anymore?
Thank you in advance!
AC
EDIT: After trying to use the "else" statement as recommended by per1234, the issue continues to happen, but changing the variable type to an integer works, although the Serial output is rather messy:
int command;           //Define the int variable "command"

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

  pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
  pinMode(13, OUTPUT);    //Set pin 13 to use onboard LED as a waiting for command status LED
  digitalWrite(5, LOW);   //Start with MOSFET off
  digitalWrite(13, LOW);  //Star with status LED off
  Serial.begin(9600);     //Start Serial comm for sending commands

}

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

  Serial.println("What's your command?"); //Ask for a command in the Serial Monitor

  while (Serial.available()==0) {        //Wait for user input stopping the code
    digitalWrite(13, HIGH);               //Blink the onboard LED indicating that the code is waiting for user input
    delay(100);
    digitalWrite(13, LOW);
    delay(100);
  }

  command=Serial.parseInt();          //Save the Serial Monitor imput command to the "command" variable as an int

  Serial.println("data read");          //Confirm Serial Monitor input
  Serial.println(command);              //Print the command sent over the Serial Monitor to confirm the data received

  if (command==1) {                  //Turn the MOSFET on
    digitalWrite(5, HIGH);
  }
  if (command==2) {                  //Turn the MOSFET off
    digitalWrite(5, LOW);
  }
  else {                                 //Provide feedback for a wrong command
    Serial.println("Wrong command!");
  }
}

And the Serial Monitor output:
What's your command?
data read
1
What's your command?
data read
0
Wrong command!
What's your command?
data read
2
What's your command?
data read
0
Wrong command!
What's your command?

Does anyone experience this issue? I even tried rolling back my IDE to 1.8.3, which I used to write the code the first time, then after a library update, and also getting version 1.8.5, it stopped working.
Also, anyone knows how to avoid the multiple Serial Monitor outputs?
I tested this with "String" variables to be able to get this fixed.
Also, a side question regarding the post size, should I remove the original code when editing, or should I move it to another answer?
Thank you.

The problem with the original code is evidenced in the following:
What's your command?
data read
On

Wrong command!

See that blank line?  Nowhere in your sketch do you specifically print a blank line, rather it is being printed because the command string contains a carriage return and/or newline character captured with the input, which is causing a comparison of exact equality to fail.
To fix this, you could either trim these non-printing characters off the end, or use a different comparison, for example command.startsWith("On").  But if you do use a start-of-string comparison, beware if you have any command verbs that extend other shorter ones.
You also have a bug in your block if-else statements, in that instead of
if ...
if ...
else ...

you should have
if ...
else if ...
else ....

So that the "none of the above" clause only runs when none of the conditions are satisfied, rather than running whenever the penultimate condition is not satisfied.
In terms of the numeric version producing an un-entered value of 0, this is the documented return value of the parseInt() methods if they time out without finding a valid integer.
It would be more traditional to use an end-of-line condition rather than a timeout to detect the end of user input.  Many traditional "until end of line" read mechanisms trim the line ending characters off the resulting string for you, eliminate the comparison problem, too.

Thank you Chris, the if-else statements have changed on my second revision of the code, since the serial output doesn't have the blank line anymore. Do you think deleting everything from my Arduino folder under the Windows user folder would help? The newline or carriage return can be causing the 0 character to show up automatically on the serial output on my integer code.

No, don't wipe your install, rather see the documentation for parseInt and what it says it does if input times out with no number entered.

Let's look at what this code does when you send "On":
  if (command=="On") {                  //Turn the MOSFET on
    digitalWrite(5, HIGH);
  }

This will evaluate true so pin 5 is set to HIGH.
  if (command=="Off") {                  //Turn the MOSFET off
    digitalWrite(5, LOW);
  }

This will evaluate false so the else clause is executed:
  else {                                 //Provide feedback for a wrong command
    Serial.println("Wrong command!");
  }

So the output you are seeing is correct for your code. The problem is that your code doesn't match your intent. For that you need to change this line:
  if (command=="Off") {                  //Turn the MOSFET off

to:
  else if (command=="Off") {                  //Turn the MOSFET off

Then the else clause will only run if the command doesn't match "On" or "Off".
For more information see:
https://www.arduino.cc/reference/en/language/structure/control-structure/else/

Thank you per1234. I'll test this and provide feedback later in the day.

Hi per1234. Unfortunately, this did not fix my issue, but changing the variable type did. Can you please check the code in my edit?

Thank you for your help.
I have been able to find the root cause of my original problem.
After reading this post on https://forum.arduino.cc/index.php?topic=73372.0, more specifically an answer regarding filtering for \n and \r characters and the Arduino IDE Serial Monitor line ending option.
My problem was caused by having the "Newline" option selected in the Serial Monitor. After selecting "No line ending", my original code runs as expected, and I know now how to use String variable and Serial.readString() in a more efficient way, and the if-else statements.
Also, the blank line mentioned by Chris Stratton is gone, and my search to fix that led me to the solution of the main problem, and the code also works 100% with the formatting help provided by per1234.
Thank you both again for the help.

You probably do not want to disable the line ending transmission; rather you likely want to read until a line ending (and then exclude it) rather than until a timeout.  The Arduino serial monitor is a bit odd as a client in encouraging you to tap an on-screen button to send, more typically it's pressing return than triggers transmission, or else if characters are sent as typed, makes the recipient act on them.

Thank you for that info Chris. I will look into that. For now, I'm going to use the serial monitor to simulate the input and effects on my code, since my final goal is to setup the Arduino to read external analog signals, but since I'm quite new to this type of programming, I'm trying to understand what I can or can't do. I've been using Arduino for some years, but mostly with pre-assembled sensor boards and copy pasting code.


text:
LED fade class strobes for unknown reason
Okay, so here is what I'm trying to accomplish:
I have four LEDs, under my fish tank, that I want to fade in and out.  I want each LED to fade at a different rate, start at a different "brightness" with PWM, and get a "new" fade-rate every once in a while.  Ultimately, it'll make the bottom of the fish tank "pulse" in a "natural" way.
The code I'm using to accomplish this can be found in my GIT repo.  There is also a GIF of it "working," there.

Now, here is my problem:
Every once in a while, one of the LEDs (not a specific one) will stop fading and start blinking like a strobe light.  I'm not sure what's causing this blinking, since it seems to happen randomly.
The other three LEDs seem to continue to fade in/out while the "bad" LED is spaz-ing out, and it doesn't seem to be isolated to a specific LED.  It also doesn't seem to affect only one LED at a time, although it's usually only one LED "blinking" and any given time... but I have seen two going at the same time.
It also doesn't seem to be specific to the "high" or "low" PWM levels, either... it can happen at "bright" levels, "dim" levels, or even in the middle of the fading transition.

Here's what I've tried:
I've tried different Arduino boards, and I've taken the LED count down to a single LED.  I've changed variable types from bytes to ints, and back and forth with that tactic.  I've been combing through this sketch all day, and I don't see anything that stands out to me as causing the problem.
So, now I'm turning to you all, hoping that someone will be able to see where I've screwed up my code.
Thank you, in advance!

EDIT:  Since I've been asked for direct posting of my code, instead of just a link to the source code:
Here is the main .ino file:
#include "led_controller.h"

// Set pin numbers for each LED
byte led1 = 3,
           led2 = 6,
           led3 = 9,
           led4 = 11;

void setup(){
    pinMode( led1, OUTPUT );
    pinMode( led2, OUTPUT );
    pinMode( led3, OUTPUT );
    pinMode( led4, OUTPUT );
}

// Initialize our four classes for our four LEDs
LED a( led1 ),
    b( led2 ),
    c( led3 ),
    d( led4 );

void loop(){
    a.ledChange();
    b.ledChange();
    c.ledChange();
    d.ledChange();

    delay( 60 );
}

And the header file with the class:
// Create our custom LED class
class LED{
    private:
        // Set higest and lowest brightnesses for LEDs
        byte highest = 250,
             lowest = 5;
        byte pin, brightness, isNeg; // Random necessary variables
        int change; // Set the inc/decrement rate for the LED
        int checkNeg(); // See if our change rate is negative, or not
        void changeChange(); // Get a new change rate
    public:
        LED( byte led ); // Define our constructor
        void ledChange ();
};

// Define our constructor
LED::LED( byte led ){
    pin = led;
    changeChange();

    // Set the initial LED brightness by random
    brightness = random( lowest, highest );

    // Randomly determine if the LED will start brightening or darkening
    if( random( 1, 2 ) == 1 )
        change *= -1;
}

// Get a new change rate
void LED::changeChange(){
    change = random( 1, 4 );

    if( isNeg )
        change *= -1;
}

int LED::checkNeg(){
    if( change < 0 )
        return 1; // If `change` is negative, return true
    return 0;
}

void LED::ledChange(){
    // Flip LED change value between brightening and darkening
    if( brightness <= lowest || brightness >= highest ){
        change *= -1;

        isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

        // A 1-in-25 chance to change the fade-rate
        if( random( 25 ) == 13 )
            changeChange();
    }

    brightness += change; // Adjust the LEDs brightness

    analogWrite( pin, brightness ); // Brighten/darken the LED
}

Sounds like integer wraparound to me.

It sounds like the values you are using for PWM are going outside of the range needed for the fading in and out effect. As part of changing the values, make sure that the value generated for the next setting is within the range for the LED effect that you want to see. I am not sure what library you are using or what PWM settings are being changed or I could be more specific. I am not willing to take the time to peruse your git repository so if you want to update your question with the specific code that generates a new setting, that may be helpful.

I believe I'm staying well between the byte values of 0 and 255.  I am just using the regular Arduino analogWrite() function for PWM.

I added some Serial.print() statements to your code to point out the bug:
This is the modified LED::changeLed() function I used:
void LED::ledChange() {

  /**/Serial.print(brightness);

  // Flip LED change value between brightening and darkening
  if ( brightness <= lowest || brightness >= highest ) {
    change *= -1;

    isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

    // A 1-in-25 chance to change the fade-rate
    if ( random (25) == 13 )
      changeChange();

  }

  brightness += change; // Adjust the LEDs brightness

  analogWrite( pin, brightness ); // Brighten/darken the LED

  /**/Serial.print("\t+ ");
  /**/Serial.print(change);
  /**/Serial.print("\t= ");
  /**/Serial.print(brightness);
  /**/Serial.print("\t");
  /**/for (int i = 0; i < (brightness / 5); i++) Serial.print("*");
  /**/Serial.print("\n");
}

I marked the additional lines with /**/.
Here is a piece of the serial monitor output, where the bug occurred.  The columns are organised as follows: brightness before the function changed it + change = brightness at the end of this function. The * lines graphically represent the LED brightness (i.e. the last number); this allowed me to run your sketch without a physical LED, at much higher speed (I deleted the delay(60) in loop()).
183        +    3         =    186  *************************************
186        +    3         =    189  *************************************
189        +    3         =    192  **************************************
192        +    3         =    195  ***************************************
195        +    3         =    198  ***************************************
198        +    3         =    201  ****************************************
201        +    3         =    204  ****************************************
204        +    3         =    207  *****************************************
207        +    3         =    210  ******************************************
210        +    3         =    213  ******************************************
213        +    3         =    216  *******************************************
216        +    3         =    219  *******************************************
219        +    3         =    222  ********************************************
222        +    3         =    225  *********************************************
225        +    3         =    228  *********************************************
228        +    3         =    231  **********************************************
231        +    3         =    234  **********************************************
234        +    3         =    237  ***********************************************
237        +    3         =    240  ************************************************
240        +    3         =    243  ************************************************
243        +    3         =    246  *************************************************
246        +    3         =    249  *************************************************
249        +    3         =    252  ************************************************** #####
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************

The bug begins at the line I marked with ####. I'll try to narrate the events from the point of view of your function, starting from line #### (1):

Is brightness 249 in range? yes -> don't invert sign | add 3 | return
Is brightness 252 in range? no -> invert | change fade rate? yes, new fade rate = ±1 | add -1 (we just inverted the sign) | return
Is brightness 251 in range? no -> invert (here's the bug!) | change fade rate? no | add +1 (ve should subtract, but we just inverted the sign...) | return
It continues like that until a fade rate change occurs, oscillating between 251 and 252. That looks out like a constant brightness.
The fade rate increases and the oscillation values change, maybe approaching 255 (if the smaller value goes below 250 the led will continue to behave properly, but that's not our case).
Another fader rathe change causes the program to make brightness greater than 255 (in our case 254 + 2). And if you add 2 to a one-byte unsigned variable holding a value of 254 you won't get 256 (the variable can't hold that value) but 0. That's something called "integer wraparound", as Majenko pointed out in his comment to your question.

So, that was a long description of a very simple problem.
To solve it you cold for instance prevent the brightness value to be greater than 250 and smaller than 5 adding two lines to your ledChange function:
void LED::ledChange(){
    // Flip LED change value between brightening and darkening
    if( brightness <= lowest || brightness >= highest ){
        change *= -1;

        isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

        // A 1-in-25 chance to change the fade-rate
        if( random( 25 ) == 13 )
            changeChange();
    }

    /**/ if(brightness > highest) brightness = highest;
    /**/ else if (brightness < lowest) brightness = lowest;

    brightness += change; // Adjust the LEDs brightness

    analogWrite( pin, brightness ); // Brighten/darken the LED
}

Holy cow!!!  You are absolutely amazing!  I have stepped away from this, because I was just getting frustrated, and could NOT figure it out... but you nailed it on the head!  I wish I could give you more than just a fake internet point.


text:
Every so often ESP8266 hangs... WifiClient seems to be at fault
This code works fine without any freezes:
#include <ESP8266WiFi.h>
#include <Servo.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>

Servo turn;

ESP8266WiFiMulti wifiMulti;

const char* host = "192.168.1.148";
WiFiClient client;

int turnPos = 90;
unsigned long ts = 0;

void setup() {
  startWiFi();
  turn.attach(14);
  turn.write(90);
}

void loop() {

  if (millis() - ts > 500 && millis() - ts < 1000) {
    turnPos = 160;
  }
  else if (millis() - ts >= 1000) {
    ts = millis();
  }
  else {
    turnPos = 20;
  }

  /*if (client.connected()) {
    }
    else {
    if (!client.connect(host, 3000)) {
    }
    }*/

  turn.write(turnPos);
  yield();
}

void startWiFi() {
  wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }
}

While this code (with the wificlient bit commented out) freezes every so often:
#include <ESP8266WiFi.h>
#include <Servo.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>

Servo turn;

ESP8266WiFiMulti wifiMulti;

const char* host = "192.168.1.148";
WiFiClient client;

int turnPos = 90;
unsigned long ts = 0;

void setup() {
  startWiFi();
  turn.attach(14);
  turn.write(90);
}

void loop() {

  if (millis() - ts > 500 && millis() - ts < 1000) {
    turnPos = 160;
  }
  else if (millis() - ts >= 1000) {
    ts = millis();
  }
  else {
    turnPos = 20;
  }

  if (client.connected()) {
    }
    else {
    if (!client.connect(host, 3000)) {
    }
    }

  turn.write(turnPos);
  yield();
}

void startWiFi() {
  wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }
}

Only difference is in the working one the WifiClient bit of code is commented out.   How would WifiClient cause this problem?

fun with esp8266. try new core package 2.4.2

I see you're using String in a terrible way. If this snippet is anything to go by you're probably doing the same thing elsewhere, and making swiss cheese of your heap.

The problem still occurs without the String bit -- I have edited my question to include all of my code.

yes and this is fixed in latest version of arduino esp8266 core

Are you sure?   How can I check the version?   Because I think I have the most updated version.

It is a bug and it was fixed in Arduino esp8266 core package 2.4.2 published 2 days ago.
see first line in ESP8266WiFi section of the changes list

2.4.2 ESP8266WiFi:
  Fix memory leak when reusing WiFiClient object (#4497, #4516, #4549)


text:
3.3v Arduino I2C communication with motor controller powered at ~6v
I am trying to just use the voltage from 4 Alkaline AA batteries in series (6v nominal) to power a motor with the TI drv8830 IC.
My question is, will this circuit (specifically just pulling the sda and scl pins to 3.3v) work reliably?   The datasheet says at maximum of 6.8v vcc the chip will still recognize 3.3v i2c lines (minimum 3.13V at that vcc voltage) but will the varying voltage of the battery cause the communication to be unstable?   There is a 10uf capacitor between vbat and gnd (not shown).

will the varying voltage of the battery cause the communication to be unstable?

No. As the battery voltage drops the input HIGH threshold (which is a function of VCC) also drops. If anything as the battery voltage drops the communication becomes more stable.
Since I2C is an open drain protocol the voltage makes no different for sending data - that voltage is set by the pull-up resistors to 3.3V.


text:
How to control a DRV8266 motor controller with an ESP8266?
https://github.com/sparkfun/SparkFun_MiniMoto_Arduino_Library/tree/V_1.1.0
Will this library work on an esp8266?   If not is there any way I can get this driver to work on the ESP?

As Ignacio kindly pointed out (+1), the answer to my original question is no.

The following code works to control a Sparkfun Minimoto board, though, or more generally the DRV8830.   Just connect GPIO5 to SCL and GPIO4 to SDA.   On some variants the default SDA/SCL pins are different though -- you can always use any pins (except for GPIO0, GPIO2, and GPIO15 -- see my recent post on using these pins) for your I2C bus and just call wire.begin(sda,scl) where sda and scl are the pin numbers you want.
#include <Wire.h>

#define MOTORA_WRITE 0x64
#define MOTORA_READ 0x65
#define CONTROL_addr 0x00
#define FAULT_addr 0x01

void setup() {
  Wire.begin();

  drive(20);//enter values from -63 to 63, where negative values are reverse
  delay(100);
  coast();//releases the motor
  delay(100);
  brake();//brakes the motor

}

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

}

byte tsState = -99;//used so redundant calls of any of these methods don't do anything -- only new calls will trigger communication with the motor controller
void drive(int speed) {
  if (speed != tsState) {
    tsState = speed;
    // Write to the Fault Register to reset it
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(FAULT_addr);
    Wire.write(0x80);
    Wire.endTransmission(true);

    // Write to the Control Register
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(CONTROL_addr);
    byte regValue;
    regValue = (byte)abs(speed); // Find the byte-ish abs value of the input
    if (regValue > 63) regValue = 63;
    regValue = regValue << 2; // Left shift to make room for bits 1:0
    if (speed < 0) regValue |= 0x01; // Set bits 1:0 based on sign of input.
    else regValue |= 0x02;
    Wire.write(regValue);
    Wire.endTransmission(true);
  }
}
void brake() {
  if (tsState != -98) {
    tsState = -98;
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(FAULT_addr);
    Wire.write(0x80);
    Wire.endTransmission(true);
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(CONTROL_addr);
    byte regValue = (byte)63;
    regValue = regValue << 2;
    regValue |= 0x03;
    Wire.write(regValue);
    Wire.endTransmission(true);
  }
}
void coast() {
  if (tsState != -97) {
    tsState = -97;
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(FAULT_addr);
    Wire.write(0x80);
    Wire.endTransmission(true);
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(CONTROL_addr);
    byte regValue = (byte)0;
    Wire.write(regValue);
    Wire.endTransmission(true);
  }
}

No, since it uses AVR defines. Convert the code that uses these defines to the equivalent ESP8266 code instead.


text:
Burn normal bootloader onto Atmega328P configured to use internal 8MHz clock
I have an Atmega328P that I have previously burned with a bootloader configured to use the 8MHz internal clock as described here. I would like to now burn the normal Duemilanove bootloader configured to use an external 16MHz clock onto the chip. However, when I try following the normal procedure, it says "Invalid device signature". I can still upload programs to the chip and they will run, but I would like it to use the 16MHz external clock. How do I do this?

I have a sketch that will upload the Optiboot bootloader - that will work perfectly well on the Duemilanove.
The latest version will be available on GitHub.
This particular sketch is in the "Atmega_Board_Programmer" subdirectory.
You need to run this sketch on another Arduino (like a Uno) and connect it up like this:

As it turns out, I had the chip in backwards. It surprisingly still works.

No wonder you got invalid device signature! :)


text:
Arduino Leonardo runs unusually hot
I have a genuine (purchased from Adafruit) Arduino Leonardo that I have had for 2 years and I have not had any issues with. However, I have always noticed that it seems to be running suspiciously hot for a low power microcontroller, sometimes even too hot to comfortably touch. I measured the temperature today with an infrared thermometer at 121 degrees Fahrenheit (~49C). Based on observations by feeling the board, the 32U4 seems to be what is getting hot and everything else is cool to the touch. This happens when it is powered over USB as well as through the power jack. The chip gets hot even when nothing is connected to the I/O or power pins. The board is entirely working and does not appear visibly damaged. I am a bit worried about this as I may use this board in a project where it will be inside in enclosure and running for long periods of time. Any ideas why this is happening and if this normal?

Mine is getting hot as well. A genuine Leonardo too. I'm using Ethernet Shield and an RFM69HCW radio.

I think I solved mine, I was using 12v supply, I changed it to another one using 7v. It's normal now.

My Leonardo, which I leave on all the time, is not hot. The CPU chip feels at room temperature as far as I can tell. If you were powering something from it, maybe you are drawing too much current. If it gets hot just sitting there doing nothing, and with nothing connected, something is wrong.
Maybe you damaged it in the past? Maybe hooked up some LEDs without current-limiting resistors? If not, it sounds like a faulty device to me.


text:
How to use the timer to generate a pulse wave of the specified frequency and duty cycle
So we have the tone library, which produces a 50% duty cycle square wave of varying frequency, and analogWrite() which produces a fixed frequency wave of varying duty cycle. Is there any way to control frequency and duty cycle at the same time on an Atmega328-based board?

I don't know of any ready-made library for that, but you can always configure the timer yourself. Read the datasheet and use one of the so called “CTC” (Clear Timer on Compare Match) modes. Avoid using Timer 0 unless you don't care about loosing the Arduino timing functions (millis(), micros(), delay() and delayMicroseconds()).

Also, another related question: will using setPwmFrequency() disrupt the operation of micros() and delayMicroseconds()? The sample code at the arduino playground only says it will stop millis() and delay() from working.

If you change the Timer 0 prescaler with setPwmFrequency(), then yes, you will also disrupt micros() and delayMicroseconds(). But this gives you a limited choice between only a few frequencies. If you want a specific frequency, you should better configure the timer yourself, based on the datasheet.


text:
How to reset ATmega328P fuses using USBasp programmer?
I think I bricked two ATmega328Ps when I was trying to burn new bootloaders using Arduino Pro Mini, the USBasp programmer and the Extreme Burner AVR software. I had two ATMega328p with bad booloaders and I intended burn the correct bootloader to the chips.
First I connected the USBasp programmer to my Arduino Pro Mini equipped with an ATmega328P. I verified that communication was good as I could read and write to EEPROM. All was excellent.
I was using the following fuses:
LOW Fuse Byte=0x62
High Fuse Byte=0xD9
Extended=0xFF
Lock = 0xFF
Calibration = 0xFFFF FF8A
Then the following happened:
I killed the 1st chip when I only pressed button ERASE CHIP on the programmer.
I killed the 2nd chip when I wrote the following fuses to it:
LOW Fuse Byte=0xFF
High Fuse Byte=0xDA
Extended=0xFD
Lock Fuse = 0xCF
In both cases I had the following error message:
Cannot Communication with chip
Power On failed
avrdude output similar messages:
RC=-1. No answer...
(avrdude -c usbasp -p m328p -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m )
How can I solve this problem?
How can I reset all the fuses to factory default to make the chips respond again?

So you were running the atmega at 1Mhz? In that case you need to program the chip at a lower speed. You can do that in avrdude using avrdude -B10 ....

http://electronics.stackexchange.com/a/36553/8627

http://electronics.stackexchange.com/a/66724/8627

Beware at least some versions of some of these simple programmers don't support altering the programming speed; not sure if they will complain or silently ignore the option.

The USBASP has to have a jumper set to program in low-speed mode and some of the ones you can buy don't have the jumper header installed; some don't even have the pins hooked up at all.  Grab the USBASP schematic and see if your programmer has the pins connected and see if you can hack on a header so you can set the jumper (or maybe luck out and find that the header is already there).

Thank you very much! I generated clock by NE555 and it´s working! Many Thanks to you! The first useful guide. :)

Its possible you may have disabled the SPIEN or the RSTDISBL fuses. The only way to check and fix is to use a High Voltage Programmer like the STK500, STK600 or AVR Dragon and see. I have the AVR Dragon and it saved me a few times.
Also, do a search for AVR Fuse Doctor. Its a homemade fuse repair device. Pretty cool. But save yourself some time and invest in a programmer/debugger that has HVPP (high voltage parallel programming) and HVSP (high voltage serial programming). You won't regret it.

As someone mentioned, the first chip you may be able to fix by passing -B10 to avrdude.  In order to program an AVR, the programmer has to be running at a slower speed than the chip you're programming is running.  The fuses you have set cause the chip to run at 1Mhz using the internal clock, and -B10 will cause it to go slower (the defaults are suitable for programming a chip that is running faster than 4MHz).
The second chip, the fuses are set to 8MHz using an external crystal, so in order to fix it, you'll need to hook up an 8MHz crystal, or use a high voltage programmer.
Good luck!

Hi that happened to my Nano with atmega 328p using a usbasp programmer just checking the fuse settings to make a backup with out programming, the Extreme Burner AVR software caused the problem as it read the wrong device signature, it gave me 0x0f951e after disconnecting and trying my Nano 328p it would not work I do not use that software anymore and never had a problem with making backups with other software.


text:
'OUTPUT' was not declared in this scope - ATtiny85 with Arduino Uno r3 as ISP
I'm trying to follow this this tutorial to program an ATtiny85 micro-controller using my Arduino Uno r3 as the ISP.
I am up to the final step on the tutorial, but get an error when attempting to compile my sketch:
'OUTPUT' was not declared in this scope

I have tried multiple "Blink" scripts, but none have seemed to work.
My full error log:
Blink.ino:10:21: error: Arduino.h: No such file or directory
Blink.ino: In function 'void setup()':
Blink:15: error: 'OUTPUT' was not declared in this scope
Blink:15: error: 'pinMode' was not declared in this scope
Blink.ino: In function 'void loop()':
Blink:20: error: 'HIGH' was not declared in this scope
Blink:20: error: 'digitalWrite' was not declared in this scope
Blink:21: error: 'delay' was not declared in this scope
Blink:22: error: 'LOW' was not declared in this scope

I have also tried including Arduino.h, no help, and changing "OUTPUT" to "0x01", as it is defined to said value in Arduino.h, but instead got this error:
error: 'pinMode' was not declared in this scope

Any ideas as to what is happening?

If you change the board back to Arduino UNO does it compile? Could you turn on verbose mode for compilation and post the text that appears when you compile.

It looks like the Arduino core libraries aren't being included...

Are you using the latest version of the Arduino IDE? Seems similar to (this problem](http://forum.arduino.cc/index.php?topic=82220.0), but in reverse.

The first issue, the 'missing' .h file, creates the others. Fix the INCLUDE path and the other errors will go away.

Check this thread
http://arduino.stackexchange.com/questions/3642/output-was-not-declared-in-this-scope-attiny85-with-arduino-uno-r3-as-isp

The tutorial you are using refers to the Arduino IDE version 1.0, are you sure you are using the same IDE version?

Create an Arduino.h in ...\Arduino\hardware\attiny45_85\cores\attiny45_85 containing
#include <WProgram.h>

From here
https://electronics.stackexchange.com/questions/87328/arduino-as-isp-for-attiny

Try moving the "Cores" folder from the avi directory to the attiny director. The path was wrong for me and I was getting the same error. Had the same issue with the bootloader file. Moved it out of the avi folder as well and all worked ok then.


text:
Arduino OTA port not updating in Arduino IDE
The OTA (from the ArduinoOTA library) on my ESP8266 does not show up in the programming ports on the Arduino IDE unless I restart the IDE.   Even when I plug in a usb cable and the ports list updates to show that device, it does not show the network port without a restart.   Does anyone know why this would happen or how to solve it?
I downloaded the newest version of the IDE and this is still the case.

Is there any way to make the IDE actively check for a re-established mDns connection?

I have the same problem, ports appear on IDE restart and then except one (which also seems to be random) all disappear after some time.

I found an workaround for Windows:

disable IPv6 from Network Configuration
disable/enable network interface
restart Arduino IDE

You should see your OTA device in port list, in Arduino IDE.

Do you have to do these steps every time the OTA device turns on or does this cause the IDE to actively monitor for network OTA ports?

I just did it on the Windows machine with Arduine IDE. For example on Mac I don't have this problem.

I have the exact problem on various flavours of Linux with last Arduino IDE and rebooting the router seems to be the only thing I've found that can make the IP address port appear.

For some reason you have to close and reopen the Arduino IDE for it to discover all available OTA ports.   Not sure why this is -- if anyone knows I would be glad to learn.
EDIT: keeping this answer just for comments -- it's not a real answer.

Which version of Arduino IDE? Which Operating System? Mine eventually discovers a a device that is flashed with OTA support added - usually takes less than a minute

1.8.4 OSX -- is there maybe a refresh ports function somewhere in the IDE?

How long do you wait? Is there a later version of the ide available for Mac

I downloaded the most recent version of the IDE and this is still a problem.

I have this problem on Windows 10. I am running Arduino 1.8.5 but this problem has been on previous versions. From what I understand it is a Windows issue. But some people have what appears to be the same problem because it get assigned to IP6 rather than IP4. I'm not really familiar with the details.


text:
How to connect dual brushless motors to arduino
I'm planning on making a Force Feed Back racing wheel with arduino.Saw a lot of tutorials but it uses brushed DC motors ,couldn't find how to connect dual brushless motor for force feed back.
This the motor I want to use :
http://www.dx.com/p/chrgm25bl2418-dc-brushless-motor-with-built-in-drive-24v-12v-470930#.WkurLcvhVAg

.                       .

Your link points to a battery...

Sorry about the link

http://www.dx.com/p/chrgm25bl2418-dc-brushless-motor-with-built-in-drive-24v-12v-470930#.WkurLcvhVAg

I'm voting to close this question as off-topic because it is about haptic motion systems, not Arduino.  This can't be an Arduino question until you've clearly defined what you goal is and verified that you have selected the correct mechanical and driver parts - something that at present it appears you have not, if your goal is "force feedback"

I want to know if there is any motor controller that could be used to control these motors and could be connected to arduino

It looks like you provide the correct voltage to the VCC and GND pins to power it, and connect the CW/CCW and PWM (and GND of course) to your Arduino - the first to control the direction, and the second to a PWM pin to control the speed.
You can use the FG pin to monitor the speed from the internal hall effect sensor if you want.

Thanks,is there any motor controller for this..?

You probably won't get force feedback by this approach.

It looks like the controller is built in. A bit like a servo.

So I can connect it to arduino without a motor controller like you said.?

I repeat my previous comment.


text:
How to input text from Serial monitor into a character array?
I'm using a Mega 2560 and Uno and want to input text to the serial monitor which can be stored in character array char in[];
I want array specifically as I'll be breaking each character to trigger different code for making a morse code.
    #include<Arduino.h>
//#include<Softwareserial.h>

int Speaker1 = 4;
int Speaker2 = 6;
int LED = 2;
int Relay = 12;
char n = '0';
char in[];
//int outPins[] = { 2, 4, 6, 8 };

void high() {

  digitalWrite(Speaker1, HIGH);
  tone(Speaker2, 800);
  digitalWrite(LED, HIGH);
  digitalWrite(Relay, HIGH);

}

void low() {

  digitalWrite(Speaker1, LOW);
  tone(Speaker2, 800);
  digitalWrite(LED, LOW);
  digitalWrite(Relay, LOW);

}

void setup() {

  Serial.begin(9600);

  pinMode(Speaker1, OUTPUT);
  pinMode(Speaker2, OUTPUT);
  pinMode(LED, OUTPUT);
  pinMode(Relay, OUTPUT);

  Serial.print("Enter your desired text: ");
  //in = Serial.readString();  /*<-------------HELP NEEDED HERE */

  for (int i = 0; i < strlen(in); i++) {

    n = in[i];

    switch (n) {

      case 'A':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'B':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'C':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'D':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'E':
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'F':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'G':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'H':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'I':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'J':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'K':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'L':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'M':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'N':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'O':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'P':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'Q':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'R':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'S':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'T':
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'U':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'V':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'W':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'X':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'Y':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'Z':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case ' ':
        delay(700);
        break;
      case '1':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case '2':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case '3':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case '4':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case '5':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case '6':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case '7':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case '8':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case '9':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case '10':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;

    }

  }

}

void loop() {

}

Have you googled it? See https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Are you going to send each char at once or you will write a sentence and send?

@rvbarreto I will create a sentence and send.

@LookAlterno I did tried googling it, but the thing is I cannot quite find a way to insert text into character array with spaces. (In sentence format).
This isn't a homework, I was trying to build a code to translate input text into Morse pulses. Code is updated in question.

@LookAlterno Tried editing the question, maybe this would be a bit clear.

@EdgarBonet I don't think that link would help me here. Note - I updated with a code for my use case.

You wrote: “I don't think that link would help me”. Of course it won't help if you don't read it! But it does contains the solution to your problem.

@EdgarBonet Believe me I read it, the problem I'm seeing there is that reading needs void loop (), whereas my whole program lies in void setup and has for loop in it.
Next, I need the program to "wait" like it does in a C program if I say put code printf("Enter your text: \n);
scanf("%s", &in);
Here , the program will wait until I insert the string and then execute the rest of the code below because again, if you check above, I need to break the sentence to trigger individual Morse signal assigned. Please point out any miss info by me here, I'm still learning here.

forget the morse code task and try examples with serial input, understated them, modify a little, try if what you changed does what you expected.

Note: case '10' is not going to work, I even am surprised it compiles. You can only put one character within ' and '

@MichelKeijzers Well Damn I'm dumb.

@Juraj On it! Trying the link by Edgar Bonet RN.

Also, not a solution but to make your program (without making it more complicated) a lot easier: move the low(); and delay(300) at the end of each break statement UNDER the switch statement, this saves a lot of lines.

Another one: add the delay of 100 in low and delay of 300 in high. This saves you a lot of lines.

@MichelKeijzers
Oh, btw then I'll have to create two highs for dots and dashes and low for character space, character end, etc. Couldn't think of a efficient way for that.
Also note one of my case is ' ' i.e. space, so if I remove all the break, do I move the case ' ' to last and set the delay 400 which will make it 700 in total ? - The answer is yes, goddamnit I'm dumb

I will make an answer to show an even better way.

I suggested in a comment you read the blog post Reading Serial on the
Arduino. In this post, Majenko shows a readline()
function that does almost exactly what you want. This function is
non-blocking, which, in the embedded world, is most of the time a
mandatory feature. However, in one of your comments you wrote that you
want a blocking function:

I need the program to "wait" like [...] scanf

Degrading a non-blocking function into a blocking one is as easy as
wrapping the non-blocking function in a loop. Here is a code snippet for
reading a CR-terminated string, which is similar to a blocking version
of Majenko's readline():
char buffer[80];
size_t pos = 0;
for (;;) {
    int c = Serial.read();
    if (c == -1) continue;   // no input
    if (c == '\r') {         // end of line
        buffer[pos] = '\0';  // terminate the string
        break;
    }
    if (pos < sizeof buffer - 1) {
        buffer[pos++] = c;
    }
}

That being said, I could not resist the temptation to brutally simplify
your program. The key to the simplification is to consider the Morse
code as a data structure. Then, the code for keying a string is
generic: you look up each character in the code table and key it in
turn. This saves the long switch/case:
struct code_t {
    char c;
    const char *code;
};

static const code_t morse_code[] = {
    {'A', ".-"   }, {'B', "-..." }, {'C', "-.-." }, {'D', "-.."  },
    {'E', "."    }, {'F', "..-." }, {'G', "--."  }, {'H', "...." },
    {'I', ".."   }, {'J', ".---" }, {'K', "-.-"  }, {'L', ".-.." },
    {'M', "--"   }, {'N', "-."   }, {'O', "---"  }, {'P', ".--." },
    {'Q', "--.-" }, {'R', ".-."  }, {'S', "..."  }, {'T', "-"    },
    {'U', "..-"  }, {'V', "...-" }, {'W', ".--"  }, {'X', "-..-" },
    {'Y', "-.--" }, {'Z', "--.." },
    {'1', ".----"}, {'2', "..---"}, {'3', "...--"}, {'4', "....-"},
    {'5', "....."}, {'6', "-...."}, {'7', "--..."}, {'8', "---.."},
    {'9', "----."}, {'0', "-----"},
    {' ', " "    }, {'\0', NULL}  // sentinel
};

static inline void high() { digitalWrite(LED_BUILTIN, HIGH); }
static inline void low()  { digitalWrite(LED_BUILTIN, LOW);  }

// Key a string in Morse.
void key(const char *s)
{
    for (; *s; s++) {  // *s = current letter

        // Find this letter's code.
        const code_t *p;
        for (p = morse_code; p->c; p++) {
            if (p->c == toupper(*s)) break;  // found
        }
        if (!p->c) continue;  // not found -> ignore

        // Send this code's symbols.
        for (const char *code = p->code; *code; code++) {
            if (*code != ' ')
                high();
            switch (*code) {
                case ' ': delay(100); break;
                case '.': delay(100); break;
                case '-': delay(300); break;
            }
            low();
            delay(100);
        }
        delay(200);  // inter-letter spacing = 300 ms
    }
}

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

void loop()
{
    // Read a string.
    char buffer[80];
    size_t pos = 0;
    for (;;) {
        int c = Serial.read();
        if (c == -1) continue;   // no input
        if (c == '\r') {         // end of line
            buffer[pos] = '\0';  // terminate the string
            break;
        }
        if (pos < sizeof buffer - 1) {
            buffer[pos++] = c;
        }
    }

    // Key it in Morse.
    key(buffer);
}

Note that this program reads CR-terminated strings from the Serial port
and keys them on the builtin LED. If you want your program to work on a
single string, you can call exit() at the end of loop() or,
alternatively, merge loop() into setup() and provide an empty
loop().

Brilliant answer.

I don't understand exactly why your signals are much different from 'real' morse code, e.g. A is .-
Instead of calling each high and low separately like the 'a' for example:
  case 'A':
    high();
    delay(100);
    low();
    delay(100);
    high();
    delay(300);
    low();
    delay(300);
    break;

call it like this:
case 'A':
  send2(false, true); /* means .-
  break;

Than create a function send2 which sends a . and a -
Something like:
void send2(bool b1, bool b2)
{
   send(b1);
   send(b2);
   delay(300); /* Extra wait in between characters */
}

For characters needing 1, 3 or 4 characters, you can make send 1, send3 and send4 accordingly.
void send(bool b1)
{
   digitalWrite(Speaker1, b1 ? HIGH : LOW);
   tone(Speaker2, b1 ? 800);
   digitalWrite(LED, HIGH);
   digitalWrite(Relay, HIGH);
   delay(b1 ? 300 : 100); /* Assuming HIGH needs delay of 300 and low of 100 */
}

void low() {

  digitalWrite(Speaker1, LOW);
  tone(Speaker2, 800); /* I would expect two different values for HIGH and LOW */
  digitalWrite(LED  , b1 ? HIGH : LOW);
  digitalWrite(Relay, b1 ? HIGH : LOW);
}