text:
how to communicate MPU-6050 ( on arduino micro) wirelessly using nrf24l01 to arduino uno?
I have an Arduino Micro and MPU-6050. I'm trying to transfer the data obtained from the MPU-6050 wirelessly to my computer using an Arduino Uno at the other end. I'm not sure how to make this happen.
// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//      2013-05-08 - added seamless Fastwire support
//                 - added note about gyro calibration
//      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
//      2012-06-20 - improved FIFO overflow handling and simplified read process
//      2012-06-19 - completely rearranged DMP initialization code and simplification
//      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
//      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
//      2012-06-05 - add gravity-compensated initial reference frame acceleration output
//                 - add 3D math helper file to DMP6 example sketch
//                 - add Euler output and Yaw/Pitch/Roll output formats
//      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
//      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
//      2012-05-30 - basic DMP initialization working

/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/

// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

/* =========================================================================
   NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
   when using Serial.write(buf, len). The Teapot output uses this method.
   The solution requires a modification to the Arduino USBAPI.h file, which
   is fortunately simple, but annoying. This will be fixed in the next IDE
   release. For more info, see these links:

   http://arduino.cc/forum/index.php/topic,109987.0.html
   http://code.google.com/p/arduino/issues/detail?id=958
 * ========================================================================= */

// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT

#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(115200);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
    // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
        // .
        // .
        // .
        // if you are really paranoid you can frequently test in between other
        // stuff to see if mpuInterrupt is true, and if so, "break;" from the
        // while() loop to immediately process the MPU data
        // .
        // .
        // .
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}

Please add more detail to the question. Explain in a detailed way how this is all set up. What approach have you taken to solve this problem? What is it exactly that doesn't work? In your own testing, what have you ruled out and why? Does it work if the link was wired? Please add these details and more to the question.

You have a few options here for the wireless communication (~ denotes wireless):

MPU -> Arduino -> Bluetooth ~ ~ ~> PC
MPU -> Arduino -> NRF ~ ~ ~> NRF -> Arduino -> PC
MPU -> Arduino -> WiFi (ESP?) ~ ~ ~> PC

I don't think it'd be easy to directly communicate I2C over the NRF, so I'd just read the data over I2C (presumably you're using Jeff Roweburg's library?), then once you have it in an integer or byte, you can use any wireless module to send it over whatever method you prefer. I haven't touched the ESP8266 for WiFi, but I know the HC-05/06 and the NRF24L01 both have fairly simple libraries that can do a simple write command that will buffer a number of bytes and send it all out in the correct order.
edit:
This is code I used a long time ago, and it is almost definitely somebody else's. I'm dreadfully sorry I can't find the original author at the moment, else I'd happily link to their page on the NRF. You can split this up into a receive and transmit pair though, and get rid of all the serial printing stuff as that just used the NRFs to 'text' each other.
Two Way Communication:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8);
const int radioNum = 0;
const byte rxAddr[6] = "00001";
const byte txAddr[6] = "00002";

String readSerial() {
    String input;
    while(Serial.available() > 0){
        input.concat((char)Serial.read());
        delay(1);     //allows the buffer to fill with each character
    }
    return input;
}

void setup()
{
  radio.begin();
  Serial.begin(9600);
  radio.setRetries(15, 15);
  if(radioNum){
    radio.openWritingPipe(rxAddr);
    radio.openReadingPipe(1, txAddr);
  }
  else{
    radio.openWritingPipe(txAddr);
    radio.openReadingPipe(1, rxAddr);
  }
  Serial.println("Enter a string of characters:");

}

void loop()
{
  radio.startListening();
  while(Serial.available()==0){
    char output[32];
    radio.read(&output, 32);
    if(output[0]){
      if(radioNum)
         Serial.print("Pong: ");
      else
         Serial.print("Ping: ");
      Serial.println(output);
    }
  }
  radio.stopListening();

  String input = readSerial();
  char text[32];
  input.toCharArray(text,32);
  radio.write(&text, 32);

  if(radioNum)
    Serial.print("Ping: ");
  else
    Serial.print("Pong: ");

  Serial.println(text);
}
}

ok so I got ypr data from the mpu-6050. I posted the code. Now I want to transfer that data wirelessly using the NRF. How do I transfer the information from the mpu-6050 obtained through the NRF to another arduino?

Edited original answer to include some two-way communication code that I haven't tested in several months, so forgive me if it has some bugs. It requires the RF24 library

@EduardoCunha, Please add this to the question or start a new specific question. Comments are often ignored, so it is best to edit the question.

I'm not sure about the "wirelessly" context, but you can try this steps
1. Make sure you can read the mpu-6050 data
2. You can use bluetooth (HC-05 is the most common) to transfer data to your PC bluetooth directly, or to another arduino, then send it via serial usb cable to PC

ok so I got ypr data from the mpu-6050. I posted the code. Now I want to transfer that data wirelessly using the NRF. How do I transfer the information from the mpu-6050 obtained through the NRF to another arduino?

This is just a conception plan:
Make sure you can get all the data (YPR) you need from the MPU.
Then, using whatever protocol you want, send the data under the form of something like a byte. Here is a question I aksed about a similar topic.
For more info, please comment, I'll be happy to help.

ok so I got ypr data from the mpu-6050. I posted the code. Now I want to transfer that data wirelessly using the NRF. How do I transfer the information from the mpu-6050 obtained through the NRF to another arduino?

Send it through a byte. By mapping the value from 0-99, you can send something like yypprraa where y is yaw, p is pitch, r is roll, and a is altitude.\

ok but How do I do this? I don't know how to do that. Is there some sample code I can mess with?


text:
Error while installing bootloader ATmega328
I'm trying to install a bootloader on my ATmega328P-PU. I'm trying to install it from Arduino Uno (not original). I can install all sketches. After I click "Burn bootloader" I get the following error:
Arduino:1.6.11 (Windows 10), Board:"Arduino/Genuino Uno"

avrdude: Yikes!  Invalid device signature.
avrdude: Expected signature for ATmega328P is 1E 95 0F
 ***failed;
avrdude: verification error, first mismatch at byte 0x0000
         0x00 != 0x3f
avrdude: verification error; content mismatch
Error while burning bootloader.

How to fix it?

EDIT: First ensure that you have made the hardware correctly (see comment below this post).
If you need different settings for custom avr hardware the following will help:-
The best way to create a custom board definition is to create your own boards.txt entry in the Arduino custom hardware folder.
But less effort to learn is to try to temporarily change or add to the Arduino IDE avr board definitions.
The board definition (properties) are passed to the tool that burns the bootloader. All board specific properties are provided by the boards.txt
Edit the [ArduinoIDE\Hardware\hardware\arduino\avr\boards.txt with a text editor and find the Uno section.
It looks like this. Notice the mcu, vid, pid and uno.bootloader.file= settings in particular. The bootloader points to a file in [ArduinoIDE\Hardware\hardware\arduino\avr
uno.name=Arduino/Genuino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
uno.vid.2=0x2A03
uno.pid.2=0x0043
uno.vid.3=0x2341
uno.pid.3=0x0243

uno.upload.tool=avrdude
uno.upload.protocol=arduino
uno.upload.maximum_size=32256
uno.upload.maximum_data_size=2048
uno.upload.speed=115200

uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0x05
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

uno.build.mcu=atmega328p
uno.build.f_cpu=16000000L
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

You can add a new entry like this. The example uses a board prefix of uno2. but it can be any simple unique name.
Save the changes to boards.txt then restart the Ide:-
uno2.name=Arduino ATmega328P-PU

uno2.vid.0=0x2341
uno2.pid.0=0x0043
uno2.vid.1=0x2341
uno2.pid.1=0x0001
uno2.vid.2=0x2A03
uno2.pid.2=0x0043
uno2.vid.3=0x2341
uno2.pid.3=0x0243

uno2.upload.tool=avrdude
uno2.upload.protocol=arduino
uno2.upload.maximum_size=32256
uno2.upload.maximum_data_size=2048
uno2.upload.speed=115200

uno2.bootloader.tool=avrdude
uno2.bootloader.low_fuses=0xFF
uno2.bootloader.high_fuses=0xDE
uno2.bootloader.extended_fuses=0x05
uno2.bootloader.unlock_bits=0x3F
uno2.bootloader.lock_bits=0x0F
uno2.bootloader.file=optiboot/optiboot_atmega328.hex

uno2.build.mcu=atmega328p
uno2.build.f_cpu=16000000L
uno2.build.board=AVR_UNO
uno2.build.core=arduino
uno2.build.variant=standard

note: make a copy of the .txt or grab a new one from the zip on arduino.cc if you mess it up.

Fixed! :D I must use 22pf condensator to quartz

Okay good. I think I should leave the answer because if anyone else has working hardware but needs slightly different boot loader settings for a different board it is useful. What do you think? I'll edit it to mention ensuring the hardware works first.

source: Stack Exchange

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

sort: votes


text:
how to measure level shock using vibration sensor and arduino

My project title is about crash detection, by using this kind of vibration sensor. When the sensor reads the shock (which is when I knock the sensor) more than 50, it assumes it's a crash and will send via SMS the location of the crash to me. The problem is, that I tried to connect the sensor with Arduino, but when I knocked the sensor, the value of the shock did not change. How can I fix this?
VCC I connected to 5V,
GND to Arduino GND,
A0 to analog input Arduino,
D0 is not used
This is my code

#include <SoftwareSerial.h>

#include <TinyGPS.h>

TinyGPS gps;
SoftwareSerial ss(2, 3);
SoftwareSerial GSMx(5, 11);

static void smartdelay(unsigned long ms);
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);

//-------------------VARIABLE-------------------------------
float LastLon;
String dataString = "";
String DateString = "";
String TimeString = "";
int Sens1Pin = 0;
float Sens1;
int update=0;
float LastLat;
int dummy=0;
int RQScount;
int countERROR;
int countPHONE;
int countOK;
int commaPosition;
int index = 0;
int SMSx=0;
int ALARM=0;
int LOCK=0;
float latx;
float lonx;
int OUTRANGE=0;
String result[10];
String USER1 = "\"019*******\"";
String Data1 = "";
String Data2 = "";
String Data3 = "";
String Data4 = "";
String head = "";
String phone = "";
String pword = "";
String MESSAGE1="";
String MESSAGE2="";
String inputString = "";         // a string to hold incoming data
boolean stringComplete = true;  // whether the string is complete
boolean command = true;
boolean Enabled = false;
boolean Enabled1 = false;
boolean Enabled2 = false;
boolean Enabled3 = false;
boolean GPS_NoData = false;
float SHOCK;
int count;
float flat, flon;
  unsigned long age, date, time, chars = 0;
  float ExistingSpeed;
float SpeedGPS;

//----------------------------------------------------------

void setup()
{

  Serial.begin(9600);
  GSMx.begin(9600);
  inputString.reserve(150);
 delay(8000);

  //Serial.println("AT");
  GSMx.println("AT");
  delay(2000);
 // Serial.println("AT+CMGF=1");
  GSMx.println("AT+CMGF=1");
  delay(2000);
 // Serial.println("AT+CMGD=1");
  GSMx.println("AT+CMGD=1");
  delay(2000);
  //Serial.println("AT&W");
  GSMx.println("AT&W");
  delay(2000);

  //Serial.print("AT+CMGS=");
  delay(300);
  //Serial.println(USER1);
  GSMx.print("AT+CMGS=");
  delay(300);
  GSMx.println(USER1);
  delay(1000);
  //Serial.print("GPS-GSM TRACKER---ACTIVATED ");
  GSMx.print("Controller is now ready...");
  delay(200);
  //Serial.println(char(26));
  GSMx.println(char(26));
  delay(4000);

  //Serial.println("Sats HDOP Latitude  Longitude  Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
  //Serial.println("          (deg)     (deg)      Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
  //Serial.println("-------------------------------------------------------------------------------------------------------------------------------------");

  ss.begin(9600);
  //--------------------------------------

  stringComplete = true;
}

void loop()
{

  Sens1 = analogRead(Sens1Pin);           //read the value from the sensor
  Sens1 = (5.0 * Sens1 * 100.0)/1024.0;  //convert the analog data to digital

  SHOCK = ((390 - Sens1)/390)*100;

  unsigned short sentences = 0, failed = 0;
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

 if (SHOCK > 40){
    ALARM=1;
  }

  if (ALARM==1){
    delay(100);

    if (SMSx==0){
     //  Serial.print("AT+CMGS=");
                GSMx.print("AT+CMGS=");
               // Serial.println(USER1);
                GSMx.println(USER1);
                delay(1000);
               // Serial.print("ALARM ALERT!! at location, lat:");
                GSMx.print("EMERGENCY ALERT!!");
               // Serial.print(flat,5);
                GSMx.print(TimeString);
                GSMx.print(" ");
                GSMx.print(DateString);
                GSMx.print(" (LAT/LON/SPEED) ");
                GSMx.print(dataString);

                GSMx.print("www.google.co.in/maps/place/");
                GSMx.print(flat,5);
                GSMx.print(",");
                GSMx.println(flon,5);

                delay(200);
               // Serial.println(char(26));
                GSMx.println(char(26));
                delay(4000);

      SMSx=1;
      ALARM=0;
    }
  }

  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
  gps.f_get_position(&flat, &flon, &age);
  print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);
  print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  print_date(gps);
  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);

  gps.stats(&chars, &sentences, &failed);
  print_int(chars, 0xFFFFFFFF, 6);
  print_int(sentences, 0xFFFFFFFF, 10);
  print_int(failed, 0xFFFFFFFF, 9);
  //Serial.println();

   if (flat < 0.1){
    GPS_NoData = true;
  }
  if (flat > 0.1){
    GPS_NoData = false;
  }

  if (flat != LastLat){
               if (GPS_NoData == false){
                 LastLat = flat;
               }
             }
             if (flon != LastLon){
               if (GPS_NoData == false){
                 LastLon = flon;
               }
             }

  //---------------------------------GSM FUNCTION-----------------------------------------

              Serial.print(TimeString);
              Serial.print(" ");
              Serial.print(DateString);
              Serial.print(" ");
              Serial.print(flon,5);
              Serial.print(", ALARM:");
              Serial.print(ALARM);
              Serial.print(", DATA:");
              Serial.print(dataString);
              Serial.print(", SHOCK LEVEL: ");
              Serial.println(SHOCK);

if (stringComplete == true){

  //Serial.println("AT+CMGR=1");
   GSMx.println("AT+CMGR=1");

  count = 0;
  countERROR = 0;
  countPHONE = 0;
  countOK = 0;
  stringComplete = false;
  Enabled = false;
  Enabled1 = false;
  Enabled2 = false;
  Enabled3 = false;
}

  while (stringComplete == false){
 // count = count + 1;
       while (Serial.available() > 0){

        char inChar = Serial.read();
        inputString += inChar;

        if (Enabled2){
          Data2 += inChar;
          countPHONE = countPHONE + 1;
            if (countPHONE == 10){
            Enabled2 = false;
            }
        }

        if (inChar == 'E'){
          Enabled1 = true;
         }
         if (Enabled1){
          Data1 += inChar;
          countERROR = countERROR + 1;
                if (countERROR == 5){
                 Enabled1 = false;
                      if (Data1 == "ERROR"){
                        stringComplete = true;
                      }
                      if (Data1 != "ERROR"){
                        countERROR = 0;
                        Data1 += "";
                        Enabled1 = false;
                      }
                }

        }

        if (inChar == 'O'){
          Enabled3 = true;
         }
         if (Enabled3){
          Data4 += inChar;
          countOK = countOK + 1;
               if (countOK == 2){
                if (Data4 == "OK"){
                  stringComplete = true;
                }
                if (Data4 != "OK"){
                  countOK = 0;
                  Data4 = "";
                  Enabled3 = false;
                }
               }
         }
        if (inChar == '+'){
          if (count > 5){
            Enabled2 = true;
          }
        }
        if (count > 80){
            stringComplete = true;

         }

       }
}

       if (stringComplete){
         /*

                */
            // Serial.println(inputString);
            index = 0;
    do
  {
      commaPosition = inputString.indexOf('*');
      if(commaPosition != -1)
      {
          result[index++] = (inputString.substring(0,commaPosition));
          inputString = inputString.substring(commaPosition+1, inputString.length());
      }
    //  else
    //  {  // here after the last comma is found
    //     if(inputString.length() > 0)
    //       Serial.println(inputString);  // SMS message after final splitting
                             // print it
     // }
   }
   while(commaPosition >=0);
     MESSAGE1 = result[2];
     MESSAGE2 = result[3];

         if (result[1] == "LOCATION") {
    //            Serial.print("AT+CMGS=");
                GSMx.print("AT+CMGS=");
    //            Serial.println(USER1);
                GSMx.println(USER1);
                delay(1000);
    //            Serial.print("DEVICE TRACKING, lat:");
                GSMx.print("DEVICE TRACKING, lat:");
    //            Serial.print(flat,5);
                GSMx.print(flat,5);
    //            Serial.print(", lon:");
                GSMx.print(", lon:");
    //            Serial.println(flon,5);
                GSMx.println(flon,5);
    //            Serial.print("www.google.co.in/maps/place/");
    //            Serial.print(flat,5);
    //            Serial.print(",");
    //            Serial.println(flon,5);
                GSMx.println(" SPEED:");
                GSMx.println(SpeedGPS);
                GSMx.print("www.google.co.in/maps/place/");
                GSMx.print(flat,5);
                GSMx.print(",");
                GSMx.println(flon,5);

                delay(200);
    //            Serial.println(char(26));
                GSMx.println(char(26));
                delay(4000);
    //            Serial.println("AT+CMGD=1");
                GSMx.println("AT+CMGD=1");

                delay(4000);

            }

                              if (result[1] == "RST") {
    //            Serial.print("AT+CMGS=");
                GSMx.print("AT+CMGS=");
    //            Serial.println(USER1);
                GSMx.println(USER1);
                delay(1000);
    //            Serial.print("Alarm reset...");
                GSMx.print("Alarm reset..");
                delay(200);
    //            Serial.println(char(26));
                GSMx.println(char(26));
                delay(4000);
    //            Serial.println("AT+CMGD=1");
                GSMx.println("AT+CMGD=1");
                ALARM=0;  SMSx=0;

                delay(4000);

            }

       inputString = "";
       result[1] = "";
       result[2] = "";
       result[3] = "";
       result[4] = "";
       result[5] = "";
       result[6] = "";
       Data1 = "";
       Data2 = "";
       Data3 = "";
       Data4 = "";
      // Serial.flush();

      // stringComplete = true;
  delay(100);
  Sens1 = analogRead(Sens1Pin);           //read the value from the sensor
  Sens1 = (5.0 * Sens1 * 100.0)/1024.0;  //convert the analog data to digital
  SHOCK = ((390 - Sens1)/390)*100;
  if (SHOCK > 50){
    ALARM=1;
  }
  Serial.print("SHOCK LEVEL: ");
  Serial.println(SHOCK);
  delay(100);
  Sens1 = analogRead(Sens1Pin);           //read the value from the sensor
  Sens1 = (5.0 * Sens1 * 100.0)/1024.0;  //convert the analog data to digital
  SHOCK = ((390 - Sens1)/390)*100;
  if (SHOCK > 40){
    ALARM=1;
  }
  Serial.print("SHOCK LEVEL: ");
  Serial.println(SHOCK);
  delay(100);
  Sens1 = analogRead(Sens1Pin);           //read the value from the sensor
  Sens1 = (5.0 * Sens1 * 100.0)/1024.0;  //convert the analog data to digital
  SHOCK = ((390 - Sens1)/390)*100;
  if (SHOCK > 40){
    ALARM=1;
  }
  Serial.print("SHOCK LEVEL: ");
  Serial.println(SHOCK);
  delay(100);
  Sens1 = analogRead(Sens1Pin);           //read the value from the sensor
  Sens1 = (5.0 * Sens1 * 100.0)/1024.0;  //convert the analog data to digital
  SHOCK = ((390 - Sens1)/390)*100;
  if (SHOCK > 40){
    ALARM=1;
  }
  Serial.print("SHOCK LEVEL: ");
  Serial.println(SHOCK);
       }

  delay(100);
 // smartdelay(300);
}
//--------------------------------------START OF SUBROUTINES-------------------------------------
static void smartdelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void print_float(float val, float invalid, int len, int prec)
{
  if (val == invalid)
  {
    while (len-- > 1)
    //  Serial.print('*');
    //Serial.print(' ');
    dummy=0;
  }
  else
  {
   // Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
     // Serial.print(' ');
     dummy=0;
  }
  smartdelay(0);
}

static void print_int(unsigned long val, unsigned long invalid, int len)
{
  char sz[32];
  if (val == invalid)
    strcpy(sz, "*******");
  else
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
 // Serial.print(sz);
  smartdelay(0);
}

static void print_date(TinyGPS &gps)
{
  int year;
  byte month, day, hour, minute, second, hundredths;
  float Speed;
  unsigned long age;
  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  if (age == TinyGPS::GPS_INVALID_AGE)
   // Serial.print("********** ******** ");
   dummy = 1;

  else
  {

    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
        month, day, year, hour, minute, second);
   // Serial.print(sz);

  //  hour = hour+8;
  //  sprintf(lcd_buffer,"%02d/%02d/%02d %02d:%02d",day,month,year,hour,minute );

    hour = hour + 8;
    if (hour > 23){
      hour = hour - 24;
    }
    dataString="";
    TimeString="";
    DateString="";
    ExistingSpeed = gps.f_speed_kmph();
    Speed = gps.f_speed_kmph();
    SpeedGPS = Speed;

   TimeString = String(hour) + ":" + String(minute) + ":" + String(second);
   DateString = String(day) + "/" + String(month) + "/" + String(year);
   dataString = String(flat,5) + "  " + String(flon,5) + "  " + String(Speed,2);

  }
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  smartdelay(0);

    }

static void print_str(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
  //  Serial.print(i<slen ? str[i] : ' ');
  smartdelay(0);
}

Have you tried a minimal sketch that just reads the vibration sensor and prints what it reads?

no, i didn't try it yet, i want the sensor that i used compatible with the coding as this is my fourth sensor that i had try on.

So step one is to confirm that the sensor is working and that it gives you the kind of values you expect - with a minimal program that reads the sensor and prints out the values.

From the huge amount of code it's hard to tell what exactly is wrong, but I noticed that you used 0 for the analog pin which is not the same as A0.
Your pin number should be defined as:
int Sens1Pin = A0;

On the UNO the two are interchangeable, since the analog pins are completely separate from the digital pins. It sees the numbers 0 to 5 or 14 to 19 (the latter are what A0-A6 alias to) with an analogRead() and maps then to the 6 available analog channels.

oh, i'm little bit confuse,  what do you means by maps then to the 6 available analog channels? could you give me an example according to my coding.

@Majenko I see. I just checked the pin definition and not the implementation of analogRead.

yes, my sensor implemented for analogRead, that why i use int Sens1Pin=0; but the problem is, my sensor cannot read the shock level, so the device cannot detect the shock level when it crash. because i use if else selection which is if shock level > 40, is assume as crash and sending me a SMS. There is no error at my coding i give above. just i not sure why i can't read the level of sensor when i knock it. i had try to change int SenslPin= A0; but the result are same. can u help me.

@MissBlur Did you try just reading the sensor and sending it to serial, to see if it works? Maybe try to use the digital pin on the module, since you just need a trigger at a threshold value. And adjust the sensitivity with the pot.

@gre_gor i had tried to testing the sensor and sending it to the serial, and i found out that my sensor do not detect the vibration because the result are not change. so the problem is my sensor right ? but when i run the code, the light(LED) of my sensor are just fine. do i need to replace the sensor? or i just need to try another code??

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


text:
LCD shows output without pressing the sensor
#include<LiquidCrystal.h>
LiquidCrystal lcd(13,12,11,10,9,8);
#define vibrate_sense 7

char str[70];
char *test="$GPGGA";
char logitude[10];
char latitude[10];

int i,j,k;
int temp;
//int Ctrl+z=26;    //for sending msg
int led=13;

void setup()
{
  lcd.begin(16,2);
  Serial.begin(4800);
  pinMode(vibrate_sense, INPUT);
  pinMode(led, OUTPUT);
  lcd.setCursor(0,0);
  lcd.print("..Initializing..");
  lcd.setCursor(0,1);
    lcd.print("....System...");
delay(1000);
lcd.clear();
lcd.setCursor(0,0);
  lcd.print("Searching for");
    lcd.setCursor(0,1);
      lcd.print("Gps Signals");
  delay(2300);
lcd.clear();
  lcd.setCursor(0,0);
    lcd.print("Setup Completed");
  delay(500);
  lcd.setCursor(0,0);
    lcd.print("Accident detect");
  lcd.setCursor(0,1);
    lcd.print("& Alert system");
  delay(1500);
  lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("No accident");
        lcd.setCursor(0,1);
        lcd.print("occured");

}

void loop()
{
  if (digitalRead(vibrate_sense)==0)
  {
    for(i=18;i<27;i++)          //extract latitude from string
    {
      latitude[j]=str[i];
      j++;
    }

    for(i=30;i<40;i++)          //extract longitude from string
    {
      logitude[k]=str[i];
      k++;
    }

lcd.clear();
    lcd.setCursor(0,0);        //display latitude and longitude on 16X2 lcd display
    lcd.print("Latitude(N)");
    lcd.print(latitude);
    lcd.setCursor(0,1);
    lcd.print("Longitude(E)");
    lcd.print(logitude);
    delay(500);
    lcd.clear();
        lcd.setCursor(0,0);
    lcd.print("Accident has");
            lcd.setCursor(0,1);
    lcd.print("been Detected");
delay(500);
lcd.clear();
    lcd.print("Sending SMS");
    delay(500);
    lcd.clear();
    Serial.begin(9600);

    Serial.println("AT+CMGF=1");    //select text mode
    delay(10);
    Serial.println("AT+CMGS=\"7066128969\"");  // enter receipent number
    Serial.println("Vehicle Accident occured:");
    Serial.print("Latitude(N): ");             //enter latitude in msg
    Serial.println(latitude);                  //enter latitude value in msg
    Serial.print("Longitude(E): ");            //enter Longitude in Msg
    Serial.println(logitude);                  //enter longitude value in msg
    Serial.print("http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=");
    Serial.println(latitude);
    Serial.println("+");
    Serial.println(logitude);
    Serial.write(26);                      //send msg  Ctrl+z=26

      lcd.setCursor(0,0);
    lcd.print("SMS Sent");
delay(1000);
lcd.clear();
          lcd.setCursor(0,0);
    lcd.print("Help Please");

    temp=0;
    i=0;
    j=0;
    k=0;
    delay(20000);                        // next reading within 20 seconds
    Serial.begin(4800);
  }
}

void serialEvent()
{
  while (Serial.available())            //Serial incomming data from GPS
  {
    char inChar = (char)Serial.read();
     str[i]= inChar;                    //store incomming data from GPS to temparary string str[]
     i++;
     if (i < 7)
     {
      if(str[i-1] != test[i-1])         //check for right string
      {
        i=0;
      }
     }
    if(i >=60)
    {
     break;
    }
  }
}

This is my code for my project.
It is accident detection system and it has to work like, when I press the sensor or limit switch, it has to show a message on an LCD that an accident occurred. But it shows the message on the LCD WITHOUT pressing the sensor button.
What to do?
I think there is a mistake in my program. Can anybody please tell me where it is?

you have not learned the basics before attempting your program ...... start by writing a short program that turns on an LED when the button is pressed and turns off the LED when the button is released

Do you have a pullup resistor?

Please do not vandalize your or anyone else's posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the CC BY-SA 3.0 license). By SE policy, any vandalism will be reverted.

First off I edited indentation in your code because incorrect indentation is little bit confusing.
#include <LiquidCrystal.h>
LiquidCrystal lcd(13,12,11,10,9,8);
#define vibrate_sense 7

char str[70];
char *test="$GPGGA";
char logitude[10];
char latitude[10];

int i,j,k;
int temp;
//int Ctrl+z=26;    //for sending msg
int led = 13;

void setup(){
  lcd.begin(16,2);
  Serial.begin(4800);

  pinMode(vibrate_sense, INPUT);
  pinMode(led, OUTPUT);

  lcd.setCursor(0,0);
  lcd.print("..Initializing..");
  lcd.setCursor(0,1);
  lcd.print("....System...");
  delay(1000);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Searching for");
  lcd.setCursor(0,1);
  lcd.print("Gps Signals");
  delay(2300);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Setup Completed");
  delay(500);
  lcd.setCursor(0,0);
  lcd.print("Accident detect");
  lcd.setCursor(0,1);
  lcd.print("& Alert system");
  delay(1500);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("No accident");
  lcd.setCursor(0,1);
  lcd.print("occured");
}

void loop(){
  if (digitalRead(vibrate_sense) == 0){
    for(i = 18; i < 27; i ++){          //extract latitude from string
      latitude[j]=str[i];
      j++;
    }

    for(i=30;i<40;i++){          //extract longitude from string
      logitude[k] = str[i];
      k++;
    }

    lcd.clear();
    lcd.setCursor(0,0);        //display latitude and longitude on 16X2 lcd display
    lcd.print("Latitude(N)");
    lcd.print(latitude);
    lcd.setCursor(0,1);
    lcd.print("Longitude(E)");
    lcd.print(logitude);
    delay(500);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Accident has");
    lcd.setCursor(0,1);
    lcd.print("been Detected");
    delay(500);
    lcd.clear();
    lcd.print("Sending SMS");
    delay(500);
    lcd.clear();
    Serial.begin(9600);

    Serial.println("AT+CMGF=1");    //select text mode
    delay(10);
    Serial.println("AT+CMGS=\"7066128969\"");  // enter receipent number
    Serial.println("Vehicle Accident occured:");
    Serial.print("Latitude(N): ");             //enter latitude in msg
    Serial.println(latitude);                  //enter latitude value in msg
    Serial.print("Longitude(E): ");            //enter Longitude in Msg
    Serial.println(logitude);                  //enter longitude value in msg
    Serial.print("http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=");
    Serial.println(latitude);
    Serial.println("+");
    Serial.println(logitude);
    Serial.write(26);                      //send msg  Ctrl+z=26

    lcd.setCursor(0,0);
    lcd.print("SMS Sent");
    delay(1000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Help Please");

    temp = 0;
    i = 0;
    j = 0;
    k = 0;
    delay(20000);                        // next reading within 20 seconds
    Serial.begin(4800);
  }
}

void serialEvent(){
  while (Serial.available()){            //Serial incomming data from GPS
    char inChar = (char)Serial.read();
    str[i] = inChar;                    //store incomming data from GPS to temparary string str[]
    i++;
    if (i < 7){
      if(str[i-1] != test[i-1]){         //check for right string
        i = 0;
      }
    }
    if(i >= 60){
      break;
    }
  }
}

Second thing is this line if (digitalRead(vibrate_sense) == 0){ you are checking there vibrate_sense for value 0. Are you sure, that triggered value is 0 and not 1? Try this code to test which value is equal to triggered state.
#define vibrate_sense 7

void setup() {
  Serial.begin(9600);
  Serial.println("Sensor testing");
  pinMode(vibrate_sense, INPUT);

}

void loop() {
  Serial.println(digitalRead(vibrate_sense));
  delay(300);
}

Last thing is connection of your sensor/button. For button you have to use also PULL_UP/PULL_DOWN resistor to have correct logic value on digital pin.

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


text:
Is the arduino hackable when using communication shields?
Let's say I have an arduino Uno connected to a W5100 ethernet shield. The arduino communicates with the ethernet shield using the tx0 and rx0 pins. When I upload a new script to the arduino using USB, it uses the same tx0 and rx0. So that made me think.
What if I run a script on my arduino that fetches some data from a webpage using HTTP requests but someone manages to hack into my server. Is it possible for the hacker to upload some kind of code to my server, which will erase (when fetched by the arduino) the old script and upload a new arduino script, by making the arduino think it's uploading a new script while it's getting data from the ethernet shield (or other communication shields?)
EDIT: Let's expand the question a bit.. How can I add security to my code to prevent this situation from happening?

Ask on infosec.EE . Use memory buffers prudently and don’t worry.

You are not expanding the question “quite a bit”: you are opening a vast subject. Lots have been written about how to handle untrusted data, and about the kind of errors you should avoid. In any case, your new question would be more appropriate in https://security.stackexchange.com/

@EdgarBonet Oh no that's not what I meant by that. Just point me in the right direction like you did.

You should be pretty safe, at least as long as your code handles the
incoming data properly.
When you upload a new sketch through USB, the USB-to-serial interface
uses the Arduino pins TX0, RX0 and RESET. Your Ethernet shield, on
the other hand, does not control the RESET pin. Pulling the RESET pin
LOW is needed to make the processor enter the bootloader, which in turn
is needed in order to upload a new program. For pulling this pin low,
the malicious code would need not only to break into the Ethernet
shield's firmware, it would also need a hardware hack to access the
pin.
Now, if your own code is not safe, it is conceivable that the malicious
payload tricks your program into jumping to the bootloader or, as
suggesting by Juraj, into triggering a watchdog reset (which ends up
being equivalent). Thus you should treat anything coming from the
network as potentially malicious.

@LookAlterno: Right, but at the hardware level, NodeMCU is a completely different beast.

different beast with not open source chinese code deep inside :)

if the downloaded data could trigger the watchdog reset, and the Ethernet shield had STK500 programmer in firmware then a hack hex could be written into avr :)

@Juraj: The downloaded data cannot trigger a watchdog reset. Not by itself: it would need to first exploit a security hole in the user's program. I edited my answer to account for this possibility.

@EdgarBonet, I know, just wanted to point out that writing of the hex is not just sending it to tx/rx

No it's not possible. Assuming you mean this shield (and if you don't, please clarify):

Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega.

Further on it mentions:

The shield contains a number of informational LEDs:
...
RX: flashes when the shield receives data
TX: flashes when the shield sends data

That's Rx and Tx on the shield, not the Arduino. Since it does not connect to the Tx/Rx on the Arduino, and since it cannot reset the Arduino, it therefore cannot reprogram it.
If you are worried, disable the BOOTRST fuse on the Arduino so that the bootloader is not active after a reset.
If you are really worried, disable the SPIEN fuse so that you cannot even reprogram it using SPI. Of course, then you won't be able to reprogram it either.
Personally I would be more worried that a cockatoo would come and peck at the shield.

Birds are not to be trusted.

The bird problem is a serious concern.

Great answer!! But now another problem arises, I have an aviary in my garden, should I get rid of it?

If you have cockatoos, I would advise caution. As Wikipedia says: They can be a nuisance in urban areas due to destruction of property ... Birds may also target external wiring and fixtures such as solar water heaters, television antennae and satellite dishes.


text:
How do I isolate numbers in text?
I need to separate numbers from the text where my string of numbers will always be of length 8:
string text = "77953505HELLO THIS IS A MESSAGE"; //my string of numbers will always be of length 8

My result
string number = "77953505"; //my string of numbers will always be of length 8
string message = "HELLO THIS IS A MESSAGE";

What operation should I use?
this is the job I'm doing
void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {

    String Texto = String(Serial.read());

    String number = Texto.substring(0, 7);
    String message = Texto.substring(8);

    Serial.write(number);
    Serial.write(message);
  }
}

help me!

read() reads one char. https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

please, helpme  whith a example

i new in the world of arduino

it has little to do with Arduino. It is programming in C++. Read the blog.

Depends, and probably better to use C strings:

If you know the number is always the same amount of characters, use the C function strncpy.
You can also split on a delimiter (char), with strtok, but in your case this is not possible since you don't know the delimiter character.
If the number has a variable length, start copying character by character through the string, until you find a character that gives false for the isdigit condition and copy the remainder (with strncpy) to the other string.

Update after the question's edit
Since the number of text to be copied is know, strncpy can be used with the following prototype:
char *strncpy(char *dest, const char *src, size_t n)

In your case put the text in a normal text string:
char text[80]; /* Assuming max length of text */

Copy it where needed:
strcpy(text, "77953505HELLO THIS IS A MESSAGE");

Note: it can be done in once like this:
char text[] = "77953505HELLO THIS IS A MESSAGE";

Than you can copy the items by:
char number[9]; // Add 1 for \0
char message[81]; // Assuming max length of message;

strncpy(number, text, 8);
strncpy(message, &(text[8]), strlen(text) - 8);

(Note not checked with compiler).
Improvements: use instead of 8 a define e.g.
#define NUMBER_LENGTH 8

char number[NUMBER_LENGTH + 1];

strncpy(number, text, NUMBER_LENGTH);
strncpy(message, &(text[8]), strlen(text) - NUMBER_LENGTH);

You can do similar for MESSAGE LENGTH
#define MESSAGE_LENGTH 80

Also, another improvement is not to copy the message, but just set the pointer to the correct place:
char* message = &(text[8]);

message will point to "HELLO THIS IS A MESSAGE"
like below
"77953505HELLO THIS IS A MESSAGE"
|        |
+-- text |
         +-- message

In an Arduino 80 bytes can be a lot of memory, using two buffers cost 160 bytes, and this way you save at least one buffer.

i edited my question

So in this case you can use strncat; I will edit my answer

I changed strncat by strncpy and added some improvements.

look at my edition

what output you get? I don't see a problem so far.

For a fixed length substring the simple arduino-ish way would be to use String.substring(left_pos, right_pos)
String number = text.substring(0, 7);
String message = test.substring(8); // right_pos is optional

This is not necessarily the best option depending on how you intend to use the resulting substring.  Memory is allocated and the content is copied. Requiring at least double the memory (plus some overhead). If memory is tight you may not want to create a String but use char* instead.

look at my edition


text:
Am I maximising my A0 readout rate with this peak-detection code?
I have a pulse going into A0 on a Nano, and want to detect the peak voltage.  With low-pass filtering to slow down the input pulse I'm still reading marginally too slow.
The code overall inhibits a laser except for 50ms after a button is pressed.  During that 50ms I read A0 to look for the peak voltage/laser pulse energy.  The pulse is negative, several volts, and is AC-coupled into A0, pulled up to a 5V baseline.
The monitoring loop is simple:
while (millis() < (PulseStart + LaserPulseWidth)) { // monitor ADC (PbSe amplified photodiode with negative output, AC coupled and pulled up
  if (V_in <= V_old) {
    V_old = V_in;
  } // this will report the minimum voltage seen on the monitor pin.  Should be near enough proportional to the pulse energy.
  V_in = analogRead(MonitorPin);
}

Outside the monitoring loop, but in the main loop, I toggle various status LEDs etc.  The resulting laser pulse energy is sent using softwareSerial to (a Raspberry Pi in) the box with the trigger button, about 12m away. softwareSerial requires interrupts, but anyway so does millis()

Channel 1 (yellow) is measured at A0.  Channel 2 is the unfiltered output from the PbSe amplified IR photodiode, and is used to trigger the scope.  Note the timebase is 100us, close to the nominal readout time of A0; I thought this would effectively average over approximately 1 division, which might be OK, but taking some rough calibration data suggests otherwise.
Here's my circuit:

A simplified version of the whole code follows. I've removed some status outputs (LEDs, beeps, USB serial transmssion) from the main loop and the code to set them up; the ADC read-in loop is unmodified from my running code.
#include <SoftwareSerial.h>

int MonitorPin = A0;
int FireButton;
int stopbutton;
int lastFireButton = LOW;
int V_in;
int V_old;
char message[8];
int V_base;
int LaserPulseWidth = 50; //in ms.  50 ms should be right for 20 Hz laser

SoftwareSerial mySerial = SoftwareSerial(2, 3); // RX, TX

void setup() {
  pinMode(pin7, INPUT_PULLUP);  // fire laser
  pinMode(pin8, INPUT_PULLUP);  // disable
  stopbutton = digitalRead(8);
  FireButton = digitalRead(7);
  pinMode(LaserPin, OUTPUT); // Laser trigger pin
  Serial.begin(9600); // for comms to a host PC (includes debug info)
  mySerial.begin(9600); // for comms to RPi
  mySerial.println("Second serial port");
  interrupts();
}

void loop() {
  stopbutton = digitalRead(8);
  FireButton = digitalRead(7);
  while (stopbutton == HIGH) { // not actually used, but implemented in case we want to suppress firing (pin internally pulled up so just ground to suppress)
    lastFireButton = FireButton;
    stopbutton = digitalRead(8);
    FireButton = digitalRead(7);
    V_old = 1024; // initialise to max so anything we read is less

    if (FireButton != lastFireButton && FireButton == LOW) { // detect negative edge
      digitalWrite(13, true); // flash the onboard status LED on
      V_old = 1024;
      for (int i = 0; i < 10; i++) {
        V_in += analogRead(MonitorPin); // read ADC before firing to provide a baseline
      }
      V_base = V_in / 10;
      digitalWrite(LaserPin, true); // laser trigger on
      PulseStart = millis();
      while (millis() < (PulseStart + LaserPulseWidth)) { //monitor ADC (PbSe amplified photodiode with negative output, AC coupled and pulled up
        if (V_in <= V_old) {
          V_old = V_in;
        } // this will report the minimum voltage seen on the monitor pin.  Should be near enough proportional to the pulse energy.
        V_in = analogRead(MonitorPin);
      }
      digitalWrite(LaserPin, false); // laser trigger on

      int V_peak = V_base - V_old;
      sprintf(message, "ADC=%d", V_peak);
      mySerial.println(message);
    }
  }
}

Sidenote; to handle millis rollover, use while ( (millis()-PulseStart) < LaserPulseWidth)  instead.

Do you have a schematic, and an oscilloscope picture of the pulse as it is, and as it arrives at the Arduino pin? Just to get some idea of what "a little too fast" is. analogRead() is quite slow by default, but can be sped up.

You could you do like, say, 20 measurements, and store those in an array. Then afterward see which value was the peak value. That way your code doesn't have to do a millis call, and two comparisons, making it run a bit faster. If that's not enough, you'd have to change the prescaler of the ADC, to get a faster Analog to Digital conversion.

@Gerben the pulse can occur anywhere within a window of 50ms (the laser has a 20Hz rep rate; I allow emission for 1/20 s to get one pulse).  I don't think I've got enough storage to read flat out for 50ms then post-process.

@ocrdu I'll get a scope trace with the latest circuit.  I've been building a low-pass filter this morning, since posting.  My schematic needs updating.  It was a simple block diagram before I started AC-coupling and low-pass filtering

Actually (@Gerben) I'm right on the edge of having enough storage.  The compiler says I've got 1103B free for local variables, which is enough for 550 ints or 55ms if I read every 100us.  I'm not sure if all that is actually free, but I could free up some more.

@ocrdu I've added the circuit; it's more of an electronic lab-book sketch but hopefully clear enough

"On ATmega based boards (UNO, Nano, Mini, Mega), it takes about 100 microseconds (0.0001 s) to read an analog input". Your pulse only takes 50µs. So you need to increase the ADC speed, by changing the prescaler.

What is it you are trying to measure? The peak-voltage, or the time till the peak occurs?

@Gerben I've been looking into that and will almost certainly do so.  What's not clear to me is how much is settling time (effectively averaging? or so I hoped) and how much is dead time.  Also my scope's  negative peak width measurement is unhelpful.  This trace has a "?" after it, not all do, but the number is always >~100us.  I'm after peak V; I'll add that to the Q.... I think it was clearer before one of my edits

The ADC averaging time is not specified, but probably tiny compared to the conversion time. Have you considered using a diode-based peak detector?

@EdgarBonet previous tests had showed this to be a rather slow (several hundred us) photodiode so I had expected not to need a significant sampling circuit.  Partly it's because I'm designing/building my electronics at home and testing/using them in work (the laser takes up most of a room, but we're supposed to work from home where possible).  The former slowness may be a thermal effect as the photodiode is sensitive out to 4.8um.  The laser pulses are a few picoseconds BTW.  The photodiode amplifier is internal. Changing the clock prescale is looking helpful so far.

I could also use an MCP3002 over SPI; that's faster and I've got some on rather large boards I'm not using

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


text:
Use chars in quotes in const char* as name of function
I have been trying for a long time how to use a word declared as const string* word = "xxx" as name of void function declared somewhere below in my code.
Here is example with ssid:
const char* ssid = "name_of_ssid";

void (*name of ssid*) () {

⠀//some code

}

I want to use word declared in const char* in quotation marks as name of function.
It can not be written just void ssid().
Yes, I can set a name of void function manually, when const char* ssid = "CoffeeWifi" I can type void CaffeeWifi() but I want to do that by this way because my code is specific for this option and explaining this code here would be very difficult. When I change array of const char* word from "xxx" to "yyy" I want to  change the name of void from void xxx() to void yyy() as well.
How to do that? What function should I use?
Thank you!

There's no way to do that sort of thing in C++.  What you could do is write another program that produces C++ code that you could then compile.  None of this has to do with Arduino though.

What is it you hope to achieve with this that you couldn't do with just passing the SSID as a parameter to the function?

You could accomplish that with #define instead of assigning a character string.

Maybe you could write some preprocessor macro to achieve it, but I can really think of no good reason why you would want to do this. Anyway, @timemage is right. This has nothing to do with Arduino.

I have feeling, that this is a x-y problem. You have a problem, that you didn't describe, and you think this is the solution, but most likely it isn't. So please describe better, why you want to do this

It sounds like something that, if described well, might be an application for x-macros, but they're not really Arduino-related either.

@timemage is my answer okay ? (edits also allowed)

That's mostly up to O.P.  If you're just wondering about my opinion: it's a reasonable answer to reasonable speculation of the problem that might be motivating their question. But their question as asked isn't addressed by it. It's not always easy to tell to what degree you should to take a charitable interpretation of a person's question or to get them to be precise.  I tend to push for details and less speculation, but there's a line somewhere.  If you're wondering about this sort of stuff, probably the thing to do is to read in the help center and ask on the meta site.

@timemage from my understanding, the OP is looking forward to execute a particular function specifically for a particular use case. Taking it into consideration. I feel that my answer is okay. Adding arguments seems to be a bit troublesome to me in such a situation (which means editing the exemplar function void execute() to accommodate arguments for input into the required function, but that should work just fine only if all functions follow the same argument declaration format).

" explaining this code here would be very difficult. " Try me, I'm always up for learning something.

Such a thing is impossible (unless you keep striving; neither have I tried it yet). Judging from your intention, one thing you can do is to create an array of the names of the functions you'd like to use, another array carrying the pointers to the functions and a programme to call the function according to the input text. I haven't tried it myself, so perhaps I may not sound sensible, but that is the only thing that came to my mind.
An example:
String function_names[3] = {"foo", "bar", "quux"}; /* I am not sure of this syntax;
                                                corrections are welcome */
int *functions[3] = {&foo, &bar, &quux};

String input;

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

void loop(){
        while(Serial.available()){
              String temp_input = Serial.readString()
              input = (temp_input == "")? String("Nothing here") : temp_input;
              execute(input);
        }
        delay(1000);
}

void execute(String func_name){
        for(int i = 0; i < 3; i++){
              if(function_names[i] == func_name){
                     *functions[i]();
              }
         }
}

int foo(){
    Serial.println("foo");
    return(0);
}

int bar(){
    Serial.println("bar");
    return(0);
}

int quux(){
    Serial.println("quux");
    return(0);
}

Being a const char, you can set it at compile time with a define and then use it.
#define fstring(x) #x

const char* ssid = fstring(SSID_NAME) ;

void setup() {
  Serial.println("Start");
  Serial.println(ssid);
  SSID_NAME();

}

void loop() {}

void SSID_NAME (){
  Serial.println(ssid);
}

Instead of using quotes, this uses the stringize operator.

Missing Serial.begin call aside, I don't think this does what you intended it to do.  Knowing how the stringize operator works, I'm having a hard time figuring out what the code was suppose to do just by looking at it.  You should try it yourself in any case.

Tested on a Leonardo (OP doesn't specify), so doesn't need Serial.begin.

I'm not sure about OP's 'why', but I think this achieves the 'what', but in reverse. Instead of using a string as function name, it makes the function name available as a string.


text:
Help On Creating Derived classes in Headers
Here's a small problem I encountered while I was trying to make this small header file Devices.h:

Is it possible to use templates with abstract classes ? If yes, how and how can I use that abstract class to derive another class ?

Here's the contents of the header file :
#ifndef Devices_h
#define Devices_h

/* Initial build for MCUOS
Anybody can edit this according to their device needs */

#include "Arduino.h"

template < typename datatype>

class Device_Handler
{
    // a class to handle devices
    public:
        virtual void write_to_device(datatype *send_data)= 0; // write data to device
        virtual void read_from_device(datatype *store_location)= 0 ; // read data from device to location
        virtual void clear_device() = 0; // clear device state
};

class Serial_Handler:public Device_Handler<char*>
{
   public:
          void write_to_device(char *send_data);
          void read_from_device(char *store_location);
          void clear_device();
};

void Serial_Handler<char*>::write_to_device(char *send_data){
        Serial.println(*send_data);
 }

void Serial_Handler<char*>::read_from_device(char *store_location){
       *store_location = Serial.read();
}

void Serial_Handler::clear_device(){
        Serial.flush();
}

#endif

This is a small project I am trying at home nowadays (that MCUOS thing up there), also considering it a learning opportunity. I am not sure if I wrote the code in the header the right way. Initially, I made the Device_Handler class and used it in my sketch to craft the Serial_Handler class, but then it showed an error that the compiler expected a class name before the '{' character right at the place where I started writing the code for the derived class. Thus I decided to move the code for the derived class to the header, but I decided to seek your advice before heading further as I fear that more errors may come up and as I am kind of a beginner at C++.
Thanks in advance !
EDIT : I also doubt if it was because I wrote a comment near the starting line of the abstract class as the syntax highlighter here showed the comments in colour.
Edit: I resolved the issue up there (it was due to the misplaced comment), but a new issue has popped up saying that it expected an initialiser before the '<' token at the places where I had defined the functions in the derived class. This is where my actual is.
My snippets of main concern:
void Serial_Handler<char>::write_to_device(char *send_data){
        Serial.println(*send_data);
 }

void Serial_Handler<char*>::read_from_device(char *store_location){
       *store_location = Serial.read();
}

I doubt if these will be able to handle long sentences or have syntax errors.
Edit
I decided to move forward despite errors. Here's how I remade my header file:
#ifndef Devices_h
#define Devices_h

/* Initial build for MCUOS
Anybody can edit this according to their device needs */

#include "Arduino.h"

template < typename datatype>
class Device_Handler
{
               // a class to handle devices
    public:
        virtual void write_to_device(datatype *send_data)= 0; // write data to device
        virtual void read_from_device(datatype *store_location)= 0 ; // read data from device to location
        virtual void clear_device() = 0; // clear device state
};

class Serial_Handler:public Device_Handler<char*>
{
   public:
          void write_to_device(char *send_data);
          void read_from_device(char *store_location);
          void clear_device();
};

void Serial_Handler::write_to_device(char *send_data){
        Serial.println(*send_data);
 }

void Serial_Handler::read_from_device(char *store_location){
       *store_location = Serial.read();
}

void  Serial_Handler::clear_device(){
        Serial.flush();
}

#endif

Here's the sketch code:
#include <Devices.h>

Serial_Handler myserial;
char storage = '\0';
char test_string[] = "Hello";

void setup() {
  Serial.begin(9600);
  myserial.write_to_device(test_string);
  myserial.read_from_device(&storage);
}

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

}

(I know that the code up there may also be faulty)
and errors come up:
Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"
Devices_Test:3:16: error: cannot declare variable 'myserial' to be of abstract type 'Serial_Handler'

 Serial_Handler myserial;

                ^~~~~~~~

In file included from C:\Users\<smbdy>\Documents\Arduino\Devices_Test\Devices_Test.ino:1:0:

C:\Users\<smbdy>\Documents\Arduino\libraries\Devices/Devices.h:19:7: note:   because the following virtual functions are pure within 'Serial_Handler':

 class Serial_Handler:public Device_Handler<char*>

       ^~~~~~~~~~~~~~

C:\Users\<smbdy>\Documents\Arduino\libraries\Devices/Devices.h:14:16: note:     void Device_Handler<datatype>::write_to_device(datatype*) [with datatype = char*]

   virtual void write_to_device(datatype *send_data)= 0; // write data to device

                ^~~~~~~~~~~~~~~

C:\Users\<smbdy>\Documents\Arduino\libraries\Devices/Devices.h:15:16: note:     void Device_Handler<datatype>::read_from_device(datatype*) [with datatype = char*]

   virtual void read_from_device(datatype *store_location)= 0 ; // read data from device to location

                ^~~~~~~~~~~~~~~~

exit status 1

cannot declare variable 'myserial' to be of abstract type 'Serial_Handler'

How should I resolve this?

The Serial_Handler is not a template, so you are not supposed to be using SerialHandler <...> ::write_to_device / read from device

I edited it. Thanks @KIIV

Now I have run into another problem.

I defined the derived class definitions for the virtual functions is Device_Handler class but still the error came up... that is what is bothering me now.

Well, apparently that overrides are not the same as those pure virtual methods in the parent

@KIIV how come that be so ? I'd like to understand that a bit..

Also, I hope you know that I am a bit of a beginner ':)

The datatype is char*, that results into   char ** send_data etc. But don't worry, I didn't noticed this one much sooner

Let us continue this discussion in chat.

You are on the track, but it needs some adjustments:
template < typename datatype>
class Device_Handler
{
    // a class to handle devices
    public:
        virtual void write_to_device(datatype *send_data)= 0; // write data to device
        virtual void read_from_device(datatype *store_location)= 0 ; // read data from device to location
        virtual void clear_device() = 0; // clear device state
};

class Serial_Handler:public Device_Handler<char> // instead of char*
{
   public:
       void write_to_device(char *send_data) override;
       void read_from_device(char *store_location) override;
       void clear_device() override;
};

void Serial_Handler::write_to_device(char *send_data){ // It's not template, so no template specialization
        Serial.println(*send_data);
 }

void Serial_Handler::read_from_device(char *store_location){
       *store_location = Serial.read();
}

void Serial_Handler::clear_device(){
        Serial.flush();
}

The alternative is:
template < typename datatype>
class Device_Handler
{
    // a class to handle devices
    public:
        virtual void write_to_device(datatype send_data)= 0; // write data to device
        virtual void read_from_device(datatype store_location)= 0 ; // read data from device to location
        virtual void clear_device() = 0; // clear device state
};

class Serial_Handler:public Device_Handler<char*>
{
   public:
       void write_to_device(char *send_data) override;
       void read_from_device(char *store_location) override;
       void clear_device() override;
};

I worked it out.. thanks !

I have edited my project and it's in Github :https://github.com/Coder-X15/MCUOS


text:
Does UNO and Nano have the same pins?
Do Arduino Nano Atmega328p have the same pins as Arduino/Gizduino Uno Atmega328p?

uno and nano are about the two closest together AVR boards; nano is a small uno.

The '328P uC on the boards is the same die. The 328P in DIP has 4 fewer pins brought out (Vcc, Gnd, A6, A7) compared to the surface mount parts. The boards themselves then bring the pins out to edge connectors in physically different locations.

Gizmoduino Uno has SMD ATmega328 with A6 and A7 brought out


text:
Outputting 400 mV using Arduino Nano PWM pin

I am trying to output analog voltage (400 mV) using Arduino Nano PWM pins. Is it okay to directly connect (using jumper wires) the PWM pins to the Vin+ of the INA219 current sensor?
I badly need it for my graduation project. Thanks for the help.

I think adding several capacitors of different sizes between the arduino PWM pin and ground would smoothout the PWM signal into constant voltage. Could you show us how yor circuit works?

I inserted my circuit connection above. Can you help me?

So you just want the INA219 to show value of 400mV? There is no circuit that actually uses that voltage? You can achieve that in simpler ways then using an Arduino.

It's unclear why exactly you want this 400mV voltage (or other voltages as well)? You can build a voltage divider from 2 resistors to get 400mV from 5V and GND. Or for general voltages, you want to build a DAC (https://www.youtube.com/watch?v=Y2OPnrgb0pY)

Yes, why do you think you want to generate 400mV?

@FilipFranik please don't use just capacitors. You'd need a resistor as well, or you'll end up destroying the Arduino pin.

@FilipFranik I think you were thinking of a low pass filter. It has a resistor and capacitor as mentioned by Gerben. You can add a second low pass filter to the output of the first filter if needed.

@sa_leinad i guess you are correct. A low pass filter is used to make a simple DAC https://create.arduino.cc/projecthub/Arduino_Scuola/build-a-simple-dac-for-your-arduino-4c00bd

PWM pins don't output analog voltages. They output pulses of 5V. You then need to average the output in order to get an actual analog voltage out of it. You should be able to use a capacitor and resistor to average out the voltage of the PWM pin, making a low-pass filter. You won't get exactly to 400mV. If I remember correctly the PWM pin has a value of 0 - 255, and 1/255 is 0.0196 V after a good low-pass filter, or 19.6 mV, so analogWrite(pin,20) should get close to the 400mV you want.
Another option would be to use a voltage divider to the output to get the output you want. That way you can use the full range of analogWrite() in producing the 400 mV and smaller voltages, thus gaining precision. Then again, if all you want is a fixed 0 or 400mV you could accomplish that with a digital output pin and a fixed voltage divider - no need for PWM.

Of course it's possible !
Duncan you made a little error of 10^2 ;)
5V / 1023 = 0.004887.. = 4.88mV
For 400mV you got 400/4.88 = 81.9.
So in the arduino a value of 82 (0-1023) will send you an output of 400.16mV after beeing redressed by a RC filter.

Please adjust your calculations based on this page: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/


text:
'Var' does not name a type!
I don't have much experience in C++ programming. I'm getting this error
'z' does not name a type!!!
which I have't seen in MATLAB or python... What's wrong??? It is so simple!!!
float x=10; float y=50; float z;
z=x*y;

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

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

float z=x*y; will work

You cannot put an expression statement outside a function. Only the variable declarations can be placed outside functions (and those variables are called globals/global variables).
Try the following:
float x=10; float y=50; float z;

void setup() {
  // put your setup code here, to run once:
  z=x*y;
}

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

Update
What even is easier and also works (thanks to Ruslan and Juraj):
float x=10; float y=50; float z=x*y;

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

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

Thank you. pretty much basic thing that I didn't know about C++.

You can put an expression outside a function (e.g. float z=x*y; does have an expression x*y in it, and may appear in namespace scope). What you can't put there is an expression statement (or any other type of statements).

@Ruslan Thanks for the clarification; I added the word statement in my answer.

and float z=x*y;


text:
using a switch case with a 5-position switch and serial output
I'm trying to get started on developing a menu system for my LCD1602. I have a Parallax 5-position switch (up,down,left,right,center) and I would like to interface the two.
I've been trying to get some code working but I'm kind of lost. I don't have a lot of recent experience with Arduino and could use some advice. I realize that there is a version of the 1602 that comes with a keypad integrated into the circuit but I don't have that model. I have a plain-jane screen and a separate 5-position switch.
I'm also aware that the easiest way to accomplish what I desire is with a resistor network and mapping the ADC values. However, I don't want to make an analog switch, I want to make a digital switch.
Is there any way I can take the pins and put them into an array and then translate that into a switch case statement?
I've tried several different ideas and nothing seems to be working. Forgive the example code, it's hacked together.
below is my code
*/

// constants won't change. They're used here to set pin numbers:
char buttonChar1 = 'a';     // the number of the pushbutton pin
const int buttonPin1 = 2;
const int buttonPin2 = 3;
const int buttonPin3 = 4;
const int buttonPin4 = 5;
const int buttonPin5 = 6;
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState1 = 0; // variable for reading the pushbutton status
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
int buttonState5 = 0;
int pinsArray[5] = {2, 3, 4, 5, 6};
void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);
  pinMode(buttonPin4, INPUT);
  pinMode(buttonPin5, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState1 = digitalRead(buttonPin1) == 2;
  buttonState2 = digitalRead(buttonPin2) == 3;
  buttonState3 = digitalRead(buttonPin3) == 4;
  buttonState4 = digitalRead(buttonPin4) == 5;
  buttonState5 = digitalRead(buttonPin5) == 6;
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:

  switch (pinsArray[5]) {
    case 2:    //
      digitalWrite(ledPin, HIGH);
      Serial.println("button1");
      break;
    case 3:     //
      digitalWrite(ledPin, HIGH);
      Serial.println("dim");
      break;
    case 4:    //
      Serial.println("medium");
      break;
    case 5:    //
      Serial.println("bright");
      break;
  }
  }

When you want to perform actions in response to button presses, you
should take care of reacting to the signal edges rather than levels.
In other words, you perform the action only when the signal changes from
LOW to HIGH, not every time you see it HIGH.
You should also read about button bounce, and either implement your own
debouncing or use an existing library. Below is an example using
Bounce2, but there are other options:
#include <Bounce2.h>

const uint8_t pinDim    = 3;
const uint8_t pinMedium = 4;
const uint8_t pinBright = 5;

Bounce buttonDim, buttonMedium, buttonBright;

void setup() {
    buttonDim.attach(pinDim, INPUT);
    buttonMedium.attach(pinMedium, INPUT);
    buttonBright.attach(pinBright, INPUT);
}

void loop() {
    buttonDim.update();
    buttonMedium.update();
    buttonBright.update();

    if (buttonDim.rose()) {
        Serial.println("dim");
    }
    if (buttonMedium.rose()) {
        Serial.println("Medium");
    }
    if (buttonBright.rose()) {
        Serial.println("bright");
    }
}

You could also, as suggested in Michel Keijzers' answer, use arrays for
the pins and Bounce objects. While these would help streamline the
calls to attach() and update(), they will not help with the meaty
part of the code, i.e. reacting to the presses. There, I would prefer
the button to have descriptive names.

I'm not sure debouncing is really important here ... it seems the menu items are 'dim' bright', 'medium' ... so it does not matter if a button is seen two or twenty times (the result will be still dim or bright). It matters when it is used to increment/decrement or doing an action where the number of button presses matter.

@MichelKeijzers: It makes a difference for the serial output. Admittedly, this may not be an important functionality...

Upvoted ... you are right ... however, I thought the Serial.println was only for debugging purposes.

Michael has already given you some excellent advice on how to clean up your code.
Your switch statement does not make much sense. You're switching based on an out-of-range index into an array of constants.
Once you've read the states of all your buttons as outlined by Michael, your loop needs to decide what to do about the state of each switch.
Is this a joystick style switch, where the user can only engage one direction at a time? Or is it possible to press 2 switches at once?
If it's a diamond arrangement of 5 switches with a switch in the middle, the user could press any combination of switches at the same time.
I'd suggest code like this:
void loop() {
    if buttonStates[0] == HIGH {
       //code to handle button 0 (pin 2) being pressed
    }

    if buttonStates[1] == HIGH {
       //code to handle button 0 (pin 3) being pressed
    }
    //And so on for the rest of your switches.
}

Upvoted for giving an 'actual'  solution.

Edgar's point about detecting a CHANGE of switch state is a good one, as is his point that you'll need to debounce your buttons. In my projects I created something similar to the Bounce class. My buttons can either be edge sensitive or state sensitive.

I'm not sure debouncing is really important here ... it seems the menu items are 'dim' bright', 'medium' ... so it does not matter if a button is seen two or twenty times (the result will be still dim or bright). It matters when it is used to increment/decrement or doing an action where the number of button presses matter.

Next time align your code with ctrl-K (after selecting).
And yes, you can heavily optimize your code (for maintainability) using arrays:
Instead of
const int buttonPin1 = 2;
const int buttonPin2 = 3;
const int buttonPin3 = 4;
const int buttonPin4 = 5;
const int buttonPin5 = 6;

use
const int buttonPins[] = { 2, 3, 4, 5, 6 };

In software engineering it's normal to start with index 0 (such as an array index).
For the button states:
int buttonState1 = 0; // variable for reading the pushbutton status
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
int buttonState5 = 0;

you can use
boolean buttonStates[5];
for (uint8_t buttonIndex = 0; buttonindex < 5; buttonIndex++)
{
    buttonStates[buttonIndex]= false;
}

Instead of setting the pin modes:
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
pinMode(buttonPin4, INPUT);
pinMode(buttonPin5, INPUT);
Use a for loop:
for (uint8_t buttonIndex = 0; buttonindex < 5; buttonIndex++)
{
   pinMode(buttonPins[buttonIndex], INPUT);
}

You can combine the two for loops above with one.
To read the button states:
buttonState1 = digitalRead(buttonPin1) == 2;
buttonState2 = digitalRead(buttonPin2) == 3;
buttonState3 = digitalRead(buttonPin3) == 4;
buttonState4 = digitalRead(buttonPin4) == 5;
buttonState5 = digitalRead(buttonPin5) == 6;

Use
for (uint8_t buttonIndex = 0; buttonindex < 5; buttonIndex++)
{
   buttonStates[buttonIndex] = digitalRead(buttonPins[buttonIndex]) == buttonPinds[buttonIndex]) ? true : false;
}

For the switch, I think you need to keep it as it differs per pin.
And instead of using the value 5 use e.g.:
const uint8_t NR_OF_BUTTONS = 5;

and use the NR_OF_BUTTONS constant everywhere.
Note: I don't have a compiler at hand, so forgive me for any possible compiler errors.
Also, instead of multiple arrays (each of length NR_OF_BUTTONS), you can use an array of a struct which contain the pin number and state, but this is maybe beyond the scope of your programming knowledge. The use of arrays is already a huge improvement.


text:
Is it possible to use Arduino PWM for audio within a PAM8493 amplifier?
I've seen some projects using PWM for playing audio files, and it seems like it needs an amplifier, otherwise the sound is very low.
I already made a project using a DFPlayer and PAM8403, but now I need more control over the files in the SD Card which is not supported by the DFPlayer library, so it seems like I need to use PWM and a SD Card module, instead of a separate audio module.
My questions are, can I simply connect the PWM output to the amplifier (PAM8403) and I will be able to control volume (using the programming language) and have a good quality sound?

Are you using a basic Arduino board (not I2S) and a sampling frequency of 8 kHz or 16 kHz? That could interfere with the default switching frequency of 260 kHz.
My suggestion is to use a low pass RC filter.
You might have to lower the signal level from the Arduino.
The PAM8403 requires a series capacitor and resistor at the input (those are probably already on the amplifier module).
In the end you probably need a voltage divider with a capacitor to ground for each channel.
I don't know if your PWM library has volume control. The TMRh20 has a function to set the volume.
The overall quality will be reasonable, but not very good. There are MP3 shields that can play mp3 files from a SD memory card. Those have better quality.
[ADDED]
I think I have misunderstood your question. Sorry. I'm still not sure that I understand your question now.
Wiki of DFPlayer Mini: DFRobot:DFPlayer Mini
Code on Github for DFPlayer Mini: Github:DFPlayer Mini
The PAM8403 has no volume control, you need to adjust the audio signal that is going to the PAM8403 module.
The DFPlayer Mini code has functions for volume, volumeUp, volumeDown and readVolume. However, it does not seem to have a function to select a specific file.
The Adafruit Music Maker shield is in two versions, one has an amplifier onboard: Adafruit:Music Maker MP3 Shield for Arduino w/3W Stereo Amp - v1.0. With that shield, you can play a file by its name. It can also set the volume. I suppose that is what you want ?

I already have a project running with DFPlayer, but now I need to have control over the fles in the SDCard and it seems like none of the mp3 modules provides that. I can chose any board. Currently the DFPlayer project was made with a nodemcu

@Valdir, I have added a [ADDED] section. In my opinion, every "normal" mp3 player module can select a file, only the very cheap ones can only play the next one, but not a specific file.

Note that if using the TMRh20 library, which uses raw PWM to generate audio, the correct "audio amplifier" to use to drive the speaker is a DC motor driver (H bridge), such as one from Pololu.


text:
How to select hardware for my Arduino board?
As I embark on my first Arduino project, I have lots of questions. Specifically, what considerations should I make when selecting equipment, and what are the critical parameters to safe operation?
Some elaboration upon my questions can be seen below. However, outlining general principals of equipment selection would be highly useful.
I have an Arduino Uno. The Uno has an input voltage of 6-20 V, and operating voltage of 5 V as from the tech specs. Does this mean that I can select any sensor with less than 20 V output to send data to my Arduino?
I am interested in using a sensor like this
 Texas Instruments HDC1080 High Accuracy Digital
Humidity Sensor, which has a supply of 5.5 V. If my logic is correct, this output should be fine. I should know whether or not I need to buy some sort of shield based purely upon the output pins of the sensor, correct? I know I have 6 analog and 6 PWM/digital pins on the Arduino, so the digital signal should be capable of being processed by my Arduino. However, the interface type on the sensor product is I2C, but I am unsure as to what this means or if it needs to be a consideration.

One question you have (3rd paragraph) brings a caution to mind. Your inputs to the Arduino are typically going to be 5v based, either digital or analog, although I may be phrasing this slightly loosely. A sensor not of the type you reference would provide a digital signal (Low/High relative to ground) or analog, which would be limited via external circuitry to 5v or lower. I think there's a good chance that if you find and use a sensor that pumps 20v into your Arduino, the smoke might be released.
I've read over the sensor you've linked. It was fascinating reading. It appears that the device is focused on being connected to a PC with USB and a Windows interface, but permits direct register access for specific data.
You'd want to research the best way to connect an i2c device to your Arduino, and I'm certain there are plenty of libraries for that. A good place to start is the reference on the "official" Arduino web site for i2c. This same page references use of the library, calling/polling the device and reading/writing data.
What I read in the volumes of the data sheets and user guides for the device you linked appears to cover everything you need to know and a tremendous amount of information you may not need.
It looks like a fun project and well engineered, at least from the sensor reference.

To be clear, you are saying that although the arduino specs say that my input voltage is up to 20 V, I really should stick to near 5?

Your input voltage for powering the Arduino may be as high as 20v, but the signals the unit can safely handle should be limited to 5v and there's a possibility that some devices will restrict this to 3.3v, but my brain cells are on hiatus at the moment and I'm not confident about the last statement. Excessive voltage to power the Arduino will also be shed as heat via the regulator circuit.

I think you are correct that some boards like the arduino pro have a smaller limit of 3.3v, but  what is input voltage supposed to mean if not the signal voltage that you can feed into the board?

One quick add here. I did a search for maximum power for Arduino and the search results return a maximum of 12v for the Arduino Uno. Most of the projects I've built have used either six or nine volts to power the board. Twelve volts may not create excessive heat, as the board is rated to handle that level.

"what is input voltage supposed to mean if not the signal voltage" The input voltage in this case refers only to the power supplied to the Arduino board for powering the MCU and will be regulated down to 5v. Excess power will be dissipated by the regulator as heat. From the point of view of the MCU, both its operating voltage and its input signals are expected to be 5v. (This is a slight simplification; the MCU could, on a differently designed board, be run at somewhat lower voltages.)

For your first project, power the Arduino Uno with the USB cable and use everything at 5V.
There are tutorials which guide you step-by-step to make something. The Adafruit tutorials are very good.
The HDC1080 is a sensor that works at 3.3V and at 5V. That means you can use it with the 5V Arduino Uno without problem.
This Tindie HDC1080 module points to a HDC1080 library on Github. I suggest you try to make that work.
If you can not get data out of the sensor, then you should start with something very simple. A few leds (with series resistors) or a LDR light sensor is fun to start with.
As soon as you start using higher voltages (for example 12V) you might consider buying a spare Arduino Uno, because the Arduino Uno will be blown when 12V touches one of the pins.
Be also careful with sensors that can only handle 3.3V and not 5V. Since the Arduino Uno runs at 5V, a pin of the Arduino could feed 5V into the sensor and damaging the 3.3V sensor.