text:
Why is my Arduino Nano's buzzer clicking?

EDIT: I'm so sorry but the clicking wasn't coming from the Arduino but from the piezo buzzer! I was wrong and I'm so sorry for misguiding you!
I recently bought an Arduino Nano so that I could downsize my arrangement with my Arduino Uno so I soldered everything together and when I plugged in the Nano I extra made sure that nothing was shorting each other out. But the buzzer attached to it kept making this clicking noise. Does anyone know why? Do I actually have a short-circuit?
Here is the code:

#define LED 1
#define twoLED 2
#define threeLED 4
#define fourLED 5
#define fiveLED 6
#define sixLED 7
#define sevenLED 8
#define eightLED 9
#define nineLED 10
#define tenLED 11

int state = 0;
int old = 0;
int buttonPoll = 0;

void setup() {
  pinMode (3,INPUT);
  pinMode (11,OUTPUT);
  pinMode(LED, OUTPUT);
  pinMode(twoLED, OUTPUT);
  pinMode(threeLED, OUTPUT);
  pinMode(fourLED, OUTPUT);
  pinMode(fiveLED, OUTPUT);
  pinMode(sixLED, OUTPUT);
  pinMode(sevenLED, OUTPUT);
  pinMode(eightLED, OUTPUT);
  pinMode(nineLED, OUTPUT);
  pinMode(tenLED, OUTPUT);

  digitalWrite(LED, LOW);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

}

void loop() {

while (state == old)
{
  buttonPoll = digitalRead (3);
  if (buttonPoll ==1)
  {
    delay (50);
    buttonPoll = digitalRead (3);
    if (buttonPoll == 0)
    {
      state = old + 1;
    }
  }
  else
  {
    delay(100);
  }

  switch (state)
  {
    case 1:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 2:
      digitalWrite(LED, HIGH);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 3:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

case 4:
      digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 5:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

case 6:

  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 7:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

case 8:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 9:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

case 10:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 11:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

    case 12:
        digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 13:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;
case 14:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 15:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

case 16:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 17:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

case 18:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 19:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, HIGH);

      tone (11,493.88);
      delay(150);

      tone(11, 523.25);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11,329.63);
      delay(150);

      tone(11, 261.63);
      delay(150);

      tone(11, 246.94);
      delay(150);

      tone (11,196.00);
      delay(150);

      tone(11, 246.94);
      delay(150);

      tone(11, 261.63);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11, 523.25);
      delay(150);

      tone (11,493.88);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11, 329.63);
      delay(150);

noTone(11);

old = state;
state = 0;
old = 0;

    break;

    default:
  digitalWrite(LED, LOW);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

    old = 0;

    break;
}

}

  }

Here is a video of the clicking:
https://drive.google.com/file/d/1TprL56p2YyJ3j8cq43U2LYzaWofZpJM7/view?usp=sharing

Uhh, I want to see this. =)  Maybe hear it also.

Not-so-good ceramic capacitors have been known to sing/click...  Does the NANO work or not work at this point?

How could I show it to you?

Well, I've tried it out and not much seemed to work

are you certain that the Nano is clicking? ... maybe the power supply is making the noise

I'm pretty sure it's the Arduino. I connected it to my computer and my computer has never made that sound before.

What's the nature of the clicking? Can you describe it as like a sound that might be familiar? Is it clicking at a steady continuous rate? Just once after power up? Since you soldered it yourself, I would at least check the soldering under a magnifier and check for solder bridges (shorts). You could take a close picture with your phone, making sure it's clear, and post it.

Please post a clear picture. It’s very hard to see if there’s a problem otherwise.

Here, I've uploaded a video of the clicking: https://drive.google.com/file/d/1TprL56p2YyJ3j8cq43U2LYzaWofZpJM7/view?usp=sharing

@Éemia, need to get a public link for it.

Oops, you're right, there, I've updated it.

The simpler piezos click when a voltage is applied, and again when it is removed. To make it buzz, it needs a pulse-train: many clicks makes a buzz. There are piezos that have that feature built-in, but I'm guessing yours hasn't. That's actually a Good Thing in disguise: it allows you to make tones by making pulse-trains at different frequencies. The easiest way to do that is to connect it to one of the PWM pins (5, 6, 9, 10, or 11) and use the tone() library-function (look it up if you need to). Of course, you can do it "manually", too, on any output pin, just by switching it HIGH and LOW at rates that you choose, but that will pretty much tie up your processor, at least for higher frequencies.
Update:

Just why wasn't it clicking when I connected it to the Arduino Uno?

I can't tell without seeing the two sketches but in your video, it sounds like it is being turned on or off, or pulsed, once per second.
Please add your code (both of them, if they're different) to your question. Wiring diagram(s) of the piezo connection to the Arduino boards would help, too.

Thanks so much for your information! Just why wasn't it clicking when I connected it to the Arduino Uno?

Okay, I've uploaded the code but how I wired the piezo buzzer is the simply that I connected the positive side to the digital pin (D13) and the negative side to ground, just like how you should do it according to research.

You've described wiring it to pin 13 but your calls to the tone() function address pin11. Is that an connection error or a typo? Pin 11 is indeed a PWM pin, and connecting the piezo to it should work correctly. If it really is connected to pin 13, I don't see a reason why it should click when running your program, but it might very well click during upload if your bootloader flashes the on-board LED - pin 13.

Oh right, I used pin 11 when I hooked everything up to the Arduino Uno but now I transferred everything to the Arduino Nano and I didn't modify the code. Still, I can't even upload the code to my Arduino Nano. It keeps saying that there is an error. Thanks for your comment!

Please add the error message to your question, and be sure both "Show verbose output" boxes in the IDE preferences are ticked when you run the compilation and upload.


text:
Arduino 33 Nano BLE Sense not compatible with pulseIn()?
Preface
Currently, I'm making an application on a Arduino 33 Nano BLE Sense. I'm trying to measure the current humidity and send it via BLE to another device. The target is to send a precise value with a high frequency, 8-10 values every second.
For measuring the humidity I connected an external sensor, the P14 Rapid Capacitive Humidity Sensor (it's faster and more accurate than the onboard humidity sensor) with a NE555 Timer IC in Monostable Mode.
To read the output pulse (frequency: ca. 500Hz) I'm using pulseIn().
I managed to calculate the humidity correctly and also the BLE data transfer worked.

Problem
My (minified) sketch:
#include <ArduinoBLE.h>

void setup() {
    // some setup, takes around 10s
}

void loop() {
    BLE.poll(); // polling for new events, takes ca. 10 µs

    value = pulseIn(6, HIGH); // read the high pulse, takes around 500-4000 µs

    // calculating the average value, takes < 1 µs

    if (/* this if is executed every 1 second for testing purposes, targeted is every 100ms*/) {
        // humidity is calculated, takes ca. 20 µs

        characteristic.writeValue(/* calculated value */); // takes ca. 50 µs
    }
}

When I merged the features, the problems began. I couldn't connect to the Arduino anymore.
When I try to connect to it (with nrf Connect App), this happens. When I manage to connect to it before it stops working, I will be disconnected with a GATT_CONN_TIMEOUT exception.

When the Arduino is powered on, the setup is called and it's connectable while the setup is running. When pulseIn() is called for the first time the BLE connection stops working. But the programm keeps on running.
I already tried calling pulseIn() only every 10s or only once, the BLE connection stops working.
And yes, commenting out the pulseIn() makes BLE work again.

Possible Solution
Next thing I would try is to delete the pulseIn() and use interrupts for measuring the time.
My question is if there is a better way to fix this issue?

Likely you can not mix these two libraries.  If you are so inclined I would dive into the source code for each library in an attempt to find the conflict.  You are probably looking for both libraries using the same resource such as a timer.  Setting up your own timer as stated in the question may be easier.  It may be a bit extreme, but if you understand the underlying (to an Arduino sketch) C++ language, you might also consider destroying & constructing the BLE library ever time you want to use it.

how do you know that it stops at pulseIn()? ... the code that you posted has no debug functions

@jsotola as said in the question the code i posted is very minified. I print the value I get from the ´pulseIn()` and when it's printed the connection stops.

so it does not stop at pulseIn() ... it stops a couple of program lines after

@jsotola sorry, I wasn't very clear about what stops. The programm keeps running normally and I see the prints the continue. But the BLE connection stops, as seen in screenshot the device stops "existing".

source: Stack Exchange

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

sort: votes


text:
sensor detection is too slow when another feature is added
Can anyone figure it out for me? I am new to arduino and 1sheeld, Completely beginner. In my project(Smart Cane For Blind) has currently two part. One is object’s distance detection by using ultrasonic sensor and another feature is Emergency feature. When the blind people lost his way he can press the push button to sent his location to his family member for help.
My problem is that when I integrate that two feature, The sensor part, the detection is too slow and weak.
#define CUSTOM_SETTINGS
#define INCLUDE_GPS_SHIELD
#define INCLUDE_SMS_SHIELD
#define INCLUDE_VIBRATION_SHIELD
#define INCLUDE_PUSH_BUTTON_SHIELD
#define INCLUDE_TERMINAL_SHIELD
#define INCLUDE_MIC_SHIELD

/* Include 1Sheeld library.*/
#include <OneSheeld.h>
#include <string.h>

// Define Pins for Sensor 1
#define trigPin1 4
#define echoPin1 5

//Define Pins for Sensor 2
#define trigPin2 6
#define echoPin2 7

// Define Pin for VibMotor 1
#define motorPin1 12

// Define Pin for VibMotor 2
#define motorPin2 13

/* Define a boolean flag. */
long duration, distance, UltraSensor, UltraSensorTwo;
boolean isMessageSent = false;
float lat;
float lon;
String Message;
String Message1;
String Message2;
char latitude[10];
char longitude[10];

void setup()
{
  /* Start communication.*/
  Serial.begin(9600);
  OneSheeld.begin();
//  PushButton.setOnButtonStatusChange(&Emergency);

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);

  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
}

void SonarSensor(int trigPin, int echoPin)
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
}

void SensorHandler() {

  SonarSensor(trigPin1, echoPin1);
  UltraSensor = distance;

  SonarSensor(trigPin2, echoPin2);
  UltraSensorTwo = distance;

  if (UltraSensor <= 60 && UltraSensor >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin1, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin1, LOW); // motor off
    delay(200);
  }
  else if(UltraSensor < 45 && UltraSensor >=30)
  {
    digitalWrite(motorPin1, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin1, LOW);
    delay(100);
  }
  else if(UltraSensor < 30)
  {
   digitalWrite(motorPin1, HIGH);
   delay(50);
   digitalWrite(motorPin1, LOW);
   delay(50);
  }
  else
  {
    digitalWrite(motorPin1, LOW);
  }

  Terminal.print("SensorOne: ");
  Terminal.println(UltraSensor);

    // For VibMotor Two

  if (UltraSensorTwo <= 60 && UltraSensorTwo >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin2, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin2, LOW); // motor off
    delay(200);
  }
  else if(UltraSensorTwo < 45 && UltraSensorTwo >=30)
  {
    digitalWrite(motorPin2, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin2, LOW);
    delay(100);
  }
  else if(UltraSensorTwo < 30)
  {
   digitalWrite(motorPin2, HIGH);
   delay(50);
   digitalWrite(motorPin2, LOW);
   delay(50);
  }
  else
  {
    digitalWrite(motorPin2, LOW);
  }

  Terminal.print("SensorTwo: ");
  Terminal.println(UltraSensorTwo);
}

void loop()
{
//    Terminal.println("Test");
//    Emergency();

    SensorHandler();
    //delay(10);
    if (PushButton.isPressed())
  {
    Terminal.println("Button Pressed");
    //delay(100);
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        Message1 = String(lat,8);
        Message2 = String(lon,8);

        Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
        Terminal.print("Message Sent");

//        SMS.send("0819033655",Message);
    delay(3000);
  }
  delay(1000);
}

The following code is after I fixed by learning BlinkWithoutDelay example but the vibration rate according to the distance seems not right. (When the object is closer, the vibration motor vibrate rate should be faster).
#define CUSTOM_SETTINGS
#define INCLUDE_GPS_SHIELD
#define INCLUDE_SMS_SHIELD
#define INCLUDE_VIBRATION_SHIELD
#define INCLUDE_PUSH_BUTTON_SHIELD
#define INCLUDE_TERMINAL_SHIELD
#define INCLUDE_MIC_SHIELD

/* Include 1Sheeld library.*/
#include <OneSheeld.h>
#include <string.h>

// Define Pins for Sensor 1
#define trigPin1 4
#define echoPin1 5

//Define Pins for Sensor 2
#define trigPin2 6
#define echoPin2 7

// Define Pin for VibMotor 1
#define motorPin1 12

// Define Pin for VibMotor 2
#define motorPin2 13

/* Define a boolean flag. */
long duration, distance, UltraSensor, UltraSensorTwo;
//boolean isMessageSent = false;
unsigned long previousMillis = 0;
unsigned long interval = 1000;
float lat;
float lon;
String Message;
String Message1;
String Message2;
char latitude[10];
char longitude[10];

void setup()
{
  /* Start communication.*/
  Serial.begin(9600);
  OneSheeld.begin();
  //  PushButton.setOnButtonStatusChange(&Emergency);

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);

  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
}

void SonarSensor(int trigPin, int echoPin)
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
}

void SensorHandler() {

  SonarSensor(trigPin1, echoPin1);
  UltraSensor = distance;

  SonarSensor(trigPin2, echoPin2);
  UltraSensorTwo = distance;

  if (UltraSensor <= 60 && UltraSensor >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin1, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin1, LOW); // motor off
    delay(200);
  }
  else if (UltraSensor < 45 && UltraSensor >= 30)
  {
    digitalWrite(motorPin1, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin1, LOW);
    delay(100);
  }
  else if (UltraSensor < 30)
  {
    digitalWrite(motorPin1, HIGH);
    delay(50);
    digitalWrite(motorPin1, LOW);
    delay(50);
  }
  else
  {
    digitalWrite(motorPin1, LOW);
  }

  Terminal.print("SensorOne: ");
  Terminal.println(UltraSensor);

  // For VibMotor Two

  if (UltraSensorTwo <= 60 && UltraSensorTwo >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin2, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin2, LOW); // motor off
    delay(200);
  }
  else if (UltraSensorTwo < 45 && UltraSensorTwo >= 30)
  {
    digitalWrite(motorPin2, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin2, LOW);
    delay(100);
  }
  else if (UltraSensorTwo < 30)
  {
    digitalWrite(motorPin2, HIGH);
    delay(50);
    digitalWrite(motorPin2, LOW);
    delay(50);
  }
  else
  {
    digitalWrite(motorPin2, LOW);
  }

  Terminal.print("SensorTwo: ");
  Terminal.println(UltraSensorTwo);
}

void loop()
{
  //    Terminal.println("Test");
  //    Emergency();
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval)
  {
    previousMillis = currentMillis;
    SensorHandler();
  }
  if (PushButton.isPressed())
  {
    Terminal.println("Button Pressed");
    lat = GPS.getLatitude();
    lon = GPS.getLongitude();
    Message1 = String(lat, 8);
    Message2 = String(lon, 8);

    Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
    Terminal.print("Message Sent");

    //SMS.send("0819033655",Message);
    //delay(3000);
  }
  //delay(1000);
}

study the example sketch called BlinkWithoutDelay .... it will give you information on how to remove the delay() functions from your code

@jsotola , Thanks sir. I will try to learn it now!

it seems a bit faster but the vibration rate according to the distance is not seems right. here's my code after I added. can you please check for me mr.@jsotola. I will edit in my question code.

You should replace ALL delays with non-blocking code like in BlinkWithoutDelay. This will only work good, if you ditch all the delays

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


text:
Arduino with Ultrasonic sensor integrated but vibration motor not working according to the code
Here's my code after editing the measurement had error. Now the ultrasonic measurement is working but the vibration motor is not vibrating.
#define trigPin1 8
#define echoPin1 7
#define motorPin1 13

long duration, distance, UltraSensor;

void setup()
{
  Serial.begin(9600); // to use the serial monitor.
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  //pinMode(motorPin1, OUTPUT);

}

void SonarSensor(int trigPin, int echoPin)
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  delay(100);
}

void loop()
{
  SonarSensor(trigPin1, echoPin1);
  UltraSensor = distance;
  Serial.print(distance); // print out the distance on Serial Monitor
  Serial.println("cm");
//
  if (distance <= 60 && distance >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin1, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin1, LOW); // motor off
    delay(200);
  }
  else if(distance < 45 && distance >=30)
  {
    digitalWrite(motorPin1, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin1, LOW);
    delay(100);
  }
  else if(distance < 30)
  {
   digitalWrite(motorPin1, HIGH);
   delay(50);
   digitalWrite(motorPin1, LOW);
   delay(50);
  }
  else
  {
    digitalWrite(motorPin1, LOW);
  }
}

Cut out everything from your sketch except the distance measuring. Forget the rest for now. Get the distance measuring working first.

And while you are at it, disconnect the motor and post a picture clearly showing how you have the ultrasonic sensor wired to the arduino.

After i cut out everything except the distance measuring part also not working. You can check below. Sorry for inconvenience

do not put updates into comments ... update the original question ... there is an edit button for doing that ... while you are at it, change the title of your question to Arduino not measuring distance correctly, because that is the problem, it is not a motor problem.

I already edited my code and now the measurement is working but the motor is not vibrating. Any help ?

I think you have to uncomment the line that defines the motor as an output device.
//pinMode(motorPin1, OUTPUT);

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


text:
Adafruit IO example won't compile, library required is correct version
I have Arduino IDE 1.8.5 installed, and also Adafruit IO Arduino 2.6.0 and Adafruit MQTT Library 0.20.0.
With the Adafruit IO lib comes a set of examples, and I wanted to use example adafruitio_07_digital_out as a starting point for a project on an Adafruit HUZZAH ESP8266.
It won't compile. I get
#error "This sketch requires Adafruit MQTT Library v0.17.0 or higher. Please install or upgrade using the Library Manager."

which I find strange. I've tried installing 0.17.0 instead of 0.20.0, but that doesn't help.
Is there anything I can do to get this to work? The suggested solution of using the Library Manager to install the required package is obviously not working.

can you double check and confirm that the library you have installed is actually installed and is higher than the required version?

@EngrAbbas I don't know how to check that other than using Sketch->Include Library->Manage Libraries and I've been through there many many times by now. Anywhere else I should look?

@gibson - On Stack Exchange sites such as this answers are not to be edited into questions.  Remove that and post it instead in the answer form below.

It turns out that the problem was that I had installed the Arduino IDE through the windows app store. Uninstalling it, downloading it through a browser, and using the same code works just fine.

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


text:
At dimming = 128, suddenly voltage goes up to 240 volt and then back to 0 volt
While using dimmer circuit with esp8266, at dimming = 128, suddenly voltage goes up to 240 volt and then back to 0 volt. at the output inductive load is connected like TABLE FAN , it has not any type of adapter, its AC line device.
where, the dimming range is 0-128 .
0=ON (no power clipping) means load should be ON.
128=OFF means load should be OFF.

Is this happens with dimmer circuit normally while load connected [TABLE FAN] or I am doing something wrong?
Also , can we use this value(128) for switching purpose? --means whenever we put the dimming=128 the load will be stay OFF,and power consumption stops towards load, as switch works.

i am newbie and trying esp8266 dimmer for first time.
here , the line voltage is 230-240 volts AC, 50Hz power supply .
I am referring this circuit as it is and code also, only the change is dimming value taken using serial communication
here i am using inductive load (TABLE FAN).

`
  const int interruptPin = 14;
int AC_LOAD = 4;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
{
  Serial.begin(115200);
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx)

  int dimtime = (75 * dimming);  // For 60Hz =>65
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay
  // (for 60Hz use 8.33) Some Triacs need a longer period
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {

   dimming = Serial.read(); // dimming value is taken from serial for
                               dimming the load

}`

is it a 240 V fan or it has a AC/DC adapter working from 60 to 240 V?

It is 240 v ac fan has not any adaptor

int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

The code comments explicitly tell you that the range is 0-128; while non-trivial to do safely, digging out a scope to understand what exactly happens on overflow could be interesting (for example, it may skip alternate half cycles), but the obvious solution is to never command values outside that range, and clamp any out-of-range values which might be requested over the serial port to the limits.
Given that the timing is done unreliably in software, the precise phase behavior of your zero cross detector may be different than the original author's and the line frequency and pulse width constants may or may not be correct for your location, it's not really surprising that you are seeing 128 fall outside the limit of proper behavior rather than just within it.  Likely you want to be conservative in what you allow.
To avoid inconcistency, even better than clamping the maximum value, you may simply want to treat everything above a chosen delay limit as an absolute "off" by simply finishing the ISR immediately without firing the triac at all.  This may prove a lot simpler than trying to reliably find a delay limit that is "almost entirely" off without sometimes slipping over to firing right at the start of the next half cycle - and who really uses the "barely even on" range anyway?
Technically, depending on what the actual memory access width and alignment rules of the ESP8266 are, the sharing of a potentially non-atomic variable between the main and interrupt contexts could cause a one time glitch when it is changed (though even that is unlikely for your expected range of values, especially if you do the limiting before assignment to the shared variable). However, the atomicity concern can be simply remedied by using a volatile unsigned char (or more portably including stdint.h and using a volatile uint8_t) as the shared variable. The volatile keyword is used to require that the compiler actually calculate a variable that may not appear to be used, and actually store it in memory rather than merely cache it in a register.
It's worth noting that the software timed dimming, while somewhat portable is not particularly reliable, and may at high degrees of delay mean the processor spends almost all of its time in the ISR.  For this reason it is generally better to use a hardware timer for this purpose, however that then becomes more chip-specific.  If you are hoping to have things life WiFi running on your ESP8266 at the same time, you'll almost certainly want to move to a hardware timer to avoid glitching.
Ultimately it seems that the tutorial your are following is a poor one, such that doing a complete from-scratch reimplementation would be wise.  Additionally, mains-powered dimming circuits present many safety and reliability concerns even when driving a lightbulb - and it is by no means clear that your triac and snubber circuit are safe to use with an inductive load.  This is a challenging project, and not necessarily an appropriate one to attempt without deep experience.  You might want to consider using a DC fan PWM-controlled from a well-engineered low-voltage power supply instead.

Untrue.  8-bit variables with a single writer as suggested here are atomic almost everywhere, including on ATmegas.  There are no linked variables here - the topic is already complex enough without getting sidetracked into situations that do not occur in it.

Again, there is nothing specific to a given MCU here.  The poster got into their predicament by following a poorly written tutorial; getting out of it will require real thought to apply the explanations here.  This is not a project which can safely be approached by beginners - so the last thing it needs is untested code for someone to copy and paste to other situations where they do not understand that it does not apply.


text:
Stable frequency generation
I'm trying to work out the best way to generate a stable frequency with my Uno R3
I'm using interrupts to generate an approximately 40KHz frequency which drives some ICs/MOSFETs to effectively generate 40KHz AC which powers a transducer.
I need to receive the frequency at a second transducer and calculate any frequency shifts.

The problem is that the generated frequency drifts a little bit off of 40KHz. Is there a way to lock it in at 40KHz via software? I'm receiving approximately 40KHz output (as measured using PicoScope software) with this code:
#define LEDPIN 13
void setup()
{
pinMode(LEDPIN, OUTPUT);
// initialize Timer1
cli();          // disable global interrupts
TCCR1A = 0;     // set entire TCCR1A register to 0
TCCR1B = 0;     // same for TCCR1B
// set compare match register to desired timer count:
OCR1A = 24;
// turn on CTC mode:
TCCR1B |= (1 << WGM12);
// Set CS11 for 8-bit prescaler:
TCCR1B |= (1 << CS11);
// enable timer compare interrupt:
TIMSK1 |= (1 << OCIE1A);
// enable global interrupts:
sei();
}

void loop()
{
// main program
}

 ISR(TIMER1_COMPA_vect)
{
digitalWrite(LEDPIN, !digitalRead(LEDPIN));
}

If there isn't a way to lock it in, is there atleast a way for the Uno to accurately display/store the frequency of the signal it generated at a given time?
Or is this not plausible because the Uno would "think" it is generating 40KHz?

Thanks for  any hints or suggestions.
EDIT: @RussellMcMahon pointed me in the right direction for this, so I accepted his answer. However, I wanted to share my final code and my misconceptions I encountered. Hopefully this will assist someone else in the future. I'm obviously by no means an expert, and I will try to not give any misleading information here.
My original goal was, although poorly stated, to generate as clean a 40KHz PWM with 50% duty cycle as possible.
Problems with my original code above were:

Using an 8-bit pre-scaler
Using an interrupt
Using digitalWrite()

8-Bit Pre-Scaler
      The problem here was that the counter only ticked over once every 8 clock cycles. 16MHz clock / 8 (pre-scaler) = 2MHz clock When I asked one of my professors about this he stated something along the lines of "a cycle could be missed due to an interrupt, and would cause it to wait 7 more cycles to 'tick'". Indeed I was originally using interrupts, and when we did the calculations it seemed like it could plausibly cause up to a a 1KHz swing at 40KHz.
      To rectify this I took out the pre-scaler, and ran straight at the base clock speed to increase resolution.
Using an interrupt
      Essentially the interrupt could cause clock cycles to not be counted, further complicated by using an 8-bit pre-scaler. If one clock cycle was missed, with a 2MHz clock (after pre-scale), you add 5E-7 seconds to the counter, changing the output frequency.
Using digitalWrite()
      The digitalWrite function is pretty slow. I'm not a guru, but I read this in multiple places and there seems to be a good comparison of methods here: Digital Pin Oscillation To get around this problem it had been suggested I toggle a single bit, which is what I set out to do in my final code. (It is worth noting, now that I've completed this project, that the previous link also makes reference to a library addition for faster digitalWrite/Read/etc....)

I went through a few variations and scrounged code from all over, and made a couple working examples but they didn't do it the way I wished. I believe part of the project I based this version off of was a melding between a previous version I had working and a class example I found online.
Without further ado, I present the code that took me an embarrassing amount of time to write from numerous sources... I really should tinker with this stuff more often:
#include <avr/io.h>
#include <avr/interrupt.h>
void setup()
{
//Disable interrupts
cli();
// Clear Timer1 registers
TCCR1A = 0;
TCCR1B = 0;
// Set OCR1A (TOP): 16MHz/40KHz /2 = 200 steps.
// Divide 200 by 2 = 100 because waveforms are centered around OCR1A (because toggle)
OCR1A = 100;
// Configure Timer/Counter 1
// Select P & F Correct PWM Mode, and OCR1A as TOP. Use WGM Bits 10 and 13.
// WGM Bits are in TCCR1A and TCCR1B. Any previous settings are cleared.

// Enable COM1A0 to toggle OC1A on compare match
TCCR1A = _BV(WGM10) | _BV(COM1A0);
// CS10 to enable base clock without pre-scale
TCCR1B = _BV(WGM13) | _BV(CS10);

//Set OC1A (Digital Pin 9 / Port B Pin 1) to output
DDRB |= _BV(1);
}

void loop()
{
}

 For reference, here is the clock frequency formula. In this instance, I had to divide the result by 2 again since I am toggling.

Resultant output verified by PicoScope:

In closing, you will notice that it isn't exactly 40KHz. Research turned up that the Arduino Uno makes use of a less accurate ceramic resonator to clock the ATMEGA328P (although a 16MHz crystal oscillator is onboard to clock the USB). To further increase accuracy in a generated signal will require the Arduino to be driven with an external clock source.

Have you tried using PWM outputs? Their frequency can be changed, see http://playground.arduino.cc/Code/PwmFrequency.

Presumably processor is crystal controlled? | Cannot the timer control a pin directly without interrupts? - or is that what is happening here ? (glancing through the code it's not obvious (to me) how it completes the function you are implementing.) If this is counter timer mode why are interupts requiired - does not the pin get happily toggled by the timer without invoking an interrupt. If so, an IRQ may add variable latency to the task.

@DaveP, I don't believe I can scale the frequency down to what I need. With the digitalWrite I'm using, basically it creates a PWM from scratch.

@RussellMcMahon I missed a snippet of code when I pasted it originally - please see the updated code. I thought about just running the toggle method through a loop, but wouldn't that potentially tie up the Arduino from doing anything else? Although, if I can rely on it to generate an accurate signal I suppose I wouldn't need the Arduino to do anything else.

You can't have the arduino measure the timer1 generated signal. The clock for timer one is the same as that of the processor, so it will always tell it's right on the money. You'd have to tune it using some external measurement. By the way, I don't get why you aren't using the option of having timer1 toggle the pin, unless there is a need to use pin 13 instead of 9 or 10.

This is using Waveform Generation Mode 9 (0b1001), phase and frequency correct, which gives you a 50% duty cycle by toggling on matching OCR1A while it counts up to OCR1A and then back down.  If you need to adjust the duty cycle away from 50%, you could use you could use the OCR1B compare register to control the OC1B output pin, or you could use WGM mode 8 to set the TOP with ICR1 and control the duty cycle on OC1A with OCR1A.     You could also get to twice the maximum frequency by using the count-up-only fast PWM schemes with WGM modes 14 or 15 (0b1110 or 0b1111).

Sorry for asking but i cant see the ISR function of TIMER1 you used at your last code. I only read the setup of timer and port for digital pin 9.

You can use a timer/counter to output a square wave signal of your choosing without processor intervention or use of interrupts.
In data sheet
"ATmega48A/PA/88A/PA/168A/PA/328/P"Atmel-8271I-AVR- ATmega-Datasheet_10/2014
page 142  it says

The double buffered Output Compare Register (OCR2A and OCR2B) are compared with the Timer/Counter value at all times. The result of the compare can be used by the Waveform Generator to generate a PWM or variable frequency output on the Output Compare pins (OC2A and OC2B). See ”Output Compare Unit” on page 143 for details. The compare match event will also set the Compare Flag (OCF2A or OCF2B) which can be used to generate an Output Compare interrupt request.

The interrupt CAN be generated and used but is optional.
It looks like relevant material extends as far as page 159.

Thanks Russell, I've been struggling with this and that seems to be the right direction to head. I've been reading over the documentation and I think I about have it ironed out.

PWM is the solution.
Russel's answer is proper. My contribution here is a simplification and to relay my observations. I made a QA about PWM recently and can affirm that "bit banging" and interrupts are not going to be stable. I observed digital writes to be roughly 1 microsecond, so toggling a pin is 2 µsec. This did not affect my project, so no further tests performed about the digitalWrite() function. Writing changes to the port macro as a whole is much faster than using digitalWrite(), however this still will not have the inherent stability setting up the PWM and its output pin will provide. Anecdotally, analogRead() is roughly 100 µsec.
I set up my timer with a prescaler and then applied a count to OCRxA. Via my prescaler and WGM bits, it turns out that the OCR registers were 1:1 for microseconds. OCRxB perfectly set the pulse width I was seeking.
Observing the period on an o'scope, it might have been off from the exact integer in OCRxA but did not drift. The error I observed was in the tens of microseconds and the values in OCRxB were between 6300 and 63000. Code examples are in aforementioned link to my QA. From researching my own solution, I learned this error is likely within tolerance of the crystal providing CPU freq.

I know this thread may be dead but if it happens to somebody, the aformentioned method works perfectly fine. You just need to disable timer0 (power_timer0_disable();) and then your 40kHz signal will not fluctuate (in frequency).
In any case, yeah try to avoid digitalWrite if you want speed.


text:
How to protect my arduino, while hotplugging its power supply and other related electronics
The unsolved: when I connect power and signal lines to my Arduino - while power is on - I potentially kill it. I have fried 2 so far.
Situation:

I have build an DMX-controlled lighting fixture, which consists of the fixture and a Controller Box.
The fixture houses 2 Arduino's (5V), 2 steppers, 2 drives (36V), 2 fans (24V) and some temperature sensors.
The controller box houses 1 Arduino, amongst other electronics.

The controller box receives DMX and does calculations an send controls via I2C to the fixture.
There is a 8 pole connector between fixture and controller box.
1 - GND
2 - 5v
3 - 24v
4 - 36v
5 - CLK (i2c)
6 - SDA (i2c)
7 - signal line (used as charge pump)
8 - reset

All wires are shielded(but the shield is only connected AFTER the initial pins make contact)
When the power on the controller box is ON and i connect the light Fixture with the 8-pole connector my arduino goes to heaven.
My own idea's so far:

Voltage spike, because the connection wires is grounded after it connects the pins.
Some strange flyback? via the Arduinos in the light fixture? I connected everything straight to the 5v pins, not using the regulator.
no idea

Any help on a way to search for the most likely cause of the problem would be greatly appreciated.

This apparatus may well have dangerous design defects to begin with which would desperately need correcting, but even if not you should not try to hotplug it.  Think about what would happen if the 5v and 36v lines were connected but the ground was not yet - while the grounds of the 36v and 5v systems are presumably connected together on the remote side.  It seems like you could easily end up with 31v across the series combination of the 36v load and the Arduino... backwards.

Hmm, i dont understand fully. But would it mean that the 36V uses the 5v as a gnd? somehow and thus it puts 31V on the 5v side? That would really hurt the feelings of the arduino.

Yes - current will flow through whatever path exists.  Consider if that 36v gizmo has a big capacitor across the supply input.  Discharged, it will initially look almost like a dead short.  So pretty much the entire difference between the 36v and 5v rails briefly shows up across the Arduino components - and backwards at that.

Thanks Chris, Yes that gizmo has a big capacitor so this makes sense and is indeed a major design flaw. Hmm so 2 things to do. 1 find a connector that grounds first. 2. use SSR or relay to switch on the 36v powerdrive, only after i have a proper I2C connection made.

Also consider a Ruggedino as a 2nd tier kind of protection. While it's possible it would survive, I'd suggest making the design improvements first. http://www.ruggedcircuits.com/microcontroller-boards/ruggeduino-se-special-edition

If you ever drive an I/O more than a diode drop above or below its power supply rails, the internal ESD protection structure will begin to conduct.  The internal structure is only there to keep the part alive during normal handling, i.e. in a factory but not for the situation described above.  If the current in this structure is allowed to go high enough, it looks like an SCR and "Latches" up.  When latch up occurs the device, like an SCR, will keep conducting as much current as the power supply rails are capable of until the current is removed and usually results in device destruction.  The way around this is to limit the current that may flow into a pin, and prevent current from forward biasing the ESD structure:  http://www.tayloredge.com/reference/Electronics/EMIESD/InputProtection.pdf

There's usually a number of scenarios that can cause hardware to go poof when you plug it in to a live system.  Most of them you have managed to identify, so I won't go into detail here.
Suffice it to say that creating hot-pluggable devices isn't as straight forward as you would at first guess.
There are two main critical things to consider when designing your system:

Suppression

Invest in TVS diodes to suppress ESD.  All the IO pins that connect to the outside world that will be liable to be disconnected or connected at any time should be protected by adequate suppression.  Any inputs should also ideally be tied to a default state with pullup or pulldown resistors so they aren't left floating.

Connector

The connector itself is pretty critical.  Hot-plug connectors typically have different pins of different lengths so that they connect in a specific pre-determined order.  Normally you want your ground and shield to connect first.  Then your power supplies, and finally your IO pins.  Doing it in any other order is asking for trouble - such things as back-powering through the IO pins if the supply hasn't been connected.
If you can't use a proper hot-plug connector then there are ways you can simulate it internally.  You can add hardware (buffers, reed relays, FETs, whatever, depending on your signals) which normally isolate the signals from the MCU, and only when the MCU is powered up and ready does it then activate the buffers to allow the signals through.  Of course, the buffers themselves have to be able to withstand any possible back-powering etc while the plug is being inserted.
One other small trick is to ensure that all your IO lines have a series resistor in them.  This limits the maximum current that can ever go in or out of a pin (at a specific voltage of course) to a level that is safe for the hardware.  470Ω - 1KΩ are good values.

that makes a lot of sense to have a connector with different pin lengts to connect to ground first. I'm going to try and source that. Would those TVS diodes influance the fast i2c signals? The idea was nto to make a Hotswapable device, its just that the poroject got out of hand and it needs to go on tour for 1 or 2 years and i'm sure this will happen....

TVS diodes shouldn't affect the signals, no.  They only come into effect when you get out-of-range voltages.  For more info on hot swap connectors you can read wikipedia: http://en.wikipedia.org/wiki/Hot_swapping

Thank you Majenko, you gave me new leads to research. thats great help, thank you.


text:
Arduino UNO capacitive sensor not working
This is a visualization of my Arduino connections:

I wish to read the data using the Capacitive sensor Library. iv'e tried the following code but variables total1, total2, total3 always have the value 0 and i don't know what is wrong.
My code:
// Import the CapacitiveSensor Library.
#include <CapacitiveSensor.h>

// Name the pin as led.
#define speaker 11

// Set the Send Pin & Receive Pin.
CapacitiveSensor   cs_2_3 = CapacitiveSensor(2,3);        // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4);        // 10M resistor between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_5 = CapacitiveSensor(2,5);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_6 = CapacitiveSensor(2,6);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_7 = CapacitiveSensor(2,7);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_8 = CapacitiveSensor(2,8);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_9 = CapacitiveSensor(2,9);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil

void setup()
{
  cs_2_3.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example

  // Arduino start communicate with computer.
  Serial.begin(9600);
}

void loop()
{
  // Set a timer.
  long start = millis();

  // Set the sensitivity of the sensors.
  long total1 =  cs_2_3.capacitiveSensor(60);
  long total2 =  cs_2_4.capacitiveSensor(60);
  long total3 =  cs_2_5.capacitiveSensor(60);
 /* long total4 =  cs_2_6.capacitiveSensor(60);
  long total5 =  cs_2_7.capacitiveSensor(60);
  long total6 =  cs_2_8.capacitiveSensor(60);
  long total7 =  cs_2_9.capacitiveSensor(60);*/

  Serial.print(millis() - start);        // check on performance in milliseconds
  Serial.print("\t");                    // tab character for debug windown spacing

  Serial.print(total1);                  // print sensor output 1
  Serial.print("\t");                    // Leave some space before print the next output
  Serial.print(total2);                  // print sensor output 2
  Serial.print("\t");                    // Leave some space before print the next output
  Serial.print(total3);                  // print sensor output 3
  Serial.print("\t");                    // Leave some space before print the next output
  Serial.print("\n");
}

What is the performance(i.e., how much time does it take to complete the procedure)?

i just wnna know if you got this code to run? i wanna try this project out. :)

Yes I run this, I only change board.

As found on the Capacitative Sensor Library page (emphasis added):

Use a 1 megohm resistor (or less maybe) for absolute touch to activate.
With a 10 megohm resistor the sensor will start to respond 4-6 inches away.
With a 40 megohm resistor the sensor will start to respond 12-24 inches away (dependent on the foil size). Common resistor sizes usually end at 10 megohm so you may have to solder four 10 megohm resistors end to end.
One tradeoff with larger resistors is that the sensor's increased sensitivity means that it is slower. Also if the sensor is exposed metal, it is possible that the send pin will never be able to force a change in the receive (sensor) pin, and the sensor will timeout.
Also experiment with small capacitors (100 pF - .01 uF) to ground, on the sense pin. They improve stability of the sensor.

The two emboldened points suggest that for a touch-piano, it would likely be advantageous to use a lower value resistor such as 1MΩ. Because the sensitivity increases as the resistor value increases, you want to use the lowest possible resistor value to reduce jitter & interference among your signal wires.

Also, later on the page:

The grounding of the Arduino board is very important in capacitive sensing. The board needs to have some connection to ground, even if this is not a low-impedance path such as a wire attached to a water pipe.

Ensure the Arduino is not run from a battery or unplugged laptop. For capacitative sensing to work, a stable ground connection is needed (via a DC plugpack or USB wall-wart is fine).
As a general note, try testing with only one capacitative connection first, then when that works, re-add the others.


text:
What could cause interrupts from MCP23017 suddenly stop working?
I have 4 rotary encoders connected to an MCP23017 which in turn is connected to interrupt port 0 on the arduino (and to I2C of course). Everything works fine: I get interrupts for all 4 rotary encoders, can read the values for them and even store these values in the EEPROM and load them in setup.

Now, I connect a WS2812 LED to the arduino (with a resistor and a capacitator in front of it). I connect the UNO and the led lights up. I attach the serial console (resetting the UNO) and it stops working (LED does not light up). This could just be simple wiring mistake and is not my real problem.
I remove the LED (and the capacitor) from the board and start everything up again. I can see via the serial console that the UNO works, however it does not receive any interrupts anymore. I exchange the MCP23017 thinking I fried it somehow but that doesn't change anything either...
Is there some sort of state the UNO has I could have affected?
Or could I have fried the interrupt "sub-system" on the UNO (again: all the other stuff still works)?
EDIT: The code is here: https://github.com/qollin/Liting/blob/master/src/Liting.cpp

You need to set the CONFIGURATION REGISTER (ADDR 0x05) to control how INTA and INTB react.

I wonder if the LED is a red herring and you just have some iffy code that is being picky about when it works. Could you post your code?

Just added a link to the main file (it uses quite a lot of libraries, though)...

I think I figured out whats wrong: you need to reset the interrupt handling of the MCP in setup() (by reading from both INT pins). Otherwise the MCP may start in a state where it does not generate new interrupts, because it waits for the old ones to be handled...

@qollin please post your solution as an answer so others can find it more easily.

I think I figured out whats wrong: you need to reset the interrupt handling of the MCP in setup() (by reading from both INT pins). Otherwise the MCP may start in a state where it does not generate new interrupts, because it waits for the old ones to be handled...

I'd just tie nRESET of the MCP' to the nRESET of the Arduino, but your call.


text:
Problems running Arduino project off a 9V battery
I have been working on an Arduin Uno Rev2 project for a while now. I have been developing using my MacBook, downloading code through the USB jack running it, monitoring the serial output on my MacBook, etc.
The Arduino is being powered from my MacBook through the USB jack which is also carrying the serial output back to the MacBook.
But now I want to make this project portable. IE: instead of powering it off a wire from my Macbook, I want to power it off a battery. So I followed these instructions #4 and connected up a 9V battery to the VIN pin.
At first it seemed to work. But very soon started noticing great instability. There are many serious problems I need to solve working off this battery:

As soon as I connect up the battery, I loose the Serial Monitor connection (even though the USB cable is still connected). So I can no longer see what's going on inside the Arduino for debugging purposes. Why? How can I continue to see the Serial Monitor? Is there a way to see the serial output from somewhere other than the USB jack?
I can tell by the lights on the board and by the behavior of the outputs that the software is malfunctioning. But I can't tell exactly why (because of #1). Why would changing the power source cause this?
I know that the VIN pin needs 7-12 volts. The battery I plugged in is a new 9V battery. But what happens as it wears down? Does it still push 9 volts? Or does the voltage drop? Can I tell my Arduino to stop functioning if the voltage drops below acceptable levels? Because ceasing altogether is better than malfunctioning.
I have read that I need to ensure that the current from the battery remains around 500mA. But how can I measure that in hardware/software? This ties back into question #3.

the Uno WiFi Rev 2 has too high current draw for a 9 V battery and it will empty any battery very  fast. I would try an USB power bank maybe.

A 9v battery is useless. Use a better battery.

@Majenko what battery should I use? A bank of 6 AA 1.5 V batteries?

Use a USB power bank.

I want to power it off disposable, non-rechargable batteries that can be purchased at regular groceries stores. So I think that rules out USB power-banks.

Than make sure to buy large quntities of batteries and change often - vote to close

Why vote to close when nobody has answered questions #1, #3 or #4?

Q3 ("Or does the voltage drop?" Yes it does; and it does it even when the battery is new. All batteries have some internal resistance, so the more current you draw, the lower the battery voltage. 9v batteries are especially poor in this respect - they really are meant for very low current / long run-time devices like smoke detectors and do a very poor job of supplying larger currents. You'll do much better with 6 Alkaline cells. Choose the size battery that gives enough run-time between replacements.

As soon as I connect up the battery, I loose the Serial Monitor connection (even though the USB cable is still connected). So I can no longer see what's going on inside the Arduino for debugging purposes. Why? How can I continue to see the Serial Monitor? Is there a way to see the serial output from somewhere other than the USB jack?

Probably because although the voltage is high enough to cut off the power from the USB port it's not got enough current to run the main MCU properly.

I can tell by the lights on the board and by the behavior of the outputs that the software is malfunctioning. But I can't tell exactly why (because of #1). Why would changing the power source cause this?

Because 9V batteries can't provide enough current.

I know that the VIN pin needs 7-12 volts. The battery I plugged in is a new 9V battery. But what happens as it wears down? Does it still push 9 volts? Or does the voltage drop? Can I tell my Arduino to stop functioning if the voltage drops below acceptable levels? Because ceasing altogether is better than malfunctioning.

No. The voltage drops rapidly to about 8V then down and down and down until it's below what the regulator can regulate. You can see this curve in any battery datasheet.

I have read that I need to ensure that the current from the battery remains around 500mA. But how can I measure that in hardware/software? This ties back into question #3.

That's nonsense. The current demands will be whatever the circuit needs at any moment in time. There will be an upper limit to that demand (defined by your circuit and what you are doing at any one time - the peak current draw) and your power source has to be able to provide at least that amount of current.  If you try to draw more current than the battery can handle then the output voltage will drop to a level where it can no longer power the circuit properly. It is at this point you get "brownouts" and the board resets randomly and strange unpredictable things happen.
In short: never use a 9V battery for an Arduino project. It's fine for vert low power operations, which take careful design, but for general use stay away from them. Also the Arduino's built-in regulator is a very inefficient and will waste about 25%-40% of a 9V batteries power before you even begin. Instead you should use a more efficient switching regulator to provide 5V directly to the 5V pin (or USB port) from suitable higher capacity batteries (such as AA cells).

As a comparison here's some typical battery discharge graphs comparing alkeline AA to PP3 (9V). These are both Duracell Ultra.

As you can see the PP3 drops its voltage very rapidly even under a light load. Under a "heavy" load (what would be considered a very light load to an AA) it tumbles away to next to nothing in no time at all.

Thank you for this explanation. I'm a software guy.
New to the world of hardware engineering and electricity.

@SaqibAli Then to give you a context you will understand: Device datasheets are the API of the hardware world. When programming you need to know the API. With electronics you have to understand the power and timing. Reading the datasheet is just the same as reading a library's API document.

If I get this working with AA batteries, then how can I get the serial output while running on battery power?

It should "just work".

When I get this working with AA batteries, can I get the Arduino to simply shutdown if the voltage is too low rather than have brown-outs, malfunctions and other unpredictable behavior?

If you build a circuit to do that, sure. It's not something the Arduino can do alone - the Arduino has no concept of "shut down" other than holding RESET low, which has to be done externally.

Actually I thought, that brown out detection is meant to hold the Arduino in reset, until it has sufficient voltage, to prevent it from malfunctioning. Then you would just need to configure it correctly


text:
Can I get around extremely long time to setup WIFI connection WPA2 Personal?
I'm using the Arduino Wifi Nina Library to connect an Arduino Uno Wifi Rev2 to wifi and then using the Arduino HTTP Client library to make HTTP post calls to the internet.
To connect the Arduino to my home Wifi Network (WPA2 Personal), I use the WiFi.begin() method. This method takes an excruciatingly long 4 seconds to connect to the Wifi. This seems to be a known issue. Since this methods is synchronous/blocking, my sketch is completely unresponsive during this time to any user input such as button-presses etc. I'm trying to create a proof-of-concept for a commercial-grade product. So having it go unresponsive to user-input for several seconds is unacceptable.
Is there any workaround to this? Is there a asynchronous library to achieve the same goal? Is there some other workaround? How do other people deal with this situation?

wow! four seconds is an excruciatingly long time? ... i think that maybe the problem that needs correcting is not with the arduino ... spend the four seconds looking out the window or at your better half

use WiFi.setTimeout()

I don't think WiFi.begin takes four seconds, does it? Sounds to me like you have a loop that is waiting around for WiFi.status==WL_CONNECTED which is taking four seconds. I just tested on my NodeMCU and WiFi.begin() typically completes in just 5 milliseconds.

@S.Imp, yes 5 ms because it is already connected as 'persistent connection'

@Juraj My WiFiInit function calls WiFi.persistent(false) as its first operation. WiFi.begin only takes about 5ms pretty much every single time I call it (on a NodeMCU) and returns WF_DISCONNECTED if the wifi is not connected. You should poll periodically to see if it has connected before attempting to use it. In any case, it will take about 4 seconds before it finally connects, but at least begin doesn't block the whole time.

@S.Imp, but that is on the esp8266 or esp32, not on the Uno WiFi Rev.2 with WiFiNINA library.

4 even 5 seconds is normal for connecting to WiFi. How long takes your phone or other devices to connect?
You can connect a little faster with static IP address.
EDIT: With WiFiNINA library for Uno WiFi Rev.2, you can change the connection timeout with WiFi.setTimeout(). The default is 5 seconds. WiFi.begin() can end with WL_CONNECT_FAILED but if you later check the status of the connection it will eventually be connected.

With esp8266 or esp32 you can make the connection persistent and it is build up immediately after boot and asynchronously. WiFiNINA library doesn't make this possible yet. Some future version will offer WiFi provisioning.

So if I switch from WifiNINA to esp8266, then I can connect to the wifi asynchronously?

@SaqibAli, yes. but usually setup() runs much faster then the connection is build-up so even then the sketch usually waits some seconds if having network at the end of setup() is needed.  you can connect a little faster with static IP address

For a proof-of-concept, use two Arduinos, one for WiFi and one for everything else.
The everything-else Arduino can keep your system responsive (minus the WiFi, of course, during connection time) and poll the WiFi Arduino periodically (without blocking) to find out when WiFi becomes available.

I think better solution is to use ESP8266 WiFi module and Connect if needed another Arduino through GPIO pins of ESP8266.
This video will be helpful,
https://www.youtube.com/watch?v=dWM4p_KaTHY

better then what?

Without using In Built Wifi Module.

so you say it is better to use an external esp8266 module then the on-board esp32? what is the difference?

Actually ESP 32 is a improvement o ESP 8266, but  I was able to use ESP 8266 with Arduino easily than ESP32 and ESP 8266 ha lot of  community threads.


text:
4052 interfacaing with arduino uno
I am trying to interface 4052 demux with arduino, but my program is not working as high is not displayed on serial monitor corresponding to select lines.
//output coming from demux pins
int sensorValue0=A0;
int sensorValue1=A1;
int sensorValue2=A2;
int sensorValue3=A3;

void setup() {
  Serial.begin(9600);
  Serial.println("start");
  //select pins connected A,B connected to 2 and 3
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
}

void loop() {
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  analogRead(sensorValue0);
  //Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  int voltage0= sensorValue0 * (5.0 / 1023.0);
  Serial.println("volatge0");
  Serial.println(voltage0);
}

Have you looked at any tutorials of references on how to use analogRead()?

You are ignoring the value read by analogRead().  You are then using the value A0 (14) in your sum to calculate the voltage.
Instead:
int adcReading = analogRead(sensorValue0);
int voltage0 = adcReading * (5.0 / 1023.0);

Although I think what you really meant to write was, in total:
int sensorPin = A0;
int sensorValue0;//output coming from demux pins
int sensorValue1;
int sensorValue2;
int sensorValue3;

void setup() {
Serial.begin(9600);
  Serial.println("start");
  pinMode(2,OUTPUT);//selecr pins connected A,B connected to 2 and 3
  pinMode(3,OUTPUT);
}

void loop() {
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  sensorValue0 = analogRead(sensorPin);
  float voltage0 = sensorValue0 * (5.0 / 1023.0);//Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  Serial.print("voltage0 = ");
  Serial.println(voltage0);
}

Note that the value sensorPin is where you read the voltage from, and sensorValue0 is where you store that reading. Also note the use of a float type to store the calculated voltage, since an int will give you only values of 0, 1, 2, 3, 4 or 5 in this situation (so, pretty meaningless really).

actually select pins of demux are not selected according to program written.

I am assuming it's a partially written program at the moment.

sir,one more thing what should i write to control two demux in a program using inhibit pin and activate only one demux at a time..

Just use digitalWrite to activate the mux you want.

I have used digitalwrite(4,LOW); as 4 pin of arduino is connected with demux inhibit pin and demux is fuctioning but when m not using inhibit pin of demux den still demux working,not understanding whats happening.why inhibit pin not working as it should

i have used CD4052BE DEMUX


text:
Frequent ON OFF in SSR
I am working on a project on Arduino OLED MAX6675 thermocouple and SSR for my oven.
My problem is when my SSR goes in LOW or HIGH state it  turn ON and OFF several times before going to permanent HIGH or LOW state.
This make my load(Heater) on and off many times. Since the temperature crosses the set-point to change the output state, the process temperature will be cycling rapidly, going from below set-point to above, and back below.
This frequent ON OFF will damage my SSR and heater.
My Question.
Is there any hardware or software solution. To reduce the frequency of ON OFF .
I can’t increase  the delay() time because it make my button input slow.
My codes are below.
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include "max6675.h"

//oled
//oled i2c addresss
#define OLED_ADDR 0x3C
Adafruit_SSD1306 display(-1);
// 128 x 64 pixel display
#define SSD1306_LCDHEIGHT 64

//MAX6675
//Pin initialization
int so = 2;
int cs = 3;
int sck = 4;
MAX6675 thermocouple(sck, cs, so);
float current_temp;
int set_temp;
int const h_temp = 2;

//Button
int button_up = 7;
int button_down = 8;
int button_upv;
int button_downv;

//SSR
int ssr_u = 10;
int ssr_d = 12;

void setup() {
    Wire.begin();
    delay(1000);

    // initialize and clear display
    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(8, 20);
    display.println("Welcome..");
    display.display();
    display.clearDisplay();
    delay(1000);

    //Button
    pinMode(button_up, INPUT);
    pinMode(button_down, INPUT);
    set_temp = 20;
    pinMode(ssr_u, OUTPUT);
    pinMode(ssr_d, OUTPUT);
}

void loop() {
    current_temp = thermocouple.readCelsius();
    delay(100);
    button_upv = digitalRead(button_up);
    button_downv = digitalRead(button_down);

    //button
    if (button_upv == HIGH && set_temp < 180) {
        set_temp = set_temp + 5;
    }
    if (button_downv == HIGH && set_temp > 20) {
        set_temp = set_temp - 5;
    }

    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(5, 10);
    display.println(current_temp);
    display.setCursor(5, 30);
    display.println(set_temp);

    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(30, 40);
    if (button_upv == HIGH) {
        display.println("Up");
    }
    if (button_downv == HIGH) {
        display.println("Down");
    }
    display.display();

    //SSR
    if (current_temp < set_temp - h_temp) {
        digitalWrite(ssr_u, HIGH);
        digitalWrite(ssr_d, HIGH);
        delay(500);
    }
    if else(current_temp > set_temp + h_temp) {
        digitalWrite(ssr_u, LOW);
        digitalWrite(ssr_d, LOW);
        delay(500);
    }
}

Thanks in advance for help

Which arduino board do you use? Are you using a 3.3v arduino board and a counterfeit ssr? Please explain better what you have and how it is powered. Google for hysteresis. You need to put some hysteresis into your sketch.

I am using pro mini 5v and 40 amp SSR.

the keyword is hysteresis http://forum.arduino.cc/index.php?topic=526806.0

Is there any hardware solution like adding a capacitor so that voltage remaining constant for few seconds

Hysteresis will just be way easier in software.

You need to implement hysteresis. Set two temperature points around set_temp. One a little higher to be a limit for turning the heater off and a one a little lower then set_temp to turn the heater on.
You only need to change your if else condition a little
if (current_temp < set_temp - HYST_VALUE) {
  digitalWrite(ssr_u, HIGH);
} else if (current_temp > set_temp + HYST_VALUE) {
  digitalWrite(ssr_u, LOW);
}

you could start with
int const HYST_VALUE = 1;

Is there any hardware solution like adding a capacitor so that voltage remaining constant for few seconds

this is a regulation problem, not simply solvable by hardware. the temperature could oscillate around your set temperature long time. implementing hysteresis is how it is done in all thermostats

I edited the answer

Hello juraj I tried the same as you said but this code freeze loop somewhere. I am doing something wrong somewhere please help.I tried the same code.

Hello juraj I also change my sketch in question please check it.

you have < twice and it is } else if (

Let us continue this discussion in chat.


text:
Updating MAX7456 library to work with Arduino 1.6.6
I've got this library for communicating with the MAX7456 chip.
The library is abandoned and the only one I found that actually works, so I'd really like to use it.

It compiles fine with Arduino IDE 1.0.5, but not with Arduino IDE 1.6.6 .
This happens with 1.6.6, I tried to fix it but I only made it worse.
Arduino: 1.6.6 Hourly Build 2015/07/03 10:26 (Linux), Board: "Arduino Nano, ATmega328"

Using library SPI at version 1.0.0 in folder: /home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/libraries/SPI
Using library max7456 in folder: /home/t/Dropbox/Arduino/libraries/max7456 (legacy)

/home/t/Dropbox/Arduino-IDE/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10606 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/cores/arduino -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/variants/eightanaloginputs -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/libraries/SPI -I/home/t/Dropbox/Arduino/libraries/max7456 /tmp/build4912026784583215357.tmp/sketch/HelloWorld.cpp -o /tmp/build4912026784583215357.tmp/sketch/HelloWorld.cpp.o
In file included from HelloWorld.ino:2:0:
/home/t/Dropbox/Arduino/libraries/max7456/max7456.h:228:40: error: 'prog_uchar' does not name a type
static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);
                                    ^
/home/t/Dropbox/Arduino/libraries/max7456/max7456.h:228:52: error: ISO C++ forbids declaration of 'table' with no type [-fpermissive]
static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);
                                                ^
Error compiling.

How would one make the library compatible with 1.6.6?

In the file max7456.h at line 228 change it from:
static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);

to:
static void getCARACFromProgMem(const char *table, byte i,charact c);

In the file max7456.cpp at line 484 change it from:
void Max7456::getCARACFromProgMem(const prog_uchar *table, byte i, charact car)

to:
void Max7456::getCARACFromProgMem(const char *table, byte i, charact car)

Then it compiles OK (under 1.6.4 at least).

The character map updating code does not work, but that is not a major flaw.


text:
Updating a sketch to work with IDE 1.6.6
I've got a MAX7456 chip and I am using this (this is the unmodified one) library with it.
There's a sketch inside the examples folder (Max7456WriteTable) that I need to get to work to update the character table.
I modified three lines and then I got really stuck as I do not know how to continue. This is the modified one.
In file included from Max7456Write.ino:2:0:
/tmp/build4608284042510222737.tmp/sketch/Max7456WriteTable.h:29:69153: warning: narrowing conversion of '243' from 'int' to 'const char' inside { } is ill-formed in C++11 [-Wnarrowing]

This happens for every item in the array. But that is not the only problem. (I'll skip a few hundred lines)
/tmp/build8855411239666100148.tmp/sketch/Max7456Write.cpp.o: In function `setup':
/home/t/Max7456Write.ino:13: undefined reference to `Max7456::Max7456(unsigned char)'
/home/t/Max7456Write.ino:19: undefined reference to `Max7456::activateOSD(bool)'
/home/t/Max7456Write.ino:44: undefined reference to `Max7456::getCARACFromProgMem(char const*, unsigned char, unsigned char*)'
/home/t/Max7456Write.ino:46: undefined reference to `Max7456::sendCharacter(unsigned char const*, unsigned char, unsigned char)'
collect2: error: ld returned 1 exit status
Error compiling.

It takes a huge amount of time for it to abort the compilation.

https://github.com/arduino/Arduino/wiki/1.6-Frequently-Asked-Questions#q-the-compiler-complains-about-prog_char-or-anything-that-begins-with-prog_-the-exact-error-is-iso-c-forbids-declaration-of-type-name-with-no-type-what-can-i-do

@Gerben I tried everything I could, it does not compile. I tried changing what is mentioned in the wiki page, it still does not work. The array no matter what I try either complains "duplicate const" or "not constant" or "invalid conversion from int to const char". As a newbie this is way too complex for me.

Yeah, it now works when I nuked my install.

If I change prog_uchar to unsigned char in both max7456.h and max7456.cpp the hello world example sketch compiles.
In Max7456WriteTable change
Max7456::getCARACFromProgMem(i,currentChar); //Because the table is too big for ram memory

osd->sendCharacter(currentChar,i); //We send currentChar at address i.

to
Max7456::getCARACFromProgMem(tableOfAllCharacters, i,currentChar); //Because the table is too big for ram memory

osd->sendCharacter(currentChar,i, 0); //We send currentChar at address i.

0 is probably the wrong value, but at least it compiles.

Did that already. Check my second download link for my current progress.

Just move the contents of Max7456WriteTable.h to Max7456WriteTable.ino, and adding #include <SPI.h> makes the second download compile.

Are you using IDE 1.6.6?

1.6.3. I updated to 1.6.6 and still compiles. https://www.dropbox.com/s/d3d0mkasvqrea8k/max7456.zip?dl=0

I updated my Arduino IDE version, wiped all libraries, redownloaded them, nuked all configurations and dynamic links I've created to keep consistency in my projects. It now finally works.

authors: بشير عبد الوهاب


text:
How to update the character table of MAX7456
I've got a MAX7456 chip and I am using this library with it.
But the issue is that the character table is not the one the library needs to function like it should. The "Hello world" example is nowhere near to what it should display, because the character table is wrong.
All the instructions that talk about character set updating require a USB FTDI cable (I don't have one), I am able to  program the board with USBASP programmer but that's it. I also have a few Nanos, if that helps.
How could I update the character table to what the library needs (without a FTDI cable) or how to make the sketch included to update the character set work properly?

In what way is it wrong? Garbage? Inverted? Rotated 90 degress? Please specify.

ASCII lookup does not work properly.

Question: In what way is it wrong? Answer: ASCII lookup does not work properly. Nope, still uncertain what the problem is.

"The issue is that the character table is not the one the library needs to function like it should." "ASCII lookup does not work properly." The library is not using the right characters, I have no idea how to make this even clearer.

Give an example: What do you do, what do you expect, what happens, what is the difference between expectation and observation?

I use the "Hello world" example, load it to the board. It displays stuff on the screen. The characters are wrong because the character table is wrong. It looks up the characters wrong.
Are my comments using wrong encoding and you are not seeing it right, because I have said the same thing now four times.

Have you looked at the datasheet yet? Specifically pages 34 and 33?

I posted the datasheet, yes, I have looked at it for some things but my question is how to update the character set to what the library needs, and as I described I do not have a FTDI cable and I don't know how what character set the library needs exactly.

@Avamander Included in the library is Max456WriteTable.cpp. Have a look at that: it appears to be a method of writing characters to the EEPROM on the IC. HOWEVER you still haven't said what is actually displayed on the screen when you run the "Hello World" example. Please state, unequivocally and explicitly, what you get instead. Better yet, tell it to print out ALL the characters and show us what you get vs. what you've asked for.

Oh, I must've missed the table write sketch, it does not appear in the examples. I tried to compile the sketch but it fails (IDE 1.6.4).

@CharlieHanson The character table is wrong; not the one library needs; ASCII lookup does not work; it is not using the right characters. l = @ for ex.

@Avamander, yes you keep saying that. What characters DOES it use? WHAT DOES IT PRINT INSTEAD OF "HELLO WORLD" ?? This is like getting blood from a stone.

It says "HE@@O WO(arrow pointing up)@: P- #U(arrow pointing up twice)E+(->)" no sentence comes out right.

Also, you found the charset updating sketch, how would one make it compile?

Copy the contents to a new *.ino file, and put the *.h file in the same folder as your *.ino file (unless the IDE finds it by itself).

"Max7456WriteTable.h:11:21: fatal error: max7456.h: No such file or directory #include <max7456.h>" happens.

...copy the h-file into the directory where you have saved the new sketch.

http://i.imgur.com/wIExx2t.png happens when all includes work properly. The library is also not working with IDE 1.0.5.

To solve this problem one would need to get the builtin character updating sketch work (Max456WriteTable.cpp in examples folder). After the sketch has been compiled one would have to connect either FTDI cable or a USBASP programmer to the board and upload the sketch to it.
The character set (array) itself used in the code can be updated with the appropriate program available at this site.
UPDATE: In the end I solved it this way.
Many thanks to Charlie Hanson & Nick Gammon.


text:
How do I escape a boot loop?
Note: This is a reference question (but feel free to write answers of your own!)

I uploaded code that contains a bug that causes my Arduino to immediately reset itself when starting using this code from the AVR libc FAQ. The built-in LED keeps flashing. Because it's in this state of constantly resetting, I'm unable to upload my sketch to it.
I tried holding the reset button while uploading and burning a new bootloader, but neither of those worked.
How do I get my Arduino out of this boot loop so I can upload sketches again?

If you are planning to answer your own questions, which is a great idea, it helps to note that it is a "reference question". That is, you are posting to help other people, not necessarily to canvas for answers. I did this a few times before people pulled me up on it. :)

Thanks for contributing these questions + answers to the community.

Thanks for the tip @Nick, I added a note to all of my questions :)

Start holding the reset button. This is to prevent the Arduino from entering the boot loop.
Unplug the Arduino and plug it back in.
Open a new sketch. Remove all of the code and replace it with int main(){}. This is to create a small program that will upload quickly.
Start uploading the sketch. Avrdude will attempt to upload the sketch ten times -- each time it tries, the RX LED on the Arduino will flash briefly.
Notice how often the LED flashes (0.2 Hz for me). Right before it flashes again, release the reset button. There's a small window of oppurtunity for avrdude to upload the sketch before the arduino starts up. If the TX and RX LEDs flash, success!

Since you have not specified which Arduino you have, answered your own question in quite short time, and commonly a sketch has no main(), this looks fishy.

"answered your own question in quite short time" StackExchange encourages this. This is not a Q&A site, it's a resource

"you have not specified which Arduino you have" This is not relevant

"commonly a sketch has no main()" All sketches have a main(), you just can't see it. This main() can be overridden, which is what happens in my answer

"this looks fishy" What fishy agenda could I possibly have? My answer hurts nobody, but it can help some people. I don't gain any rep from it (thanks to you, I just lost some) -- I posted it solely to help others with the same problem

decent answer to a poorly written question...

I just gave you some rep. Don't worry too much about rep. If you post good questions and answers you will soon have so much rep you won't know what to do with it. ;)


text:
How do I upload a sketch without a bootloader, using another Arduino as a programmer?
Note: This is a reference question (but feel free to write answers of your own!)

My Arduino takes too long to start up, I need to use the space taken up by the bootloader and I don't want a brown-out to be able to move the program counter to bootloader code, which could lead to my code being corrupted.
I considered buying an Arduino programmer, but since I already have an Uno lying around doing nothing, I would rather use that as a programmer.
I found a few guides on the internet, but most of them leave important details out and aren't specific enough.
So, how can I upload a sketch without a bootloader, using another Arduino as a programmer?

a 10-year old blog post about another stack might not be as relevant here as imagined. Of course SO wants any and all free content, but do users? I don't have a problem with it, but you should probably make your "questions" better fit the usual format; for this one, the "what have you tried" part is lacking, which makes this effort seem more like fishing for points than a useful Q+A combo. Your information is well laid-out and your intentions well-laid, but you should likely pay a bit closer attention to the rules, conventions, and expectations. If you beef up the question I will UV...

@dandavis I beefed up this question and the other one. I rewrote them in a more asking-help kind of manner and added things that might have been tried by the questions' target audiences. Do they look good now?

@dandavis Reference questions are perfectly fine. Our expectations are that people will contribute to the community, which glibg10b seems to be doing. Let's try to encourage new contributors.

There are a few guides on the internet that explain how to do this, but I've
found that most of them contain too much ambiguity or leave important details
out. This is my attempt at writing a short but complete guide that's easy to
follow.
Prerequisites

The board that will run your sketch
A board that will act as a programmer (a.k.a. "ISP")
7 wires
Any small capacitor

Steps
Programming the programmer
First, you'll need to upload the ArduinoISP sketch to the programmer. Here's
how:

In the Arduino IDE, press Alt+F and open Examples ->
11.ArduinoISP -> ArduinoISP.
Plug in the programmer board (USB).
Press Alt+T and set "Board" to your programmer
board's type and "Port" to your programmer board's serial port.
Press Ctrl+U to upload the sketch to your programmer.

Connecting the boards
Then you need to connect the programmer to the board that will run your sketch.

Unplug the programmer board. This is to prevent accidental short-circuits.
Connect pins GND, 10, MOSI, MISO, SCK and 5V of the programmer to pins
GND, RESET, MOSI, MISO, SCK and 5V of the board that will run your
sketch, respectively. Pins MOSI, MISO and SCK correspond to pins 11, 12 and
13, respectively, on the Uno and the Nano. Consult your board's datasheet if
you're uncertain.
Connect the capacitor between pins 5V and RESET of the programmer board. This
is to prevent it from auto-resetting while programming.
Plug in the programmer board. You will never need to plug in the board that
will run your sketch.

Uploading your sketch
The order of these steps is important due to a bug in the Arduino IDE.

Press Alt+T and set "Board" to the board that will run
your sketch's type, "Port" to your programmer board's serial port and
"Programmer" to "Arduino as ISP".
Open the sketch you would like to upload.
Press Ctrl+Shift+U to upload the sketch using the programmer.

Troubleshooting
If something went wrong, press Ctrl+, and enable verbose
"compilation" and "upload" and repeat the step that went wrong. Look out for
these error messages:
avrdude: stk500_recv(): programmer is not responding
Followed by something similar to:
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0

Remove the capacitor before uploading a sketch to your programmer board.
avrdude: Yikes!  Invalid device signature.
Scroll up and copy the line that looks similar to the following:
...avrdude -C...avrdude.conf -v -V -p... -c... -P... -b... -Uflash:w:....hex:i

Paste it into a terminal and add  -F to the end. You can reuse this command
every time you upload the same sketch.
The upload seems to succeed but my sketch is still running the same code!
If the board that runs your sketch's CPU clock is slower than 1MHz (e.g. your
sketch modifies the CPU prescaler), you need to change (1000000/6) in the
ArduinoISP sketch to something slower and re-upload the sketch to your
programmer.


text:
How do I build and upload a C++ program without the Arduino Library or IDE?
Note: This is a reference question (but feel free to write answers of your own!)

I want to use the AVR tools directly -- no arduino-builder or arduino-cli. I would also like compilation and uploading to be as fast as reasonably possible

How fast? Can you put a metric on that? Uploading necessarily takes time, because it uses serial communications. Compiling, once invoked by the IDE is likely to be as fast as if you typed it on the command line. Of course, we would all like it to be faster than it currently is. But your requirement to be "fast" is rather un-specific.

Oh, I see this is a reference question. In that case see: https://arduino.stackexchange.com/questions/15893/how-to-compile-upload-and-monitor-via-the-linux-command-line/15898#15898

Create a new file called Makefile in your project directory. Populate it with the following contents:

TEMPDIR := $(shell mktemp -d)

all:
    avr-g++ -DF_CPU=<CLK> -mmcu=<PARTNO> -fno-threadsafe-statics -O3 -flto -std=c++23 -isystem/usr/avr/include -lm -fuse-linker-plugin -Wl,--gc-sections *.cpp -o ${TEMPDIR}/a.elf

    avr-objcopy -O ihex -R .eeprom ${TEMPDIR}/a.elf ${TEMPDIR}/a.hex
    avrdude -V -p<PARTNO> -carduino -P/dev/tty<SERIAL_PORT> -b<BAUD> -D -Uflash:w:${TEMPDIR}/a.hex

    rm ${TEMPDIR}/a.elf ${TEMPDIR}/a.hex
    rm -d ${TEMPDIR}

In the Arduino IDE, press Ctrl+, and enable verbose output during compilation and uploading.
Start uploading with Ctrl+U. Replace the groups of angled brackets in Makefile (e.g. <CLK>) with the values in the Arduino IDE's build output.
Run make.

-lm links in the AVR math library. *.cpp refers to your c++ source files. -V prevents avrdude from reading back the flash contents and verifying it, which saves time, but you may want to disable it while diagnosing problems.

For a similar but more general solution, you may want to take a look at Sudar Muthu's Makefile. If you are not using the Arduino core library, you can remove a lot of cruft from the g++ command line.

Checking the signature and verifying the flashed application are important safety features, I recommend to keep them to avoid long hours of searching errors.

@busybee Amended, thanks

@edgar I just realized "a lot of cruft" refers to my answer, and not Sudar Muthu's Makefile. Fixed, thanks :)

You could enhance your answer a lot, if you add explanations why each step is necessary, and what it contributes to the process. I'm missing for example that the intermediate step with the Arduino IDE is just for finding some decent values for clock and MCU, which could be entered as well manually, since you chose them in the IDE before. -- A great answer would also reason on each option of each tool. Especially as a beginner you need to learn what is important and what is not. Currently this is just one possible way thrown without additional information to unaware users.