text:
Arduino fingerprint Scanner stop loop after enroll or delete
How can I stop the loop when I enroll a fingerprint to the module?
The loop is stuck in enrolling fingerprint even it was already done. The result I want was after the enrollment of fingerprint, it will exit the loop of enrollment and start the default switch command. Thank you in advance.
Here is my loop code.
    void loop() {
//
    if (Serial.available() > 0) {
      // read the incoming byte:
      command = Serial.read();

      // say what you got:
      Serial.print("I received: ");
      Serial.println(command);
    }
    switch (command) {
    case 'A':
    {
      Serial.println("Ready to enroll a fingerprint!");
      Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
      id = readnumber();
      if (id == 0) {// ID #0 not allowed, try again!
         return;
      }
      Serial.print("Enrolling ID #");
      Serial.println(id);

      while (!  getFingerprintEnroll() );
    }
      break;
    case 'B':
    {
      Serial.println("Case 2");
    }
      break;
    default:
    {
        getFingerprintDoorLoob();
        delay(50);
    }
      break;
  }
}

Here is the enroll fingerprint code:
 uint8_t getFingerprintEnroll() {

  int p = -1;
  Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
  while (p != FINGERPRINT_OK) {
    p = finger1.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger1.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  Serial.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger1.getImage();
  }
  Serial.print("ID "); Serial.println(id);
  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK) {
    p = finger1.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.print(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger1.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  Serial.print("Creating model for #");  Serial.println(id);

  p = finger1.createModel();
  if (p == FINGERPRINT_OK) {
    Serial.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    Serial.println("Fingerprints did not match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  Serial.print("ID "); Serial.println(id);
  p = finger1.storeModel(id);
  if (p == FINGERPRINT_OK) {
    Serial.println("Stored!");

  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("Error writing to flash");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }
}

This was the current result, what I expect was after it was stored the loop will break. please help thank you

you have to give the while loop an exit status

I see the problem here. Now observe the
if(Serial.available>0)
{
//Block of Statements
}
Your closing bracket for that if statement must be after the switch() statement.
For every iteration (void loop()) your command variable runs your switch and calls the enrolling function.
So it should be:
if (Serial.available>0){
//Block of statements
Switch(command){
//Block of statements}
}
}
Hope this helped

that result was the same, what I want was after enrollment loop then it will break but the result was after enrolling a fingerprint , the loop will start again in enrollment loop.


text:
Uno to NodeMCU Serial Connection Problem
This is my first project with any sort of development board and it has been a blast so far.
I am running into some issues, however, while trying to send serial data from my Uno to a NodeMCU board.
I have the following connections:
Uno Rx to NMcu Tx
Uno Tx to NMcu Rx
Uno GND to NMcu GND
microUSB from computer to power NMcu
usb from computer to power Uno
EDIT: after some suggestions, I have also tried the following.
Uno DigitalPin 5 to NMcu D6
Uno DigitalPin 6 to NMcu D5
Uno GND to NMcu GND
microUSB from computer to power NMcu
usb from computer to power Uno
With the following code:
// UNO sender Code
#include <SoftwareSerial.h>
SoftwareSerial toESP(0, 1); //Rx, Tx (also tried 5,6)

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

void loop()
{
  Serial.println("sending");
  toESP.println("message from Nano");
  delay(1000);
}

// NodeMCU receiver code
#include <SoftwareSerial.h>
SoftwareSerial fromNano(3, 2); //Rx, Tx (also tried D5, D6)

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

void loop()
{
  if (fromNano.available())
  {
    char inChar = fromNano.read();
    Serial.print(inChar);
  }
  else {
    Serial.println("not available");
  }
  delay(2000);
}

I can pull up a serial monitor from both and see the UNO sending data (the TX led also blinks on the uno).
The NodeMCU code never satisfies the fromNano.available condition.
Is there anything I am overlooking that is causing this not to work? I've attached a picture of my connections as well.

Any help is much appreciated.

0 and 1 are hardware Serial pins in Uno and 3 is a hardware Serial pin on NodeMcu so you should not use it for SoftwareSerial. and the wires are on pins 1 and 3 on NodeMcu (hardware Serial pins)

Hmm, thanks for the response. I tried using other digital pins on the arduino and nodemcu (and made sure to update the corresponding code) the other night, but didn't have any luck. I tried something like SoftwareSerial(5,6) for the sender (arduino) and SoftwareSerial(D5,D6) for the receiver (nodeMCU). Making sure that arduino digital pin 5 is connected to nodemcu D6, and vice versa. I'll try again later tonight.

@Juraj - After trying on digital pins 5,6 on the arduino, and D5,D6 on the nodemcu, I still cannot receive serial data. fromNano.available() is always false. I've set both to 9600 baud rate. https://imgur.com/a/gfVo2nt

Arduino UNO is using pin 0 and pin 1 to have serial with USB serial Communication. You can not use them to softserial. Change softserial to other pins.  /Mikael

Thanks for the comment. Is it fine to just use any other digital pins to initialize the SoftwareSerial?

I tried digital pins 2 and 3 (and also 5,6) for RX,TX respectively and it didn't seem to solve the issue. Thank you for the suggestion though.

Why do use 2 serial conections, you only need one.

I'm only using one serial connection between the boards from my understanding. I just tried on pairs (2,3) and (5,6) independently for troubleshooting.

In the code you are using two.

Are you referring to Serial vs SoftwareSerial? I am including a Serial channel to debug via the monitor in Arduino IDE

Is the Arduino 5V or 3V? The NodeMcu is not always 5V tollerant. Try to remove the USB connection from the Arduino then connect 3V from NodeMcu to 5V on the Arduino.

@Carlmikael is definitely correct in his answer, I should not have been using hardware pins with softwareserial.
Besides that problem, my issue was resolved ultimately when I noticed that if I powered up the NodeMCU before powering up the Arduino, everything worked as expected.
Maybe someone can elaborate as to why this caused an issue?

source: Stack Exchange

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

sort: votes


text:
hexadecimal 1 to float 1 - Compare the float 1 with a predefined float 2 - If the float 1 and float 2 are the same - Print hexadecimal 2
I want to input a hexadecimal data from cool terminal say like (05 00 02 03 00 04 00 E5) And convert the data to a float value say 45.3. Now that I have to preassign a float value say 45.3 in my program so that I can compare the converted float value with the preassigned float value. If the two values match I need to print another hexadecimal value i.e( 05 03 00 01 00 02 04 4F).
I have managed to do the conversion of hexadecimal to float. Can someone please help me in comparing the two float values?

In what format are you sending the float over serial? ASCII encoded decimal number? ASCII encoded hexadecimal number? binary? Currently you are reading ASCII encoded decimal.

please not that you're creating a char array floatString of size 9. your index 10 is out of bounds! also there are pleny of solutions for your problem online. just enter "hex string to float" into any websearch

What exactly are you trying to achieve with all this float to hex conversion? It sounds to me like you are trying to solve a problem and you have a pre-conceived, yet incorrect, notion of how to do it. What is the actual problem you are trying to solve here?

Let me edit the question for a better understanding. Sorry for the inappropriate question.

I guess you are not talking about hexadecimal data but binary data representing a double or float64 in IEEE 754 format. To compare two arrays of 8 bytes for equality, rather use memcmp

You need to clarify your question. As @DataFiddler says, it looks like what you are inputting is the binary representation of a float in IEEE floating point format. You need to edit your question to clarify.

Comparing floating point values is notoriously difficult. This is because floating point is only an approximation.
You should first define an error margin - a value which is how close together the two values need to be before you consider them to be the same.
For example 1.000000 and 1.000001 could be considered to be the same value in many circumstances.
The simplest method is to just subtract one value from the other, take the absolute value of the result, and see if it is below the error margin.
bool almost(float a, float b, float margin) {
  float diff = fabs(a - b);
  return (diff < margin);
}

Thanks for the reply

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


text:
Trying to understand AccelStepper constant speed
I'm starting to learn the AccelStepper library for controlling stepper motors for a project I'm working on. I'm able to get the stepper motors running with the basic examples that use acceleration.
I know for parts or all of project I'll want to use constant speed, so I popped up the constant speed demo: https://github.com/adafruit/Adafruit_Motor_Shield_V2_Library/blob/master/examples/Accel_ConstantSpeed/Accel_ConstantSpeed.ino
#include <Wire.h>
#include <AccelStepper.h>
#include <Adafruit_MotorShield.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myStepper1 = AFMS.getStepper(200, 2);

void forwardstep1() {
  myStepper1->onestep(FORWARD, SINGLE);
}
void backwardstep1() {
  myStepper1->onestep(BACKWARD, SINGLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1);

void setup()
{
   Serial.begin(9600);
   Serial.println("Stepper test!");

  AFMS.begin();  // create with the default frequency 1.6KHz

  Astepper1.setSpeed(50);
}

void loop()
{
   Astepper1.runSpeed();
}

(I'm using the adafruit stepper motor wing)
I uploaded it to my arduino and it's working, the shaft is rotating, but it's doing it really slow. I figured this made sense because it's set at a speed of 50, so I tried turning up the speed:
Astepper1.setSpeed(200);

But the speed still seems to be the same speed. Considering this is a 200 step motor and setSpeed is steps per second you'd think this would whip the motor around fairly quick.
I'm positive that this is due to my misunderstanding of how the library works, but I'm having a hard time trying to figure out how to properly use the constant speed methods.

please put a space before the https:// in the URL ... without it, the link is not clickable

try the other example sketches

Hey @jsotola, I corrected the link. thanks for that catch. Also, I have tried the other demo sketches. The acceleration based demos work and even the StackingTest.ino demo works which doesn't use constant speed directly, but does individual stepping without acceleration and that works, but I still can't seem to figure out why the constant speed methods themselves do not work as expected.

I just realized that the Stacking test doesn't use the accelstepper library, so yeah, still at a loss :(

@jsotola, figured it out. See my answer below.

So I ended up doing some source code diving for the AccelStepper library to figure out what the problem was and it turns out there was a missing method call in their example code, specifically a call to setMaxSpeed in the setup function:
void setup()
{
    Serial.begin(9600); // set up Serial library at 9600 bps
    Serial.println("Stepper test!");

    AFMS.begin(); // create with the default frequency 1.6KHz

    // ! Note that you need to set the max speed, otherwise the stepper motor will
    // ! only step once per interval regardless of what `setSpeed` value you give
    Astepper1.setMaxSpeed(1000);

    Astepper1.moveTo(targetDistance);
    Astepper1.setSpeed(targetSpeed);
}

If you look at the setSpeed method in the library you'll notice a constraint of the speed value:

The constrain method takes in a speed value and then a low and high, which the accelstepper library sets to the private _maxSpeed variable. If the speed is outside of that range it will set the value to the low or high value passed in.

This means, if you don't call setMaxSpeed the library will use the default _maxSpeed value assigned during construction which issss 1.0:

So, to correctly use the constant speed methods, you need to be sure to include a call to setMaxSpeed in your code before calling setSpeed, likely in the setup function.
I also shot a video explanation to share with my co-workers. You can see it here: https://vimeo.com/438272826


text:
NRF24L01+PA+LNA communication problem
I'm trying to communicate between two NRF24L01+PA+LNA modules.
I know that NRF24L01+PA+LNA modules are consuming a lot of power and here is my 3.3V power circuit.

The LM317 datasheet says it can output up to 1.5 Amp.
I'm not using Arduino, I'm using STM32F103 blue pill and I'm powering it from this single LM317 linear voltage regulator.
I'm using 1100 mAh, 8.4V LIPO battery, one for Transmitter module(NRF24L01+PA+LNA and STM32 Blue Pill) and second one for receiver module (also with NRF24L01+PA+LNA and STM32 Blue Pill).
So my problem is that, when I'm TOUCHING the Transmitter's antenna somewhere in the middle with my FINGERS, then it transmits; If I'm not touching the antenna, it does not transmit.
I also added additional 100uF polar capacitors between NRF24L01+PA+LNA's VCC and GND, but it does not help.
What else can I do?


text:
Arduino on/off PWM
When I turn on DC motor with a button I get a a fixed PWM value that goes into a loop till button state changes.
What should I change that I could change X value with potentiometer in a loop?
int X = A0;
int SW = 2;
int Xval=5;
int SWval;
int buttonNew;
int buttonOld = 1;
int buttonState= 1;
int engine = 6;

void setup() { // This executes once
  Serial.begin(9600);
  pinMode(X, INPUT);
  pinMode(SW, INPUT_PULLUP);
}

void loop() { // This loops continuously
  Xval = analogRead(X);
  buttonNew = digitalRead(SW);

  if (buttonOld == 0 && buttonNew == 1) {
    if (buttonState == 0) {
      analogWrite(engine, Xval);
      buttonState = 1;
    }
    else {
      digitalWrite(engine, LOW);
      buttonState = 0;
    }
  }

  buttonOld = buttonNew;
  delay(1);
  Serial.print("button");
  Serial.print(SWval);
  Serial.print("          X=");
  Serial.println(Xval);
}

Move the analogWrite out of the button-state-change code, and it will update the PWM continually, instead of only when the button is pressed.
See the code below.
I also change the variable name buttonState to motorState, as it indicates the state of the motor (On/Off). And I inverted it, so 1 means the motor is ON.
The other thing I did was to increase the delay to 10ms, so you don't get any issues with switch-bounce.
int X = A0;
int SW = 2;
int Xval=5;
int SWval;
int buttonNew;
int buttonOld = 1;
int motorState= 0;//indicates whether the motor is on/off
int engine = 6;

void setup() { // This executes once
  Serial.begin(9600);
  pinMode(X, INPUT);
  pinMode(SW, INPUT_PULLUP);
}

void loop() { // This loops continuously
  buttonNew = digitalRead(SW);
  if (buttonOld == 0 && buttonNew == 1) {
    if (motorState == 0) {
      motorState = 1;
    }
    else {
      motorState = 0;
    }
  }
  buttonOld = buttonNew;

  if (motorState == 1) {
    Xval = analogRead(X);
    analogWrite(engine, Xval);
  }
  else {
    digitalWrite(engine, LOW);
  }

  delay(10);
  Serial.print("button");
  Serial.print(SWval);
  Serial.print("          X=");
  Serial.println(Xval);
}


text:
Sending Variable to IFTTT via ESP32 using Asynchronous Web Server
I have been trying to send three variables to IFTTT from my ESP32 using Asynchronous Web Server. However, I couldn't set the "URL" that was supposed to be the response that will trigger my IFTTT. Here's is my code:
server.on("/ifttt", HTTP_GET, [](AsyncWebServerRequest *request){

String jsonObject = "{\"value1\":\"" + Global_T + "\"" + ",\"value2\":\"" + Global_H  + "\"" + ",\"value3\":\"" + Global_K +  "\"}";

AsyncWebServerResponse *response = request->beginResponse(200, "application/json", jsonObject);

response ->addHeader("Host", server_ifttt);
request ->send(response);
});

It shall get triggered every fixed interval that I have set, and enter here to send it to IFTTT, but this is how it looks like. I not sure where should I add in the "URL" so that the response could be directed to IFTTT.

shouldn't you be using a web client to send data to IFTTT?

Sorry, I was kinda new in this. Which means it is impossible for me to send data to IFTTT if I am using Asynchronous Web Server?

no, that is not what it means ... you can have web server code, but you also need web client code to connect to the IFTTT server

As already said in the comments you need client code - Here are ready to use blocks for your scenario - NEVER use String class if you want to have a stable running IoT device, so define global char arrays (compiled to flash) and keep heap fragmentation at a minimum, The code is commented to get you started, change to your needs:
/* Your constants */
#define READ_THIS_PIN 4
const char MakerIFTTT_Key[] = "r8X-blahblahYourKeyGoesHere";
const char MakerIFTTT_Event[] = "stack_exchange_example";

/* Define global char arrays to get rid of string class */
    char numBuf[20];       // We "just know" this is big enough for (un)signed longs
    char postRequest[256];    // Hand-calculated to be big enough (size to your needs)
/* Helper functions for constructing the POST data
    append a string or int to a buffer, return the resulting end of string */

char *appendStr(char *tempChr, char *s) {
    while ((*tempChr++ = *s++))
        ;
    return tempChr-1;
}

char *appendUl(char *tempChr, unsigned long u) {
    return appendStr(tempChr, ultoa(u, numBuf, 10));
}
/*
 This is called once per iteration to read the pin
 and send a POST to trigger the IFTTT/Maker event
*/

void updateEvent() {
    WiFiClient client;

    /* Connect to the Maker event server */
    client.connect("maker.ifttt.com", 80);

    /* Construct the POST request */

    postRequest[0] = {'\0'}; /* Reset char array */
    char *p = postRequest;
    p = appendStr(p, "POST /trigger/");
    p = appendStr(p, "MakerIFTTT_Event");
    p = appendStr(p, "/with/key/");
    p = appendStr(p, "MakerIFTTT_Key");
    p = appendStr(p, " HTTP/1.1\r\n");
    p = appendStr(p, "Host: maker.ifttt.com\r\n");
    p = appendStr(p, "Content-Type: application/json\r\n");
    p = appendStr(p, "Content-Length: ");

    /* We need to remember where the content length will go, which is: */
    char *contentLengthHere = p;

    /* It's always two digits, so reserve space for them (the NN) */
    p = appendStr(p, "NN\r\n");

    /* End of headers */
    p = appendStr(p, "\r\n");

    /* Construct the JSON; remember where we started so we will know len */
    char *jsonStart = p;

    // This example reports a pin, uptime, and "hello stack" change to your need */
    p = appendStr(p, "{\"value1\":\"");
    p = appendUl(p, 12);    //analogRead(READ_THIS_PIN));
    p = appendStr(p, "\",\"value2\":\"");
    p = appendUl(p, millis());
    p = appendStr(p, "\",\"value3\":\"");
    p = appendStr(p, "hello, stack!");
    p = appendStr(p, "\"}");

    /* Go back and fill in the JSON length
       we just know this is at most 2 digits (and need to fill in both) */
    uint8_t i = strlen(jsonStart);
    contentLengthHere[0] = '0' + (i/10);
    contentLengthHere[1] = '0' + (i%10);

    // finally we are ready to send the POST to the server!
    client.print(postRequest);
    client.stop();
}


text:
HC-SR04 ultrasonic sensor: How to check voltage on the ECHO pin
I'm using and ESP8266 with HC-SR04 ultrasonic sensor. The sensor requires 5v input and will also output to the GPIO pins at 5V.
ESP8266 has a strong recommendation to use 3.3V into the GPIO pins. I've found some setups online with people using voltage dividers to bring the ECHO pin voltage down.
Example on a PI: https://tutorials-raspberrypi.com/raspberry-pi-ultrasonic-sensor-hc-sr04/
I'm using a basic multimeter that i've found to be pretty accurate. When I put the BLACK cord on the ECHO and RED on the GROUND (of sensor pins), I get variable voltage readings. I'm trying to ensure a 3.3V coming from the ECHO into my ESP.
Questions:

Am I putting the black and red cords on the appropriate areas?
If yes to question 1, then why am i get such a variable of readings?
How can I test to ensure only 3.3V coming out of ECHO?

As Majenko already wrote, the black cord goes always to ground, so you have the leads backwards (though this just means, that your multimeter will report a negative voltage, if it is able to do so).
But besides that you cannot easily measure the echo pulse with a multimeter. A multimeter is build to measure either a DC voltage or a constant AC voltage. It is not build to measure the peak signal of a pulsed line. Some good multimeters may be able to do that, but it most of them (an definitely the basic ones) cannot do this. They are measuring the voltage over a relatively long period of time (longer than an echo pulse) with multiple measurements (to average out the noise). Also you cannot control, when exactly each measurement is taking place. So depending on the exact timing, the multimeter might have multiple pulses in the measurement (reading 5V there) or even missing pulses completely. That's the meaning of the Nyquist frequency, which states, that the measurement frequency must be higher than double of the signal frequency, or you will not be able to measure the signal correctly.
The echo pulse - if you receive one - will be rather short. With the maximum distance of most ultrasonic sensor boards of 3m, you will get a maximum pulse length of
3m / (300 m/s) = 0,01s = 10ms

You won't be able to correctly read that pulse with a multimeter. You would need an oscilloscope for that.
What to do now? If you want to make sure, that the used voltage divider divides 5V input to 3.3V output, you can connect the input to the 5V pin (but disconnect the echo pin first). Then measure the voltage at the output (which is now HIGH all the time, not just for the time of a pulse). If it's 3.3V, you can be sure, that the divider works correctly. As the ultrasonic sensor is provided with 5V, it won't output more than that. So you can be sure, that the ESP will only see 3.3V.

You have your leads backwards. But that doesn't matter, since there's nothing to measure. You'll only see a voltage (and even then only a brief pulse) when an echo is actually received.
You would need an oscilloscope to be able to read that voltage.

So what is my multimeter reading? It just keeps going up and down. It ranges between 0 and 5.

Are you actively pinging at the time? Then you may be seeing it react to the pulses.

Yes it's fully pinned. 5v source. So when it reacts to the pulses, it changes the bolt reading? Since the max reading is 5v, does that mean that my resistors aren't placed properly since the voltage max didn't drop?


text:
How to use H3LIS331DL 3-Axis Linear Accelerometer with arduino to detect Harsh braking of vehicle
I am a newbie here, Recently I was working with H3LIS331DL 3-Axis Linear Accelerometer I²C Mini Module
Here is code for the X, Y, Z-axis.
 #include <movingAvg.h>
 #include <Wire.h>

// H3LIS331DL I2C address is 0x18(24)
 #define Addr 0x18

       movingAvg xAxisAverage(5);

       int readingIndex=0;
       int readingArray[10];
       int firstFiveReadingAverage;
       int lastFiveReadingAverage;

    void setup()
   {

      // Initialise I2C communication as MASTER
         Wire.begin();
     // Initialise Serial Communication, set baud rate = 9600
        Serial.begin(9600);

    // Start I2C Transmission
       Wire.beginTransmission(Addr);
   // Select control register 1
      Wire.write(0x20);
  // Enable X, Y, Z axis, power on mode, data output rate 50Hz
     Wire.write(0x27);
  // Stop I2C Transmission
     Wire.endTransmission();

// Start I2C Transmission
   Wire.beginTransmission(Addr);
// Select control register 4
   Wire.write(0x23);
 // Set full scale, +/- 100g, continuous update
  Wire.write(0x00);
 // Stop I2C Transmission
  Wire.endTransmission();
  delay(300);

   }
 void loop()
 {

   unsigned int data[6];
   for(int i = 0; i < 6; i++)
  {
    // Start I2C Transmission
    Wire.beginTransmission(Addr);
    // Select data register
    Wire.write((40+i));
    // Stop I2C Transmission
    Wire.endTransmission();

    // Request 1 byte of data
     Wire.requestFrom(Addr, 1);
    // Read 6 bytes of data
    // xAccl lsb, xAccl msb, yAccl lsb, yAccl msb, zAccl lsb, zAccl msb
     if(Wire.available() == 1)
       {
       data[i] = Wire.read();
      }
    }
   delay(300);

     // Convert the data
       int xAccl = ((data[1] * 256) + data[0]);
       int yAccl = ((data[3] * 256) + data[2]);
       int zAccl = ((data[5] * 256) + data[4]);

    if(readingIndex<10)
  {
     readingArray[readingIndex]=xAccl;
     readingIndex++;
     if(readingIndex == 10)
  {
    firstFiveReadingAverage=(readingArray[0]+readingArray[1]+readingArray[2]+readingArray[3]+readingArray[4])/5;
    lastFiveReadingAverage= (readingArray[5]+readingArray[6]+readingArray[7]+readingArray[8]+readingArray[9])/5  ;
   if(lastFiveReadingAverage>firstFiveReadingAverage)
    {
     Serial.print("Hardbrake Pressed");
     Serial.println();
    }
     readingIndex=0;
    }
    }

  //int avg = avgAccl.reading(xAccl);
  // calculate the moving average

     // Output data to serial monitor
        Serial.print("Acceleration in X-Axis : ");
        Serial.println(xAccl);
        Serial.print("Acceleration in Y-Axis : ");
        Serial.println(yAccl);
        Serial.print("Acceleration in Z-Axis : ");
        Serial.println(zAccl);
        delay(300);
        Serial.println();

     int average=xAxisAverage.reading(xAccl);

    if (average < -1000)
    {
     Serial.print("Hardbraking: ");
    //Serial.print(average/100.0);
      Serial.print(average);
      Serial.println();
        }
       }

I have changed the code, but values are keeps on repeating when I trigger the hard braking and it keep on repeating even I released the brake.
Here is the output

A harsh braking is nothing more than a strong negative acceleration, so you could compare your accelaration values to a threshold. How is this connected to averaging?

Acutally, I am a newbie in arduino, can you please share me some examples.

Examples of what? Your title and your question seem totally different to me? It is unclear, what you are actually asking

how can I use this sensor to detect the harsh braking of the vehicle using Arduino nano?

A harsh braking is nothing more than a strong negative acceleration, so you could compare your accelaration values to a threshold. Let's assume, that the positive x-axis is the moving direction of your vehicle. This means, that braking will give an acceleration in the negative x direction. Then you first define a specific threshold for the acceleration. An acceleration in the negative x direction above this level means, that it is a "harsh" braking (you will have to test yourself, what value you want for this). Then you test, if the read values are below the negative of our threshold (since acceleration in the negative direction will be presented by negative number).
int braking_threshold=1000;
...
void loop(){
    ...
    // Convert the data
    int xAccl = ((data[1] * 256) + data[0]);
    int yAccl = ((data[3] * 256) + data[2]);
    int zAccl = ((data[5] * 256) + data[4]);

    if(xAccl < -1*braking_threshold){
        // Do whatever you want to do at a harsh braking here
    }
    ...
}

Note, that often the accelerometer data is rather noisy, especially, when mounted on a vehicle, that will vibrate during the motion (due to motors and such). You might need to apply some filter to the read values, before you can use them. That can be as easy as averaging some values, but can also go on to more complex filter algorithms, depending on how noise free you need the data. You will have to test, what values you realistically get in your application and how noisy they are. But data noise reduction is a complete different topic and thus off-topic for this question.
Also note, that your accelerometer measures a range of 200g. That's quite much I would say. When measuring relatively low accelerations the signal to noise ratio will be rather bad. So I hope, that you really want to measure accelerations, that fill this range, rather than only using a very small percentage of the range.

Thanks for the help, I am thinking this way only but not sure how to use. and i thinking to store the values in an array, lets say 5 values stored  and then average of those 5 values is taken and then new 5 values stored and average of those values is taken.After that we will compare the average and this thing is happening in a loop.How to write code for this?

You can google for "moving average". There is plenty of example code on the web and on this site.

Thanx for the help.

I have made this code but when pressing hard brake, then the average value keeps on repeating  itself even I have released it.

You can check the code above..

What do you mean by "keeps on repeating itself"? Please be more clear and add example output with a description, what you have done to get this output

I have uploaded the output above..


text:
Arduino Pro Micro clone clock cycle issue
I have several Arduino Pro Micro clones that are giving me an issue where they work immediately after being programmed while the USB cable is still connected, but as soon as I disconnect and reconnect the USB cable the program fails. I was able to break it down to the simplest form and found that the clock cycle is off by what I estimate to be almost a factor of 10.
For testing, the only command in the loop is Serial.println(millis());. Immediately after programming you can watch the milliseconds scroll by in the serial monitor at the expected rate. Unplug and plug the USB, reconnect the serial monitor and now the milliseconds scroll by at about 1 second interval.
The Arduino IDE version is 1.6.8 and have tested it from both a Mac and Ubuntu with the same results. Also tested on 4 different boards with the same results. I also tested the latest Arduino beta with no change. Next I'm going to download some older Arduino IDE versions.
Any suggestions?

The fix for this issue was to reload the bootloader.  I used the SparkFun Caterina bootloader.

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

authors: ครูวิบูลย์ กัมปนาวราวรรณ


text:
Good Arduino motor drivers
I need some motor drivers that can control a DC motor with 10-15 A and 25 V. I can't find any shield that can do the job. I need to control 4 motors with these.
Can you suggest some models that are good with this?
And one more question: if a driver can control a DC motor in 2 directions, can it control 2 DC motors in one direction each?

The "shield" form factor isn't really a good fit for these power levels.  Likely a suitable driver will be its own unit, which you will have to connect to the arduino with wires.

We don't really answer "shopping questions".
You could contact several suppliers like Adafruit, sparkfun or maybe even Digikey, Farnell etc (ebay?).
If you search for: "15A dual h-bridge" you will find some motor drivers which should work for you.
If a driver can control a dc motor in 2 directions can it control 2 dc motors in one direction each?
Where are you going to use them for?
If you're only going in one direction, you won't need a motor driver.
An MOSFET (per motor) is good enough if you only drive one direction.
If you want both motors to be able to turn each direction, a dual h-bridge will do.

I need to control the speed

You can use analogWrite(pin, value) instead of digitalWrite. The value will be the "on time", so a lower value will make the motor go slower.

Nice but can I output around 25 V?

If you use a MOSFET that's rated for over 25V, yes. You'll also need a 25V power supply.

Think of the MOSFET as an on/off switch controlled by Arduino. But when you use analogWrite() it's more like a dimmer, for different speeds.

I think that the current you need is high and you are not likely to get a shield that does that. Look at a H-bridge with the desired current and voltage rating, it will probable be largish with a heat sink. If the motors are going one way then you may just need a simple mosfet style driver. You should probably look for a module with the correct rating as it will have the correct heat sink, track sizes, connections for your motor power and will probably have a diode to protect stuff from the induction spikes.
The H bridge will probably be fine with the Arduino output and it may have a voltage reg for its logic that you could use to power the Arduino.

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


text:
Generating PWM using Arduino Uno and Simulink (interfacing) pins 5 and 6. What's the maximum frequency?
I am building a boost converter using a mosfet. The mosfet is driven by PWM generated by an Arduino Uno through Matlab Simulink. In Simulink I am giving 10 KHz pulse width 50%. Practically 10 KHz available at pins 5 and 6. Up to how much frequency can pins 5 and 6 handle?

I think the maximum frequency is 4MHz. I wouldn't use pins 5 and 6, as those use timer0, which is already used by millis and delay. You'd better of using pins 9 and 10 which use timer1.

https://www.arduino.cc/en/Reference/AnalogWrite

Just posting a link isn't very useful. What do you mean?

in the above link it states The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz

The implementation of analogWrite uses 490 and 980 Hz, but that doesn't mean you can't use other speeds. You can use a smaller prescaler for the timer being used.

pin 9 and 10 can handle frequency of 10khz.?

Yes. Though you'd have to tweak some of the registers to get this exact frequency. If the frequency doesn't need to be exact you could just change the default /64 prescaler to e.g /1 to get around 30kHz.

PS the maximum PWM frequency is actually 8MHz.

highest frequency achivable using arduino while serially communicating.?

Still 8MHz.....

How much frequency do you need and how many bits of PWM resolution do you need?

1okhz  is designed for boost converter

See my page about timers. The maximum frequency the hardware can output is 8 MHz if you are running a 16 MHz clock.
10 kHz should be easily achievable if you tweak the hardware registers, as Gerben said.

Up to how much frequency can pins 5 and 6 handle?

here is a way for you to find out:
1) pin 5/6 are OC0A and OC0B -> two output compare pins tied to timer0
2) go to the datasheet and timer0 is a 8-bit timer, with a few pwm modes who top out at 0xff or OCR0A -> useless for your application.
So the theoretical but useless answer is 16Mhz/2, at 1:1 prescaler.
the more practical answer is 16Mhz / 256, at 1:1 prescaler.
with that said, some AVRs (ATtiny25/45/85 for example) can run in asynchronous modes generating incredibly high PWM with very little outside help.
if generating high speed pwm is your thing, check them out instead.


text:
How to simply close a tab?
How can one close a tab in the Arduino IDE? There is a Tab button (little triangle) with the Option "Delete"(kind of misleading term). There is no "Close" option. And the "Delete" option doesn't do the job for me either, because the tabs are write-protected, and I just get a prompt.

I don't think you can. The IDE just opens all c/cpp/ino files inside the sketch's folder.

You cannot close a tab in the Arduino IDE.  If a file exists in the sketch then it is there with a tab. Deleting a tab deletes the file.
In the Arduino IDE a tab is a file and a file is a tab. You can't remove one without removing the other.
You might like to check out my IDE, UECIDE, which deals with tabs in a more traditional manner.


text:
Problem with DHT11 and DS18B20 temperature sensors
I am trying to connect to my Arduino Uno board two temperature sensors: DHT11 and DS18B20. The problem is with the DHT11 sensor: apparently there's an error with reading the temperature every two measurements.
Here's what I get on the serial monitor (temperature 1 is from the DHT sensor):

As I am new to this, I was wondering what the problem may be. I have read about the one wire interface used by the DS18B20, but I noticed that the DHT is not using the same protocol.
If I use the DHT11 alone, it works perfectly fine.
Also, I am using 4k7 pull-up resistors for both sensors.
Here's the code:
#include <DallasTemperature.h>
#include <OneWire.h>
#include <dht.h>

dht DHT;

#define ONE_WIRE_BUS 8
#define DHT11_PIN 7

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(void) {
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");
  sensors.begin();
}

void loop(void) {
  int chk = DHT.read11(DHT11_PIN);
  sensors.requestTemperatures();
  Serial.print("Temperature1: ");
  Serial.print(DHT.temperature);
  Serial.print(" Temperature 2 : ");
  Serial.println(sensors.getTempCByIndex(0));
}

Are the OneWire and dht libraries compatible?  They may be using the same resources (for example, the same processor timer).  An easy way to tell is if they work independently.  And you have already proved that the DHT will work if you are not using the DS chip.  Now, if you can explain exactly what you did ... we would have a better idea if there really is a conflict between the two libraries.   Or, you could review the code from both libraries and see if there is a conflict.

I am not really able to understand the code behind those libraries, but as far as I looked I can't really find any conflicts. Here's the link for the OneWire library:
https://github.com/ntruchsess/arduino-OneWire and the link for the DHT library https://github.com/adafruit/DHT-sensor-library

Linked DHT library looks differently then one you use. There is no method read11 for instance. Are you sure you use that one?

My bad, you can download the one I'm using  from here: https://arduino-info.wikispaces.com/DHT11-Humidity-TempSensor

@Darko, you're right, elena is using this project's libraries: https://github.com/RobTillaart/Arduino/blob/master/libraries/DHTlib/dht.h

The latest version has a delay change:  " 0.1.21 replace delay with delayMicroseconds() + small fix ".  You might want to check if you are using this newest version of DHTlib.

If using the latest DHT library doesn't work, you might try printing out your "chk" variable.  There are about 5 defines one for each detected error.  Also you might try to sample the DHT sensor twice in a row then the other.  If the 2nd DHT sample always worked it would point to a comparability problem.

@st2000 I tried sampling the dht sensor twice and I still get the error. http://imgur.com/TaUEjbi . Where did you find the latest version of the library?I couldn't find the one with the update you mentioned

Also, I printed the chk variabile and its value is 0, which means everything is ok..

That is really odd, every 3 samples of the DHT sensor is good.  Did you notice that?

@st2000: the dht11 sensors are pretty slow, i've read they can only deliver data every other second, or so.

@jogco, Wow, now that I know what I'm looking for, there is evidence for this all over.  And in the Adafruit version of the DHT11 Arduino library there is this: "...Check if sensor was read less than two seconds ago and return early to use last reading."

DHT11 can only be read every 1 second. See manual.

Would you mind linking to the manual you're mentioning and provide exact reference within it for the "1 second" you mention?

There appears to be several DHT sensor Arduino libraries available:

niesteszeck/idDHT11
adafruit/TinyDHT
adafruit/DHT-sensor-library

You might try an alternate library to see if that solves your current problem.  Note, some if not all of these libraries need to know which DHT model you are using.
Before going through the DHT and OneWire source code line by line looking for conflicts, try to narrow down what is causing the problem:

Try only instantiating the OneWire class and skip calling the read method within the class.

If this works, then the conflict likely resides in the OneWire read method and not in the OneWire initialization code (that is, the OneWire's Constructor).

Calling the DHT read method multiple times consecutively to see if the problem resolves it self.

Actually, you have done this and exposed a curious patter of good-bad-bad-good-bad-bad... which is worth looking into.  The point here is that if only the 1st call to the DHT read method after a call the the OneWire read method was bad, then there might be a setup problem in the DHT read method.

Call the DHT Destructor, the DHT Constuctor then make the call to the DHT read method every time you read the DHT sensor.

This is a test case only and an extreme measure.  What you are doing here is re-initializing the DHT library (driver) every time you use it.  If this works it points to an initialization problem where the DHT library is initialization something which should probably be re-initialized again inside the DHT read method.  As the OneWire library is using the same "something" (resource).
One last thing, the OneWire example I looked at here:
PaulStoffregen/OneWire
...did not use the DallasTemperature library.  I doubt this will make a difference, but it is usually best to keep your code simple and avoid unnecessary complexities.
Added later...
As pointed out in the comments, it turns out the DHT11 only takes new readings every few seconds.  Guessing, the DHT11 library you are using either knowingly returns an unreasonable value of -999.0 until this time passes.  Or is returning exactly what the DHT11 reports which, again, is an unreasonable value of -999.0.
In this DHT11 library, there is code:
boolean DHT::read(bool force) {
  // Check if sensor was read less than two seconds ago and return early
  // to use last reading.
  uint32_t currenttime = millis();
  if (!force && ((currenttime - _lastreadtime) < 2000)) {
    return _lastresult; // return last correct measurement
}

...which returns the last good value for 2 seconds after a DHT11 "real reading" should the library user call upon it faster then the DHT11 can respond.

To confirm the answers above, in my case https://github.com/adafruit/TinyDHT library worked fine with Arduino Uno, while http://playground.arduino.cc/Main/DHTLib refused to work. Same setup with DHT11 and DS1820.


text:
LinkNode D1 Serial stops working when using pinMode
The following code works. I get an output in the console every second of "Hello" and then the analogValue of the photoresistor.
int greenLedPin = D1;
int yellowLedPin = D2;
int redLedPin = D3;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  Serial.begin(9600);
//  pinMode(greenLedPin, OUTPUT);
//  pinMode(yellowLedPin, OUTPUT);
//  pinMode(redLedPin, OUTPUT);
}

void loop() {
  analogValue = analogRead(lightSensorPin);
  Serial.println("Hello.");
  Serial.println(analogValue);
  delay(1000);
//  digitalWrite(greenLedPin, HIGH);
//  digitalWrite(yellowLedPin, HIGH);
//  digitalWrite(redLedPin, HIGH);
}

Now as soon as I uncomment the pinMode commands nothing shows up on the console.
int greenLedPin = D1;
int yellowLedPin = D2;
int redLedPin = D3;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  Serial.begin(9600);
  pinMode(greenLedPin, OUTPUT);
  pinMode(yellowLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);
}

void loop() {
  analogValue = analogRead(lightSensorPin);
  Serial.println("Hello.");
  Serial.println(analogValue);
  delay(1000);
//  digitalWrite(greenLedPin, HIGH);
//  digitalWrite(yellowLedPin, HIGH);
//  digitalWrite(redLedPin, HIGH);
}

Any idea what might be going on?

Does it happen when only one of the Dn pins is uncommented?  (I'm thinking the definition of Dn might be to the wrong GPIO pin)  - I'll test you code when I get home to see if I get the same result.

Move int greenLedPin = D1; and int redLedPin = D3; to another pin, because D1 and D3 is Tx and Rx.

http://esp8266.github.io/Arduino/versions/2.0.0/doc/reference.html

Would plugging things into the D1 and D3 pins like LEDs cause this sort of weirdness to happen? My problem eventually became the chip completely ignoring any changes in my sketch. Editing the sketch or even uploading a completely different sketch resulted in the chip simply running the same old code every time.

FYI here is an image of the LinkNode D1: https://m.media-amazon.com/images/S/aplus-seller-content-images-us-east-1/ATVPDKIKX0DER/A2TOL213PF2CAG/B01DD641G6/pdmYH3IESLKD.UX970_TTW_.png
D1 is marked as "TX->D1" and D2 is "D2" and D3 is "D15/SCL/D3", so D3 isn't RX0

https://s3.amazonaws.com/linksprite/Linknode+D1/LinkNode-D1-sch.pdf
Shows pin 15, 16 (D1, D3) is connected to the USB/Serial IC.
And YES, the old code interrupts the upload of the new code. A solution is to press the reset button before the Arduino IDE shows "Upload code", this will put the ESP-12 into programming mode.

I actually did hit the reset button right after compiling but before the IDE showed Upload Code. Same result.

Sorry the correct procedure is: Connect LinkNode D1 to your PC. Press and hold the Reset button, and then Connect D8 (Flash) to ground (GND). Release the Reset button, and then disconnect D8 from ground. And now its in programming mode.


text:
Arduino nano does not draw enough power
I am trying to run a sensor from my switch using POE. I have created a temp/humidity sensor using the MySensors directions https://www.mysensors.org/about/arduino.  I decided to use a nano due to the USB connector. I have connected this to my switch via a TP-Link POE splitter set to 5 volt output.
When connected, the switch provides power for a second or two then turns off for 10 seconds or so before coming on again. I believe the Switch is testing the circuit not detecting enough power being drawn and shuts down. It then goes through the cycle again. Note: both the power LED on the switch and the nano LEDS light up while power is supplied. I believe the nano itself only uses about 20mA
I have tested with another device that requires 9volts (hand held phone) via the splitter and it works fine with power provided consistently.
I was wondering if there is some circuitry I can add before the Arduino that will draw a little more current but still provide a constant 5V to the nano.
Additional information. The switch is a Linksys LGS124P. I have tried to find more detail regarding the required power but can only find this datasheet that does not provide that level of detail
http://downloads.linksys.com/downloads/datasheet/1224699456700/25685_LINKSYS_unmanaged_POE_switches_PROD_Revised.pdf

First you need to work out exactly how much current needs to be drawn in order to make it stable. For that you really want an adjustable dummy load with current display. When you know how much current you can calculate the right size of resistor to use across the supply to draw the amount of current without wasting current or overheating and burning.

You may alternatively find the specification in the manual for the switch, but since you don't tell us what the switch is we can't help you there. Also this is not an Arduino question but a general electronics question. It should be on EE.SE.

A resistor or a light bulb in parallel with the Arduino will increase the power consumption.

Combination of this and Majenko's comments give me the answer I need. thanks


text:
How to connect RedBearLab BLE shield (Or how to find Nordic_nRF8001.h)?
I am trying to explore the possibilities of connecting an Arduino to Phonegap/Cordova. I have a RedBearLab BLE Shield, which I want to test the connection with. My MVP would be to get the value of a PIN to a Cordova app. Nevertheless, I couldn't make it even close.
The closest I got, it was using Don Coleman's Phonegap plugin.
I am trying his Simple Chat example.
With this example the sketch is attempting to include Nordic_nRF8001.h. Nevertheless, I can't seem to find this library. I downloaded it from various sources, but no matter what I do, my sketch still can't find the file.
The only way I could make it work was via CodeBender, but then the readings were a bit of a mess.
I'm not expecting anyone to do all the work for me, so if you can help me in one of the two directions, it would be awesome:

Figure out why I can't find that Nordic_nRF8001.h file.
Or help me find another method of BLE communication.

Later edit
Using the examples that come with RBL library, I figured out the name of the files I need to use. Now I'm running into another problem for which I opened a new question.
Thank you!

I tried using the web editor. There I could find the SimpleChat example, with the correct names of the libraries. They work perfectly.

The scrambled characters issue was because of the wrong Baud Rate.

I used Arduino Create Web Editor to load the SimpleChat example. It loads with these libraries, and it works perfectly:
#include <SPI.h>
#include <EEPROM.h>
#include <boards.h>
#include <RBL_nRF8001.h>

Thanks,
Andi


text:
Why does this array have stored values in it even though I have not put any values in it?
void alarm() {
  char keypressed4;
  char keypressed5;
  char keypressed6;
  char keypressed7;
  char disarmcode1[5];
  Serial.println("hi2");
  Serial.println(disarmcode1);

The array gets declared here and I print the values in the empty array. In the serial monitor I read this:
hi2
"c

I don't know why or how these values get put into the array. I have code later on that puts values into the array, but from where that point in the code is, no values should be in the array
Also I have an LCD screen hooked up too, and it prints a value of 0 at (2, 0).

That is why you usually initialize stuff with = 0 and = { 0 } for arrays respectively.

The values haven't been "put" in the array. The array has been located in memory where those values (left over from some earlier operation, possibly as part of a function's stack frame) happen to be.
The simple fact that you haven't put anything in there means that what was there before hasn't been changed.

How would i clear a array of these values or make them equal NULL then. im aware of in java you can declare they array with its values and make it equal null but null works differently in the C language

while (keypressed4 == NO_KEY) {
keypressed4 = keypad1.getKey();
}
Serial.println("hi2");
if (keypressed4 != NO_KEY) {
disarmcode1[0] = keypressed4;
lcd.setCursor(0, 0);
lcd.print(keypressed4);
}                                                                                after the serial.println disarm code is this and i need a clean array for this portion of the code to work how would i achieve this?

You can use memset: memset(discarmode, 0, 5); which sets the 5 bytes of memory to 0, or you can use an initialisation list: char discarmode[5] = {0}; or explicitly for all values: char discarmode[5] = {0, 0, 0, 0, 0};

void alarm() {
char keypressed4;
char keypressed5;
char keypressed6;
char keypressed7;
char disarmcode1[5]={0};
Serial.println("hi2");
Serial.println(disarmcode1);
while (keypressed4 == NO_KEY) {
keypressed4 = keypad1.getKey();
}
Serial.println("hi2");
if (keypressed4 != NO_KEY) {
disarmcode1[0] = keypressed4;
lcd.setCursor(0, 0);
lcd.print(keypressed4);
}
okay so this portion from the while loop to the if statment happens 3 more times to record 4 values which will be compared to a code example 1234, == keypad recorded values of 1234.

i did this in a earlier function in the code and it worked prefect. by changing the  char disarmcode1[5]; to char disarmcode1[5]={0}; it now apperares as blanks which is good. but i no longer can record values for the input and it leads for the value of the array after recording to hi2
hi2
hi2
hi2
1!N *** this happens after the 4 keypad values should have been recorded it skips right by it and outputs this

You have a fresh array every time the function is called. Make the array static so it only gets made once.

local arrays are not initialized. Reading uninitialized values is Undefined Behavior.
Practically this means that when read they will interpret the bytes at their memory location as values which can result in anything.

Ad to existing answers, while the default behavior of reading unassigned non-instance and non-static memory (e.g. local array) is undefined, you can use slightly different C++ declaration which is defined as initialized to all zeroes:
char disarmcode1[5] = {};

or in pure C
char disarmcode1[5] = {0};

An obsolete syntax for GCC even allows define ranges and their values for array initialization.


text:
Why are Arduino clones cheap?
You can buy Arduino Nano v3 clones from Alibaba at the cost of roughly $2-$3.
I have calculated the cost for fabricating and all the parts in the BOM for Arduino Nano V3, and it ended up costing around $10 to $12 (depending on where you fabricate the board, buy the components and purchasing volume - assuming less than 100 units).
However, how are Chinese clone manufacturers able to slash the price so much it's only ~1/10 of the BOM cost.
Could it purely be due to economy of scale, lower fixed costs (cheap labor), low quality parts (How do you define low quality parts)? Or are there other factors at play as well?

Most costs are cut via labor price. China is much much much cheaper than EU or USA.

All the factors mentioned in the question apply to make the cost so low.  However, with an exception or two as noted in the next paragraph, “low quality parts” is not much of a factor, as explained in two paragraphs after that.
Possible low quality parts include the USB mini-B socket, crystals or resonators, and the reset switch.  The socket and switch contain metal shapes that can be well made or badly (and more cheaply) made.  Those badly made will function but may have shorter lives and higher failure rates.  For example, the USB cable fit may be loose, or the switch may fall apart.  Crystal or resonator accuracy and stability can be poor while still allowing a Nano clone to appear to function ok.
However, SMT (surface mount technology) or SMD (surface mount device) parts on the board cannot be made significantly more cheaply than can good parts.  SMD LEDs, resistors, diodes, voltage regulators, and capacitors come off of automated assembly lines with little or no manual intervention.  See, eg, ceramic capacitor manufacturing at wikipedia.  Parts are automatically packaged into sealed reels of parts suitable for use on an automatic pick-and-place machine that populates PCBs.  In short, the dozen 0603-size SMD LEDs, resistors, and caps, and the nine other passive or small-scale-integration SMD parts on the board will cost about the same coming off a bad manufacturing line as from a good line, so there is little profit to be made producing bad parts.  The 20-odd passive parts probably cost a couple of cents, at manufacturing scale.
Active SMD parts like voltage regulators, the ATmega328P, and the 32U4 or CH340, likewise come off automated manufacturing lines.  As these parts are more expensive, there is more economic incentive for cheating, and from time to time fake parts get sold and used.  In the past (and perhaps still) there have been manufactories that specialize in removing labeling on the tops of cheap or non-functional chips, and putting accurately detailed fake labels for expensive chips on instead. (For example, NCP5318 buck regulators relabeled as ATmega328s.)  In short, most of the active SMD parts on a Nano either are genuine and work or obvious fakes that don't work and earn their sellers bad reputations or jail.
The CH340g USB-to-serial chip  vs. ATmega32U4 USB issue is more complicated.  Ie, some may think of the CH340 as a lower quality part than a 32U4.  The CH340 may need a different USB driver than the 32U4 and may not support 57600 BPS serial in some cases. 1, 2.  The ATmega32U4 seems to be available on Alibaba for $0.10 to $.20 in moderate quantities.  I think the CH340g is made only in China and is somewhat cheaper than the ATmega32U4, so its contribution to the BOM total cost may be a few cents.
The PCB probably costs 5 to 10 cents, and assembly is free except for amortized costs of pick and place machines and an IR reflow system with a conveyor.  Boards probably are processed (components placed and soldered automatically) in panels of several dozen units, tested automatically, and then separated for packaging.
Summary: Inexpensive parts and automated processing hold down the per-board costs, moreso than cutting corners on component quality.  Corners may get cut on assembly quality and on quality assurance inspections.

There are quite a few places where fabs can cut corners. Safety of the workers is one of them. Using a cheaper chip may mean just that. Also support for customers of such ICs is often shoddy.

And PCB factory uses a fair bit of water; look at this part of the process. So water pollution is another way to cut costs.

@RespawnedFluff, those comments are true, and might be part of the reason for PCBs costing under 6 cents per square inch in China, so a Nano PCB is under a dime.

@RespawnedFluff, as for support to customers, I don't know how much support you would expect from a more expensive chip. The chip manufacturer didn't sell (directly) to you, and you only bought one. I don't think Atmel would be particularly interested if you or I have a question about them.

@AMADANONInc.: That is true that as individual consumer you cannot expect much in the way of personalized attention from a big corp, however documentation and drivers are part of what I consider support. And if you visit EE.SE you'll questions about more or less obscure chips that people bought but can't figure out how to use... because the documentation is either completely lacking or perfunctory/incomprehensible.


text:
Issue in installing Arduino unit library and running with Firmata test application
I am trying to update the Arduino library via the library manager and I tried to download it from the link given in the firmata_test program:

WARNING: Category '' in library ArduinoUnit is not valid. Setting to
  'Uncategorized'
  C:\Users\SAURAB~1\AppData\Local\Temp\arduino_c8217a5b56c170d64dfe4c80a1a205dc\firmata_test.ino:
  In member function 'virtual void test_beginPrintsVersion::once()':
C:\Users\SAURAB~1\AppData\Local\Temp\arduino_c8217a5b56c170d64dfe4c80a1a205dc\firmata_test.ino:32:3:
  warning: narrowing conversion of '249' from 'int' to 'char' inside { }
  [-Wnarrowing]
};
^
Multiple libraries were found for "Firmata.h"  Used:
  C:\Users\saurabh2836\Documents\Arduino\libraries\Firmata  Not used:
  C:\Program Files (x86)\Arduino\libraries\Firmata

I'm getting this error. I searched but found no conclusive answer. I'm using Windows 8 64bit and Firmata downloaded from http://www.firmata.org/.
Am I doing something wrong?

The compiler is giving a lot of information. The warnings can be ignored but the "multiple libraries" indicates that there is at least two copies of Firmata installed. Check (search) that you have not got several downloads of Firmata. Worst case reinstall to clean up that.
Cheers!

but what about Category '' in library ArduinoUnit error what are the step to replace adruino unit library

That is from the library manager when reading the library.properties file. The category tag is not correct (actually missing) for ArduinoUnit. https://github.com/mmurdoch/arduinounit/blob/master/library.properties. It is a warning and can be ignored.

but i am not able to run the program for test firmata after reinstall it

But does it compile? This issue was about compiling it. Are there still compile warnings and errors? Did the "multiple libraries..." link error disappear? I was assuming that you had an installation problem.

no still the same issue

You have to remove one of the two libraries. Currently there is two copies of the library installed. Both get located and compile (according to the error message from the linker).

Did you still get: "Multiple libraries were found for "Firmata.h" Used: C:\Users\saurabh2836\Documents\Arduino\libraries\Firmata Not used: C:\Program Files (x86)\Arduino\libraries\Firmata". The compiler is telling you where the two libraries are. Remove one of them.

i solved the issue of library loading double but now that firmata test program is not working i am not able to controller high/low from firmata to arduino


text:
Digispark ATtiny 85 erases flash after power loss
I have some issues with my Digispark ATtiny85 board.
If I upload the blink sketch for example the LED starts blinking and everything looks fine. But as soon as I unplug the Digispark from the USB port and plug it back in nothing happens. I know that the programm starts with a delay of 5 seconds so programming via USB becomes possible, but still nothing. Its seems like the flash-memory (where the programm is stored) of the ATtiny 85 is empty.
Here is the example blink sketch:
// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(0, OUTPUT); //LED on Model B
  pinMode(1, OUTPUT); //LED on Model A
}

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

I also tried uploading the sketch from a Laptop running on Windows but without success.
I am using Linux Mint and Arduino IDE 1.8.10.
Since I am new to Microcontrollers, I would be grateful for explainations, tipps or useful links.
Thank you!

How is the eeprom used? Or you're confusing program memory (flash) with eeprom? The programmer selection is for flashing code (or bootloader by next menu item) into it over ISP connection using some programmer.

The code is saved in flash, not in EEPROM. The blink sketch does not use the EEPROM. So the actual problem is: You have a running blink sketch, but if you unplug the digispark and again plug it in, the blink sketch isn't running anymore?

Or could a floating reset pin be the reason for this behavior? the official digispark has the reset pin disabled, so you get an extra GPIO pin. So it can't be a floating reset pin.

Okay I confused flash with EEPROM. Thanks for pointing this out, I will change that in the question. @chrisl Yes that's my problem

I found that on the digistump forum: "I get the same behavior, except Arduino 1.6.5-r5.  5 boards all exhibit the same behavior.  These do not say "Digispark" on them; just "ATttiny" (85"https://digistump.com/board/index.php?topic=3161.0)
Might this problem be related to the arduino IDE?

I got the same issue, on two boards. Will probably try to burn the bootloader using usbasp, maybe they burned the wrong one back in china.

I got the same issue, on two boards. Will probably try to burn the bootloader using usbasp, maybe they burned the wrong one back in china.
EDIT:
As expected flashing the micronucleus bootloader using USBasp solved the problem on both of the boards. I've used burn-o-mat as the arduino was not seeing my programmer.
Just download the firmware from github (I've used this: https://github.com/f4goh/micronucleus/archive/master.zip )
and connect like so (here the guy is using arduino uno, doesn't matter): https://hamprojects.wordpress.com/2018/12/27/digispark-microcontrollers-implementation/


text:
Arduino Mega Wifi Shield Timeout Error
I got an Arduino Mega(not original) and also a Wifi shield, when ever I try to upload my code to it, I get this error:
Sketch uses 5504 bytes (2%) of program storage space. Maximum is 253952 bytes.
Global variables use 704 bytes (8%) of dynamic memory, leaving 7488 bytes for local variables. Maximum is 8192 bytes.
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
An error occurred while uploading the sketch

Without the shield on it works perfectly, but as soon as I plug it in it stops working, I tried uploading the code without shield and placing the shield but this way the serial port didn't work.
The shield I bought is:
ESP8266 ESP-12E UART WIFI Module Wireless Shield Converter For Arduino UNO Mega

Edit:
If there is anything connected to the arduino it wont upload, it is not just the shield, I can't get my OLED to work either. Also tried using the shield on my UNO and I get the same result.

The error usually means that there is a basic comms problem between the board.  If the Mega works without the shield this implies that the shield is interfering with serial port 0.  I'm assuming that the "debug port" is linked to the ESP, is that correct?  Do the dip switches affect how the serial port is treated?

@CodeGorilla I tried changin the dip switch but nothing changes.

via Google I found this helpful site which has an answer that might help.  It is not the same question as yours, but it explains what the dip switches are for
How to connect Wi-Fi shield ESP-12E-ESP8266-UART-WIFI-Wireless-Shield with Arduino
It seems that IF you have what is pictured a 'shield' version of the board, as opposed to a 'shaild' version, then when you plug it in to an uno it will stop the uno working, because of the serial connection from the ESP on shield pins 0 and 1.  I don't know where these pins are going on your mega, but it might be the same issue.  This page recommends bending the pins out the way and wiring them to other pins - Which is at your risk.  You could trial it by wiring the whole shield to the mega and seeing if it worked.
https://claus.bloggt.es/2017/02/26/arduino-esp8266-wifi-shield-elecshop-ml-by-wangtongze-comparison/


text:
Weird arduino bug, using microphone and relay
I made a clap light switch to control my room lights and ground LEDs, and it works perfectly but when ever I have both the LEDs and the lights on it kinda stops working.
I use two claps for the lights and three for the LEDs.
Does anyone know what could be wrong? here is my code.
/* DEFINE PINS */
const int buzzer = 2;
const int micPin = 0;
const int relayLED = 9;
const int relayLights = 8;

const int sampleWindow = 50;
const int N = 50;

unsigned int sample;

boolean lights = false; //lighs on or off
boolean leds = false; //leds on or off

double soundArray[N]; //array to check claps

int i = 0;
int clapsCount = 0;

void setup() {
  pinMode(relayLED, OUTPUT);
  pinMode(relayLights, OUTPUT);
  digitalWrite(relayLED, HIGH);
  digitalWrite(relayLights, HIGH);
}

void loop() {
  /* gets 50 constant sound sample and resets */
  if (i<N) {
    soundArray[i] = getVolts();
    i++;
  } else {
    i = 0;
  }
  if (i == N-1) {
    clapsCount = clapCount(soundArray);
  }

  /* if 2 claps detected do this */
  if (clapsCount == 2) {
    if (lights == false) {
      turnOnLights();
      lights = true;
    } else {
      turnOffLights();
      lights = false;
    }
    playSound();
    clapsCount = 0;
  }

  /* if 3 claps detected do this */
  if (clapsCount == 3) {
    if (leds == false) {
      turnOnLeds();
      leds = true;
    } else {
      turnOffLeds();
      leds = false;
    }
    playSound();
    clapsCount = 0;
  }
}

int clapCount(double soundArray[]) {
  int claps = 0;
  for (int j=0; j<N; j++) {
    if (soundArray[j] > 3.0 && soundArray[j] < 3.5) {
      claps++;
    }
  }
  return claps;
}

void turnOnLights() {
  digitalWrite(relayLights, LOW);
}

void turnOffLights() {
  digitalWrite(relayLights, HIGH);
}

void turnOnLeds() {
  digitalWrite(relayLED, LOW);
}

void turnOffLeds() {
  digitalWrite(relayLED, HIGH);
}

/* gets mic volts */
double getVolts() {
  unsigned long startMillis= millis();  // Start of sample window
  unsigned int peakToPeak = 0;   // peak-to-peak level
  unsigned int signalMax = 0;
  unsigned int signalMin = 1024;
  // collect data for 50 mS
  while (millis() - startMillis < sampleWindow)
  {
    sample = analogRead(micPin);
    if (sample < 1024) {
       if (sample > signalMax) {
          signalMax = sample;  // save just the max levels
       }
       else if (sample < signalMin) {
          signalMin = sample;  // save just the min levels
       }
    }
  }
  peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
  double volts = (peakToPeak * 5.0) / 1024;  // convert to volts
  return volts;
}

void playSound() {
  tone(buzzer, 1000);
  delay(100);
  tone(buzzer, 500);
  delay(100);
  noTone(buzzer);
}

Edit:
When I do both two claps and three claps, both lights turn on and no matter how many times I clap none of them turn back off.
Edit 2:
Components I am using are, a simple buzzer, and microphone called MAX4466 and a 5v relay with two outputs.

Please edit your question to explain exactly what you mean by "kinda stops working".

@per1234 edited now, sorry about that.

We need to know what these devices are and how they are connected. The code listing has some issues, but we can't do a good answer without the hardware info. Like, are you using an actual microphone, condenser, piezo, what? I suspect your method of identifying a clap isn't working how you think it is.

Apologies again, I edited it one more time with the other information.

This scheme of clap counting does not seem sufficiently though through to work at all - first, you evaluate in a buffer and then throw everything away, so you'd have to luck out and get all your claps in a buffer, and not some in an old one that gets throw away and the rest in the next.  But more importantly, you don't seem to ever implement anything that looks for a sharp sound and then a gap.  You basically need to start over with a plausible algorithm - you need to count sounds with intervening gaps, and then act only when theres been a long enough gap to mean no more will follow.

I've looked through your code and can't see anything obvious that is causing the problem, so I have refactored it a bit in the hope that the problem becomes more obvious.
/* DEFINE PINS */
const int PinBuzzer = 2;
const int PinMic = 0;
const int PinRelayLED = 9;
const int PinRelayLights = 8;

const int sampleWindow = 50;
const int MaxSamples = 50;

// Simple enumeration to clarify which state is on and off.
enum EOnOff { Off, On };
EOnOff lights = Off; //lights on or off
EOnOff leds = Off; //leds on or off

double soundArray[MaxSamples]; //array to check claps

void setup()
{
    pinMode(PinRelayLED, OUTPUT);
    pinMode(PinRelayLights, OUTPUT);
    digitalWrite(PinRelayLED, ConvertOnOff(leds));
    digitalWrite(PinRelayLights, ConvertOnOff(lights));
}

void loop()
{
    for (int sample = 0; sample < MaxSamples; ++sample)
    {   // Get the samples
        soundArray[sample] = getVolts();
    }
    switch (clapCount())
    {   // Analyse the samples
    case 2:
        lights = ChangeRelay(lights, PinRelayLights);
        playSound();
        break;
    case 3:
        leds = ChangeRelay(leds, PinRelayLEDs);
        playSound();
        break;
    }
}

/// Count the number of 'claps' in the sample data
int clapCount(/*clap array is global*/)
{
    int claps = 0;
    for (int sample = 0; sample < MaxSample; ++sample)
    {
        if (soundArray[sample] > 3.0 && soundArray[sample] < 3.5) /* Why 3.5?? */
        {
            ++claps;
        }
    }
    return claps;
}

/// Convert an EOnOff value to a HIGH or LOW value.
// OFF = HIGH
int ConvertOnOff(const EOnOff& state)
{
    return state == Off ? HIGH : LOW;
}

/// Change a relay to the given state.
/// Return the new state.
EOnOff ControlRelay(const EOnOff& state, const int& relayPin)
{
    EOnOff result = state == On ? Off : On;
    digitalWrite(relayPin, ConvertOnOff (result));
    return result;
}

/* gets mic volts */
double getVolts()
{
    const unsigned long startMillis = millis();  // Start of sample window
    unsigned int signalMax = 0;
    unsigned int signalMin = 1024;

    unsigned int sample;
    // collect data for 50 mS
    while (millis() - startMillis < sampleWindow)
    {
        sample = analogRead(PinMic);
        if (sample < 1024)                  // ?? Should this be 1024 or signalMin?
        {
            if (sample > signalMax)
            {
                signalMax = sample;  // save just the max levels
            }
            else if (sample < signalMin)
            {
                signalMin = sample;  // save just the min levels
            }
        }
    }
    const unsigned int peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
    const double volts = (peakToPeak * 5.0) / 1024.0;       // convert to volts
    return volts;
}

void playSound()
{
    tone(buzzer, 1000);
    delay(100);
    tone(buzzer, 500);
    delay(100);
    noTone(buzzer);
}

What I have tried to do is to reduce the number of lines of code.  If there are less lines then there should be less bugs :)
You used a bool to record the on off state, I changed that to an enumeration because that adds a bit of clarity, and when working with mains voltages I like things being clear.
I changed your while loop into a for loop, I think it looks cleaner.  This was also the reason I changed your if statements into a switch statement.
The guts of the if statements have been removed and placed in a function ChangeRelay(), it returns the new state of leds or lights.  I could have gone with a reference to make state an in out parameter, but decided a return was simpler.
ClapCount() and GetVolts() are relatively unchanged apart from a bit of const'ing of variables to make things easier to read.  Also you might have noticed I, j and N have all been removed, because single letter variable names are my nemesis, who knows what q means and why r and t are being added to it to make z?
ControlRelay lets you route all you relay switching through one function, if there was a copy and paste bug in your code (which I don't think there was) then they will either all work or not work now.
There is a big difference between "my" code and yours, you won't be able to switch both on at the same time because the switch statement won't let you.  So in a way you problem is solved.  If you really wanted to you could add:
case 5:
    lights = ChangeRelay(lights, PinRelayLights);
    leds = ChangeRelay(leds, PinRelayLEDs);
    playSound();
    break;

Thank you for making the code better!
I tried it and it works just like mine, but the bug still happens, I am not sure if  it is a limitation of the relay, if both lights are on it does not turn off no matter what.
And yeah I know the single letter variables are bad, I normally use only single variables like i, j, k for the for loops, but since I was just testing I got some weird ones with single letter too.

I tried using the serial read to type 2 or 3 as simulation of the claps and it works perfectly fine, got both on, turn off each at a time all perfect, but when ever it is claps it doesnt seem to work, maybe my algorithm to get the claps is bad.

@Matthew - In getVolts the else if should be just an if.  Otherwise you need two samples to adjust the max and min to the correct values.


text:
can we use Software serial and timer one at the same time or this software use also timer one?
i am using timer1 and software serial for gps data i need to see if we have a problem with connection .
So i made a timer1 that's start before the loop that will wait the gps sending and after 3s if we didn't receive data we will exit the loop of waiting and going to make diffrent thing .

Doesn't sound like you would need to configure an extra timer for that. Have you thought about using millis()?

a timer conflict on AVR creates a compilation error.


text:
Is it possible to overload the digital pins for an Arduino?
I worked on an Arduino project for school that was a self-driving security robot that also acted as a smart home system.
It was essentially a self-driving Roomba-like car that included several LED's(resembling home appliances), three distance sensors, an LCD screen, a motion sensor, an audio amplifier with a speaker, an SD card module to store .wav files, a Bluetooth module to connect with MIT App Inventor, and a motor driver that controlled two electric motors. It's a long list of modules so the Arduino Mega was required. When assembling all of these modules and building the code, I would perform intermittent tests that would isolate the obstacle avoidance and driving, turning on appliances(LED's), and sending and receiving data from the phone app. Every aspect of the project worked in isolation until I combined everything.
When everything was combined, instead of simply driving forward until an obstacle is detected as its programmed, the car would jitter around and not react to walls or obstacles. Also, the LCD screen was heavily dimmed as opposed to when the Arduino was running off of laptop power. Especially when the phone app called for turning on heat or AC, the proper LED's would turn on, but the whole system seemed to respond to the initial load required to read a .wav file and play the corresponding audio and made the jitter worse.
So my question is this, with all these modules plugged into an Arduino, is it possible that the number of modules all needing some input from the digital pins has highlighted a current limitation? All of these issues were exacerbated when the laptop power was replaced with a 9v battery. I was able to confirm that the code was not the issue as I would simply comment out major portions but leaving all the pins initialized. Also, if there is a current output limitation, is there any way to explain why? Thank you for reading my lengthy post and for giving feedback.

what kind of a 9 V battery are you using?

Is the battery one of these 9V block batteries, that are also often used in smoke alarms? You cannot use these batteries, since they are not able to provide enough current. They are for low power applications. And how are all the modules and motors powered? All through the Arduino 5V pin?

It's a 9v block battery, I did some research and found a simple connector that was apparently made for Arduinos. Actually, I thought that maybe it didn't supply enough current initially, so I jumped two of these 9v batteries in parallel with one another hoping to boost the current output. All the modules I listed are powered via the 5v pin I connected to the breadboard and the digital pins do all of the driving and data stuff.

a 9 V block battery consists of six AAAA cells ... try using six AA or six C cells

Hope you're not connecting it all over the onboard 5V voltage regulator. With higher currents from AA/C cells and lots of sensors, motors and so, it'll be quite hot or even shutting down

All the way through this essay I was thinking "It's a 9V battery... it's a 9V battery..."  ... and it was.

As mentioned in the comments, you cannot power your robot from a 9V block battery. These are made for low power projects (like a smoke detector) and cannot provide enough current to drive even only the motors correctly. Using 2 of them does not really help much. You need to change to a different battery type. If you want to stay with alkalines, you could use six AA batteries or C cells, like jsotola suggested. But you might want to upgrade to a fitting LiPo/LiIon battery (in combination with a fitting battery charger module). That would give you enough power for all your needs, while being rechargable.
A different issue: It seems to be, that you provide all the components (sensors and motors) with power through the 5V pin of the Arduino. But especially with motors you can easily reach the current limitation of the voltage regulator on the Arduino. When drawing more current through it, than recommended, the regulator will go in emergency shutdown (with a genuine Arduino; with the cheap clones, the regulator will melt and be destroyed).
Instead you need to be sure, that the drawn current does not exceed the maximum current for the voltage regulator (depends also on the voltage provided). At least the motors should be provided with power parallel to the Arduino, so that the motor current will not flow through the Arduino. It is unclear, how you are controlling the motors. If you are using a motor shield, then look for the terminal for external power supply on it. Most motor shields have them. Depending on the batteries, you will use in future, and on motors and shield, you maybe an directly connect the battery voltage to the shield. Or you need to buy an extra (switching) voltage regulator, which brings the battery voltage down to 5V. In that case be sure, that the regulator can provide the needed current plus some overhead clearance.

Thank you for your input, I included details about the motor driver, not the motors themselves. The motors have their own main power source, an array of 4 AA batteries. It's the Arduino's digital pins that were driving the motor driver.


text:
Data type explanation regarding analogRead of a photoresistor
This is a fundamental question - very new (1st post) and trying to learn.  I have a photocell connected in series with a 10kOhm resistor between 5v & Gnd (to make a voltage divider) and the divided voltage is connected to A1.  In my code, when I specify the datatype as uint8_t I get values around the 200 range, yet when I change the type to uint16_t the values change to 1000 range.  Where should I be looking to understand this behavior?

You should keep it uint16_t.
See: analogRead.
It shows the return value is a 10 bit number, which means a value of 0 to 1023.
If you use uint8_t, which is an 8 bit value, it only can store values from 0-255.
This means if the value is higher, the most significant bits are clipped/removed, and you only have the value module 256 left.
With a 16 bit value, you will have the left 6 bits unused, but this does not matter. It has the 10 bits you get from the analogRead function.
Example
Assume the value is 1000, which is in binary:
11 1110 1000

Written in 16 bits (using uint16_t), move it to the right and prefix with zeros you get:
0000 0011 1110 1000

However, if you try to store this in 8 bits (using uint8_t) you get:
(removed) 1110 1000

Which is the value 232 instead of 1000.
Some guidelines:

Always use a type that fits the value you want to store (in worst case).
If you know for sure your value will be non-negative, use an unsigned type (e.g. uint8_t).
If you want to preserve memory (or good practice) use a value that is not necessarily big (thus if you know a value will never be more than 1023 like in your case, don't use uint32_t).


text:
What does a tilde (~) mean as annotation for a data pin?
When I examine the datasheet for the Arduino Micro (couldn't find the Pro Micro on their site, btw) then I see some data pins annotated with a ~ character, and some are not.
For instance, D9 has a ~ annotation, D8 does not.
What does this annotation mean?

It means the pin can be a PWM output for use with analogWrite().


text:
Arduino error when compiling
When this code is uploaded I get an "Error Compiling". Any help is very much appreciated.
#include <MeetAndroid.h>
#define supplyVolts 6
#define motorVolts 5
#define baudRate 57600
// If you are using a General Bluetooth adapter (available on buildcircuit.net), then, it works with 9600bps baud rate
MeetAndroid phone;
int left = 255; // midpoint
int right = 255;
int pwmLeftPin = 3;  1 int pwmRightPin = 11;
int directionLeftPin = 12;
int directionRightPin = 13;
void setup() {
  pinMode(pwmLeftPin, OUTPUT);
  pinMode(pwmRightPin, OUTPUT);
  pinMode(directionLeftPin, OUTPUT);
  pinMode(directionRightPin, OUTPUT);
  setMotors();
  // use the baud rate your bluetooth module is configured to
  Serial.begin(baudRate);
  phone.registerFunction(setLeft, 'l');
  phone.registerFunction(setRight, 'r');
}

void loop() {
  phone.receive();
}

void setLeft(byte ignore, byte count) {
  int value = phone.getInt();
  left = value;
  setMotors();
}

void setRight(byte ignore, byte count) {
  int value = phone.getInt();
  right = value;
  setMotors();
}

void setMotors() {
  int vLeft = abs(left - 255) * motorVolts / supplyVolts;
  int vRight = abs(right - 255) * motorVolts / supplyVolts;
  int dLeft = (left > 255);
  int dRight = (right > 255);
  if (vLeft < 50) {
    vLeft = 0;
  }
  if (vRight < 50) {
    vRight = 0;
  }
  analogWrite(pwmLeftPin, vLeft);
  analogWrite(pwmRightPin, vRight);
  digitalWrite(directionLeftPin, dLeft);
  digitalWrite(directionRightPin, dRight);
}

Welcome to Arduino Stack Exchange. We hope you find this site useful. In future posts, please format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you. On this occasion I see that @jwpat7 has done it for you.

Where did you get the MeetAndroid library from? It's hard to reproduce your issue if we have to guess at where the libraries are to be found.

http://www.amarino-toolkit.net/index.php/download.html

Take a close look at this line. The compiler will not like that as it does not have the right syntax.
int pwmLeftPin = 3;  1 int pwmRightPin = 11;

Change it to:
int pwmLeftPin = 3;
int pwmRightPin = 11;

This should at least remove the first issue with your code.
Cheers!

@Tom Evans if mikael's answer worked, you should press the check mark next to his answer to reward him with some reputation.


text:
Arduino Uno "MEM CHECK FAIL" error
Just followed a tutorial on how to set up ESP8266 with my Arduino Uno R3. I have a serial connection and get a response of the Arduino but I'm stuck now at chapter "first commands".
I have successfully issued the AT command and also the AT+RST command and got a response. BUT, the response return was "invalid" at its end instead of "ready". Also theres an output "MEM CHECK FAIL!!!"
AT

OK
AT+RST

OK

 ets Jan  8 2013,rst cause:2, boot mode:(3,4)

load 0x40100000, len 1396, room 16
tail 4
chksum 0x89
load 0x3ffe8000, len 776, room 4
tail 4
chksum 0xe8
load 0x3ffe8308, len 540, room 4
tail 8
chksum 0xc0
csum 0xc0

2nd boot version : 1.4(b1)
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

ÃÕMEM CHECK FAIL!!! <<----------------------------- ???
äslrô
Ai-Thinker Technology Co. Ltd.

invalid <<----------------------------------------- should be "ready"

Can anyone explain me what that means? Do I have to (re)flash the firmware? And also - are the instructions all the same? I have bought mine from China but it was sold at the same ESP8266 module on Amazon.

The invalid on the end means that your config on the chip is either corrupted or not set up yet. So that's not part of your memcheck problem

http://www.agcross.com/2015/09/the-esp8266-wifi-chip-part-1-up-and-running/
According to the tutorial it's an undocumented bug with no fix.
If you change the name, baud, and set up the wifi and password you should be good to go


text:
WiFiSSLClient will not connect to servers with LetsEncrypt certificates
I'm trying to send data from an Arduino program to an app running on Google App Engine but WiFiSSLClient.connect() always returns false.
This is despite

the server being up and running;
the code working when the web app was on a different server.

The only possible explanation I can come up with is that the App Engine app uses a LetsEncrypt certificate while the other server was using one by another company.
WiFiSSLClient client;
if (client.connect(server, 443)){
    // Connected to server
} else {
    // Failed to connect
}

Does anyone have any solutions to this problem? I had a look at WiFiClientSecure; it has the ability to set the CA certificate in code but this seems like a bit of a pain.

The solution is to update the certificates the WIFI 101 Firmware Updater tool (in the Arduino IDE).

Install the FirmwareUpdater sketch, as described on the Arduino site.
Select Tools -> WiFi 101 Firmware Updater. Click on the Add domain button at the bottom, enter your domain and click Upload Certificates to WiFi module.

Upload the sketch to your Arduino. It should now connect to the server.


text:
Android, Raspberry, Atmega, SQL communication
Hej there,
I have a small project at home and I'm curious if people have some advice/idea for me. Because I'm not sure if the communication between the different devices is the way to go.
This is my current setup:
I have a Android application running on an Android device (tablet). This Android device can communicate with a MySQL server with a json/PHP. The Android device is receiving data from the database but also writing data to it. The MyQL/web server is running on a Raspberry.
The second device is an atmega328p microcontroller(http://www.ebay.com/itm/2-x-ATMEGA328P-PU-ATMEGA328-MICROCONTROLLER-IC-Free-Shipping-/280994585126) that is sending temperature/humidity to the MySQL server on the Raspberry. The ATmega is communicating through a 433 MHz chipRF(MX-05V). The Raspberry also has a 433 MHz chip RF(MX-05V) that is receiving this data and writing it to the MySQL server.
So actually the ATmega is communicating with the Raspberry and the Raspberry is communicating with the MySQL server.
It is working properly but I'm not sure if this is the way to go. So my question, what are you thoughts of this setup, what would you do different and why?
Thanks, Matthijs

A picture says a thousand words.  I really don't know how to answer you question because I'm not sure what your setup is.  Also people are going to vote to close the question because its not at all clear.  Can you draw a system diagram and try and clarify what you mean by a 433MHz chip (I think you mean a radio, but...)   If the Raspberry (or Pi for short) is running the SQL server then if the ATMega is talking straight to the SQL socket that is different to it talking to a daemon or app which talks to SQL.  Hope that helps, give it an edit and I'll look again :) (I'm meant to say Hi but

I've run out of letters :)

If it is stupid and it works ... it ain't stupid! Though i see how you do it ive done the same some other way, ive used the ESP8266 to transmit the data to the cloud skipping the raspberry pi server and the android app just leaving a website to check the data. Not saying your suggestion is wrong. Just inspiration.

@Magic-Mouse thanks for the responce. My raspberry also have a NRF24L01. This is similar to the ESP8266  i thinks. I use it to communicate with the Milight lights.

@CodeGorilla Thanks for responding, edit the text a bit. Thanks, going to add a classdiagram later.

Not a class diagram, I suspect the code is trivial (no offence intended).  You need a diagram of the 'bits' the exes the hardware, the 'links'.  Don't think like a softie think like a "systems engineer"

What are your concerns? Stability, costs, bandwith, expandability, reliability?

@Paul reliability. Don't want to lose data because I have to mucht incoming data.

If I understand correctly:

You have a Pi hosting MySQL and a web server.
A Mega writes temp/humidity data to the server.
An android device reads data from the web server.
The Pi and the Mega talk over a 433(MHz) radio?

Is it the write way to go?
What you have is a tried an tested design, a central server responsible for collating at serving the data.  My one concern is the 433 radios, I think you might be limiting the scalability of your design by using that.  What happens if you want to add a second Mega to report a different sensor?  You PI needs a second receiver and a second app to read, although the PI will handle 2, easily, there will be a point where it can't handle any more.  I'd suggest that you look at technology that allows multiple nodes on the same network, WiFi.
You could use WIFI by either getting adding a WiFi device to you Mega or ditching the expensive Mega and buying a $2 Wemos D1.
But that's just my opinion, and unfortunately that's the reason this question will get closed, because asking for people's opinions is taboo.

Thanks for the responce, i tested it with 2 atmega's and this works properly. But i can agree on the fact that it can be limited when i want to add more atmega's. I need to test it to see if it still works with for example 5 atmega's.

But why spend $40 on a mega when you can spend $2 on an ESP and program it exactly the same way?

sorry for the confusion.. i mean the atmega328p microcontroller: http://www.ebay.com/itm/2-x-ATMEGA328P-PU-ATMEGA328-MICROCONTROLLER-IC-Free-Shipping-/280994585126

OIC.  I Still reckon this is better http://www.ebay.com/itm/D1-Mini-NodeMcu-4M-bytes-Lua-WIFI-Development-Board-ESP8266-by-WeMos-/182035363514?epid=514207412&hash=item2a622736ba:g:NSYAAOSwe7BWzu4m  :)

https://i.sstatic.net/Uq7w1.jpg on the right u see the atmega with a movement sensor, light sensor, temp and humi. On the left the same only in testing format. I do not know the esp8266. I will check it out. Thanks!

The D1 Mini NodeMcu looks impressive! Thanks for the inspiration!


text:
cheap long lasting options for battery?
I recently made a differential drive using Arduino UNO, two BO dual shaft 9v Motor and ld293d.To power Arduino, I am using a Hi-Watt 9 volt battery, to power the ld293d 5v pin (VCC1) I am using Arduino 5v Vout pin and to power its motor driver pins (VCC2) I am using Hi-Watt 9 volt battery.
The problem is its not long lasting and after moving just a bit like 30 seconds it slows down and stops ,or one of the motor stops working.I have tried this with multiple new 9v batteries, I don't understand why is this happening because the batteries still seems to be work on other projects.Should I use some other kind of battery if yes then what would be the cheapest option?

Don't use the Arduino 5V pin to power motors. Use the battery voltage for the driver. Did you confuse Vcc1 and Vcc2 ? Pin 8 is Vcc2 is the motor power. Pin 16 is Vcc1 is the logic 5V voltage. As @jose-can-u-c wrote, you need a better battery and a there are better mosfet drivers. With your battery it is amazing that it lasts as long 30 seconds.

9V batteries are not meant for high-current discharge, as you would find when powering a motor. Not only that, they are low capacity. If you need to power motors, you should use batteries such as C or D cells in series to build the voltage required, or try Lithium-Polymer (LiPo) for a rechargeable option.
On a side note, the L293 H-Bridge is a poor choice of H-Bridge these days, especially for a battery-powered project, as there are more efficient motor driver ICs these days.