text:
Run function when triggered
I'm trying to create a motion/fall sensing device. I have a sensor that continuously checks if motion and fall is detected in void loop(). If both motion and fall are detected, then I'd like to send an image to my computer. My image capture function is camCapture(). The problem is that once the motion and fall detected, it continuously calls camCapture() and repeatedly sends images to the computer given that camCapture() is called in void loop(). I'd like to only send a single image when it is triggered, and a single image every time it is triggered thereafter.
For example, if the motion and fall is triggered, then send an image once. If it detects motion and fall again after it has already gone back to LOW, then send an image again once.
I can't use setup() since I can only run a function once, and it defeats the purpose of what I'm trying to do. My void loop() code is below.
void loop()
{
  // Read data from accelerometer
  mma.read();
  sensors_event_t event;
  mma.getEvent(&event);

  // Store magnitude of all axis
  magnitude = calculateMagnitude(event.acceleration.x, event.acceleration.y, event.acceleration.z);

  // Motion is detected! 20 seconds will be given to detect a fall from the accelerometer
  if(digitalRead(pirSensor) == HIGH)
  {
    num_timeAtPIR = millis(); // Time that PIR sensor was activated with respect to the system time
    bool_waitForAccel = 1; // Set flag to true to wait for accelerometer
    Serial.println("Motion detected!");
    digitalWrite(buzzer, LOW);
    //delay(1000);

  }
  else if(magnitude > sensitivity)
  {
    num_timeAtAccel = millis();
    Serial.println("Fall detected!");
    Serial.print("Magnitude is: ");
    Serial.println(magnitude);
    bool_waitForPIR = 1; // Waiting for PIR
    Serial.println();

    digitalWrite(buzzer, HIGH);
    delay(4000);

  }
  else // No motion is detected
  {
    Serial.println("No motion detected! :(");
    bool_waitForPIR = 0;
    bool_waitForAccel = 0;
    Firebase.setInt(firebaseData, pirPath, 0);
    Firebase.setInt(firebaseData, accelPath, 0);
    digitalWrite(buzzer, LOW);
  }

  // Motion then Fall are detected. Alarm is activated and picture is captured and save onto server.
  if(bool_waitForAccel == 1 && (magnitude > sensitivity))
  {

    Serial.println("Motion and Fall detected!");
    Serial.print("Magnitude is: ");
    Serial.println(magnitude);
    bool_waitForAccel = 0; // No longer waiting for accelerometer
    Serial.println();

    digitalWrite(buzzer, HIGH);
    delay(4000);

    camCapture(); // Take picture!

  }

  // Fall then motion are detected. Alarm is activated and picture/video is captured to save onto website.
  else if(bool_waitForPIR == 1 && (magnitude > sensitivity))
  {
    Serial.println("Fall detected");
    Serial.print("Magnitude is: ");
    Serial.println(magnitude);
    Serial.println();

    bool_waitForPIR = 0; // No longer waiting for PIR

    digitalWrite(buzzer, HIGH);

    delay(4000);

    camCapture(); // Take picture!

  }

  // 20 second timer to check if a Fall is detected after Motion is detected.
  if(millis() > (num_timeAtPIR + period))
  {
    bool_waitForAccel = 0; // Set flag to false
  }
  else if(millis() > (num_timeAtAccel + period)) // 20 second timer to check if Motion is detected after a fall is detected
  {
    bool_waitForPIR = 0;
  }

}

UPDATE 1: Posting the rest of the code.
// Program header files
#include <Wire.h>
#include <WiFi.h>
#include <WebServer.h>
#include <ArduCAM.h>
#include <SPI.h>
#include "FS.h"
#include "FirebaseESP32.h"
#include "memorysaver.h"
#include <Adafruit_MMA8451.h>
#include <Adafruit_Sensor.h>

//Time and Date NTP Server Header
#include <NTPClient.h>
#include <WiFiUdp.h>

//Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

//Variables to save date and time
String formattedDate = "";
String dayStamp = "";
String timeStamp = "";

String logPath = "/Log";
String tempPath = "/Log/Temperature";
String pirPath = "/Log/PIR_Sensor";
String accelPath = "/Log/Accelerometer";
String pirDatePath = "/Log/pir_Date";
String pirTimePath = "/Log/pir_Time";
String accelDatePath = "/Log/accel_Date";
String accelTimePath = "/Log/accel_Time";

// Database/Wi-Fi configuration
#define FIREBASE_HOST "host"
#define FIREBASE_AUTH "auth"
#define AP_SSID "apssid"
#define AP_PASSWORD "password"

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "passsword"

// Variables to keep track of previous and current time to create a delay
unsigned long currentTime = 0;
unsigned long prevTime = 0;

unsigned long bool_waitForAccel = 0; // Used to flag the accelerometer
unsigned long bool_waitForPIR = 0; // Used to flag the PIR
unsigned long num_timeAtPIR = 0; // Used to keep track of the time the PIR sensor detected motion
unsigned long num_timeAtAccel = 0; // Used to keep track of the time the accelerometer detected a fall
unsigned long period = 20000; // Amount of time given to check after motion is detected

int statusLED = 26; // Choose the pin for status LED
int buzzer = 12; // Choose the pin for Piezzo Buzzer. Connected from MOSFET gate.
int tempSensor = 2; // Choose pin for Temperature Sensor
int pirSensor = 27; // Choose pin for controller PIR Sensor

int PIR_Power = 25; // Controls Power gate for PIR Sensor
int ArduCAM_Power = 32; // Controls Power gate for ArduCAM

const int CS = 5; // GPIO5 as Slave Select for ArduCAM

int wifiType = 0; // 0: Station    1: AP (Access Point)

// Set up requests to send captured image to external server
bool onlineMode = true;
String start_request = "";
String boundary = "_cam_";
String end_request = "\n--" + boundary + "--\n";

// Set buffer size for camera data
static const size_t bufferSize = 2048;
static uint8_t buffer[bufferSize] = {0xFF};
byte buf[256];
static int iPic = 0;
static int kPic = 0;
uint8_t temp = 0, temp_last = 0;
uint32_t len = 0;
bool is_header = false;

// Threshhold for declaring a fall on the accelerometer
float sensitivity = 11.0;

float magnitude = 0.0; // Stores the calculated magnitude

// Accelerometer, Semaphore, and Firebase instances
Adafruit_MMA8451 mma = Adafruit_MMA8451();
FirebaseData firebaseData;

#if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
ArduCAM myCAM(OV2640, CS);
#endif

WiFiClient client;

void start_capture()
{
  myCAM.clear_fifo_flag();
  myCAM.start_capture();
}

void camCapture()
{
  digitalWrite(ArduCAM_Power, HIGH);

  // Flush the FIFO
  myCAM.flush_fifo();
  // Clear capture done flag
  myCAM.clear_fifo_flag();
  // Start capture
  myCAM.start_capture();

  Serial.println("Start capture!");
  while(!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));

  len = myCAM.read_fifo_length();
  Serial.print("The FIFO length is: ");
  Serial.println(len);

  if(len >= MAX_FIFO_SIZE) // 8M
  {
    Serial.println("Over size!");
  }
  if(len == 0) // 0KB
  {
    Serial.println("Size is 0KB");
    return;
  }

  long full_length;
  if(client.connect("xx.xx.xx.xx", 80) || onlineMode)
  {
    if(onlineMode)
    {
      while(client.available())
      {
        String line = client.readStringUntil('\r');
      }
    }

  start_request = start_request +
  "\n--" + boundary + "\n" +
  "Content-Disposition: form-data; name=\"data\"; filename=\"CAM.jpg\"\n" +
  "Content-Transfer-Encoding: binary\n\n";

  full_length = start_request.length() + len + end_request.length();
  client.println("POST /uploads.php HTTP/1.1");
  client.println("Host: xx.xx.xx.x");
  client.println("Content-Type: multipart/form-data; boundary =" + boundary);
  client.print("Content-Length: "); client.println(full_length);
  client.println();
  client.print(start_request);

  iPic = 0;

  static uint8_t buffer[bufferSize] = {0xFF};

  while (len--)
  {
    temp_last = temp;
    temp =  SPI.transfer(0x00);
    //Read JPEG data from FIFO
    if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
    {
      buf[iPic++] = temp;  //save the last  0XD9
      //Write the remain bytes in the buffer
      myCAM.CS_HIGH();
      client.write(buf, iPic);
      //Close the file
      //file.close();
      Serial.println(F("Image save OK."));
      is_header = false;
      iPic = 0;
    }
    if (is_header == true)
    {
      //Write image data to buffer if not full
      if (iPic < 256)
        buf[iPic++] = temp;
      else
      {
        //Write 256 bytes image data to file
        myCAM.CS_HIGH();
        client.write(buf, 256);
        iPic = 0;
        buf[iPic++] = temp;
        myCAM.CS_LOW();
        myCAM.set_fifo_burst();
      }
    }
    else if ((temp == 0xD8) & (temp_last == 0xFF))
    {
      is_header = true;
      buf[iPic++] = temp_last;
      buf[iPic++] = temp;
    }
  }

  // End the POST request to the server
  client.println(end_request);

  myCAM.CS_HIGH();

  // Stop the client
  client.stop();
  digitalWrite(ArduCAM_Power, LOW);
  }
  else // No connection to the server.
  {
    Serial.println("Could not connect to external server!");
    Serial.println("Please check the IP address or Port");
    return;
  }
}

// Calculate the magnitude with the x, y, and z axis of the accelerometer.
// Gives an overall value that is better than just using the z-axis
float calculateMagnitude(float x, float y, float z)
{
  float magnitude = sqrt(sq(x) + sq(y) + sq(z));

  return magnitude;
}

void setup()
{
  Wire.begin();
  Serial.begin(115200);
  SPI.begin();
  SPI.setFrequency(4000000);

  pinMode(CS, OUTPUT);
  pinMode(PIR_Power, OUTPUT); // Set mosfet gate to output for PIR Sensor
  pinMode(ArduCAM_Power, OUTPUT); // Set mosfet gate to output for ArduCAM

  pinMode(statusLED, OUTPUT);      // Declare LED as output
  pinMode(buzzer, OUTPUT);         // Declare Piezo Buzzer as output
  pinMode(pirSensor, INPUT);        // Declare PIR Sensor as input

  Serial.println();

  // Check if accelerometer is properly connected/found
  if(!mma.begin())
  {
    Serial.println("Couldn't start MMA8451 Accelerometer.");
    Serial.println("Check your connections.");
    while(1);
  }
  Serial.println("MMA8451 Accelerometer found!");

  // Set the g-range for the accelerometer. Can be adjusted to 2g, 4g, or 8g.
  mma.setRange(MMA8451_RANGE_2_G);

  // Check if camera is found
  digitalWrite(ArduCAM_Power, HIGH);
  uint8_t vid, pid;
  uint8_t temp;
  while(1)
  {
    //Check if the ArduCAM SPI bus is OK
    myCAM.write_reg(ARDUCHIP_TEST1, 0x55);
    temp = myCAM.read_reg(ARDUCHIP_TEST1);
    if (temp != 0x55) {
      Serial.println(F("SPI interface Error!"));
      delay(2);
      continue;
    }
    else
      break;
  }

  #if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
  //Check if the camera module type is OV2640
  myCAM.wrSensorReg8_8(0xff, 0x01);
  myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
  myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
  if ((vid != 0x26 ) && (( pid != 0x41 ) || ( pid != 0x42 )))
    Serial.println(F("Can't find OV2640 module!"));
  else
    Serial.println(F("OV2640 detected."));
  #endif

  //Change to JPEG capture mode and initialize the OV2640 module
  myCAM.set_format(JPEG);
  myCAM.InitCAM();

  myCAM.OV2640_set_JPEG_size(OV2640_640x480);
  myCAM.clear_fifo_flag();
  // Turn off Camera
  digitalWrite(ArduCAM_Power, LOW);

  // Connect to WiFi
  if (wifiType == 0)
  {
    if(!strcmp(WIFI_SSID,"SSID"))
    {
      Serial.println(F("Please set your SSID"));
      while(1);
    }
    if(!strcmp(WIFI_PASSWORD,"PASSWORD"))
    {
      Serial.println(F("Please set your PASSWORD"));
      while(1);
    }
    // Connect to WiFi network
    Serial.println();
    Serial.print(F("Connecting to: "));
    Serial.println(WIFI_SSID);

    WiFi.mode(WIFI_STA);

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

    while (WiFi.status() != WL_CONNECTED)
    {
      delay(500);
      Serial.print(F("."));
    }

    Serial.println();
    Serial.println(F("WiFi connected"));
    Serial.println();
    Serial.println(WiFi.localIP());
  }
  else if (wifiType == 1)
  {
    Serial.println();
    Serial.println();
    Serial.print(F("Shared AP: "));
    Serial.println(AP_SSID);
    Serial.print(F("The password is: "));
    Serial.println(AP_PASSWORD);

    WiFi.mode(WIFI_AP);

    WiFi.softAP(AP_SSID, AP_PASSWORD);

    Serial.println();
    Serial.print("AP IP Address is: ");
    Serial.println(WiFi.softAPIP());
  }

  // Initialize a NTPClient to get time
  timeClient.begin();
  timeClient.setTimeOffset(-14400);

  //If Firebase is connected, turn on the LED
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);
  digitalWrite(statusLED,HIGH);

  Serial.println("------------------------------------");
  Serial.println("Path exist test...");
  if (Firebase.pathExist(firebaseData, logPath))
  {
    Serial.println("Path " + logPath + " exists");
  }
  else
  {
    Serial.println("Path " + logPath + " does not exist");
    Serial.println("Adding all necessary paths to /Log");
    Serial.println("Will have to reinitialize later once everything is set up.");

     // Initialize All  variables to 0;
    Firebase.setFloat(firebaseData, tempPath, 0.0);
    Firebase.setInt(firebaseData, pirPath, 0);
    Firebase.setInt(firebaseData, accelPath, 0);
    //Firebase.setString(firebaseData, pirDatePath, ???);
    //Firebase.setString(firebaseData, pirTimePath, ???);
    //Firebase.setString(firebaseData, accelDatePath, ???);
    //Firebase.setString(firebaseData, accelTimePath, ???);

  }
  Serial.println("------------------------------------");
  Serial.println();

  digitalWrite(PIR_Power, HIGH);

  digitalWrite(pirSensor, LOW);
  digitalWrite(statusLED, LOW);

  Serial.println("Sensors booting up...");
  delay(10000); // Let sensors boot up, 10s
  Serial.println("Sensors ready!");
}

Thank you for the really well done formatting. So many people post questions with totally crap formatting that make the question very difficult to read and understand.

@JohnRomkey Haha! Thanks, I gotta make everyone’s life a little easier somehow.

You need to add a state variable to your loop() function.
At the start of loop() add a variable declaration like:
void loop()
{
  static bool capture_sent = false;

Then change your line
  if(bool_waitForAccel == 1 && (magnitude > sensitivity))
  {

to
  if(!capture_sent && bool_waitForAccel == 1 && (magnitude > sensitivity))
  {
    capture_sent = true;

or, if you want to perform some of the logic in that stanza and just not call camCapture() then leave the if line alone and make the call to camCapture() conditional upon !capture_sent.
Then in any place in your code where you see the condition which tells you you'd want to call camCapture() again when triggered, reset capture_sent to `false. I'm leaving it up to you to decide where that goes because you understand what conditions determine that.

Awesome! Thanks for the reply! I’ll implement those changes in the morning and let you know how it goes.


text:
Code stuck on mag.getEvent(&event); in HMC5833L Compass
Last week I created some code in which I can run a Ublox GPS NEO-6 and a magnetometer HMC5883L together. Which at the time worked brilliantly.
Yesterday I have attempted to run the code again, with the same connections. No modifications to the code.
The GPS NEO-6 works as expected, the magnetometer not so much. After using serial commands as breakpoints, I am able to see that it gets to the line:
mag.getEvent(&event);

Then I bought two new HMC5883L modules and uploaded the example code, to see if the magnetometer will even run correctly.
The example code returned the basic stats on the breakout board but once again stopped at that line.
Out of curiosity, I removed the magnetometer and ran the program. It displayed exactly the same.
It's not picking up that the HMC5883L is even disconnected.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_HMC5883_U.h>
/* Assign a unique ID to this sensor at the same time */
Adafruit_HMC5883_Unified mag = Adafruit_HMC5883_Unified(12345);

void displaySensorDetails(void)
{
  sensor_t sensor;
  mag.getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" uT");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" uT");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" uT");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

void setup(void)
{
  Serial.begin(9600);
  Serial.println("HMC5883 Magnetometer Test"); Serial.println("");

  /* Initialise the sensor */
  if(!mag.begin())
  {
    /* There was a problem detecting the HMC5883 ... check your connections */
    Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");
    while(1);
  }

  /* Display some basic information on this sensor */
  displaySensorDetails();
}

void loop(void)
{
  /* Get a new sensor event */
 sensors_event_t event;
 mag.getEvent(&event);

 /* Display the results (magnetic vector values are in micro-Tesla (uT)) */
 Serial.print("X: "); Serial.print(event.magnetic.x); Serial.print("  ");
 Serial.print("Y: "); Serial.print(event.magnetic.y); Serial.print("  ");
 Serial.print("Z: "); Serial.print(event.magnetic.z); Serial.print("  ");Serial.println("uT");

 // Hold the module so that Z is pointing 'up' and you can measure the heading with x&y
 // Calculate heading when the magnetometer is level, then correct for signs of axis.
 float heading = atan2(event.magnetic.y, event.magnetic.x);

 // Once you have your heading, you must then add your 'Declination Angle', which is the 'Error' of the magnetic field in your location.
 // Find yours here: http://www.magnetic-declination.com/
 // Mine is: -13* 2' W, which is ~13 Degrees, or (which we need) 0.22 radians
 // If you cannot find your Declination, comment out these two lines, your compass will be slightly off.
 float declinationAngle = 0.22;
 heading += declinationAngle;

 // Correct for when signs are reversed.
 if(heading < 0)
   heading += 2*PI;

 // Check for wrap due to addition of declination.
 if(heading > 2*PI)
   heading -= 2*PI;

 // Convert radians to degrees for readability.
 float headingDegrees = heading * 180/M_PI;

 Serial.print("Heading (degrees): "); Serial.println(headingDegrees);

 delay(500);
}

The wires i used are about 20cm long.

Please add more information to your question. Do you use the adafruit hmc5883 modules or other modules? Do those other modules have level shifters for sda and scl? How long are the wires of the i2c bus? Please also add a link to the used library: https://github.com/adafruit/Adafruit_HMC5883_Unified That library is not very good and contains a bug. It does not test if the hmc5883 is connected and the mag.getEvent function has a while loop that halts everything when the hmc5883 is not connected. That is what you found. I suggest to read the identification registers yourself after the mag.begin

i use 20 cm long jumper wires

and two another libraries i used for clearification are linked as: 1)..link and 2)..https://www.arduinolibraries.info/libraries/grove-3-axis-digital-compass-hmc5883-l

Were you able to solve this problem? @Jot would you specify more clearly what the alternative to _HMC5883_Unified is?

Denis G. Labrecque, sorry Dear, it's been 2 years ago and i haven't clearly remember its solution.

source: Stack Exchange

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

sort: votes


text:
SIM800l doesn't respond on arduino micro
I want my Arduino Micro to interact with my SIM 800 L module. But unfortunately nothing happens, may you can help me figure out where I made a mistake. Here's my wiring:

Summary of my wiring:

External Battery ---> 800L
plus ---> 5VIN
minus ---> GND (both in POWER and UART TTL-Section)

Arduino ---> 800L
RX ---> RXD
TX ---> TXD

With that setup I'm using the following code:
#include <SoftwareSerial.h>
#include<Arduino.h>

//Arduino Micro
//SIM 800l

SoftwareSerial mySerial(1, 0); // RX, TX

void setup()
{
  // Open serial communication
  Serial.begin(9600);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

  Serial.println("Setup finished");

}

void loop() // run over and over
{
  Serial.println("Sending AT command");
  mySerial.write("AT"); //OK should be returned
  delay(1000);
  //read sim-module response
  Serial.println("Response: ");
  while( mySerial.available() )
  {
    char c = mySerial.read();
    Serial.print(c);
  }

  mySerial.write("at+cmee=2"); //set sim-module into debug mode

  delay(1000);

  mySerial.write("at+cpin?"); //check if pin is necessary

  //read sim-module response
  while( mySerial.available() )
  {
    char c = mySerial.read();
    Serial.print(c);
  }

}

But it gives me the following output as a loop:
 Sending AT command
 Response:
 Sending AT command
 Response:
 Sending AT command
 Response:

And I've noticed that a yellow LED is blinking on the Arduino while running the program so I assume there has to be some input from the SIM800 but I can't read the data at the moment. On the 800L-board itself is also an LED that blinks in an interval of about one second, wich tells you that it has no connection (I live in a relatively remote area) but even if there's no connection shouldn't it still return OK when sending AT?
If you need any further information feel free to ask. I would appreciate every idea you come up with :)
Edit: On the photo the wire goes from the Arduino directly to the 800L but I've changed it so the 800L-power comes from a battery now.

Here is some edit in your code
#include <SoftwareSerial.h>
#include<Arduino.h>

//Arduino Micro
//SIM 800l

SoftwareSerial mySerial(9,10); // RX, TX

void setup()
{
  // Open serial communication
  Serial.begin(9600);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

  Serial.println("Setup finished");

}

void loop() // run over and over
{
  Serial.println("Sending AT command");
  mySerial.write("AT\r\n"); //OK should be returned
  delay(1000);
  //read sim-module response
  Serial.println("Response: ");
  while( mySerial.available() )
  {
    String c = mySerial.readString();
    Serial.println(c);
  }

  mySerial.write("at+cmee=2\r\n"); //set sim-module into debug mode

  delay(1000);

  mySerial.write("at+cpin?\r\n"); //check if pin is necessary

  //read sim-module response
  while( mySerial.available() )
  {
    String c = mySerial.readString();
    Serial.println(c);
  }

}

Change UART pins to 9,10 as 0,1 are already used in normal serial. Secondly change Seria.read() to Serial.readString() because as far as i know the response is string.

Thank you for your advice but I still get nothing returned. Only the RX led on my arduino is blinking but nothing arrives on tx. I tried mapping rxd to txd, put it to port 9,10 then back to the RX,TX ports but nothing gets me a response :/

sorry I missed on thing. Carriage Return and EOD character are most important part of AT commands. I just see that those are missing.

Thank you very very much, retrying some wiring positions and the carriage return did the job its woking now :)

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


text:
ESP8266 HTTPS post body request with WifiClientSecure
Is there a way to post HTTPS body request in Arduino esp8266.
I am able to HTTPS parameter request with WifiClientSecure library,but is not safe compared to Request Body send in POST.

You do it like any other POST. It's just you happen to be using a secure client to make the connection.

Open the connection
Send the right headers, including a Content-Type and Content-Length and maybe a Content-Encoding if you encode it.
Send the body

It's not any different to an unencrypted POST request.

Can you provide me some example? or the format to include Request body with
a Content-Type and Content-Length and maybe a Content-Encoding as you said in point 2

Just look at any post request available on any of the millions of examples.

client.print(String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n"+
"Content-Length: " + data.length() + "\r\n" +
"Content-Type: application/json;charset=UTF-8\r\n\r\n"+
data +"\r\n");
data variable will contain json body?
Will this work??


text:
Osepp DS1307 RTC program error (tmElements_t tm; does not name a type)
Using a basic 1307 SetTime program, and ran into a problem (first time programming a module).
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>

const char *monthName[12] = {
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

tmElements_t tm;

void setup() {
  bool parse=false;
  bool config=false;

  // get the date and time the compiler was run
  if (getDate(__DATE__) && getTime(__TIME__)) {
    parse = true;
    // and configure the RTC with this info
    if (RTC.write(tm)) {
      config = true;
    }
  }

  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor
  delay(200);
  if (parse && config) {
    Serial.print("DS1307 configured Time=");
    Serial.print(__TIME__);
    Serial.print(", Date=");
    Serial.println(__DATE__);
  } else if (parse) {
    Serial.println("DS1307 Communication Error :-{");
    Serial.println("Please check your circuitry");
  } else {
    Serial.print("Could not parse info from the compiler, Time=\"");
    Serial.print(__TIME__);
    Serial.print("\", Date=\"");
    Serial.print(__DATE__);
    Serial.println("\"");
  }
}

void loop() {
}

bool getTime(const char *str)
{
  int Hour, Min, Sec;

  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec;
  return true;
}

bool getDate(const char *str)
{
  char Month[12];
  int Day, Year;
  uint8_t monthIndex;

  if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
  for (monthIndex = 0; monthIndex < 12; monthIndex++) {
    if (strcmp(Month, monthName[monthIndex]) == 0) break;
  }
  if (monthIndex >= 12) return false;
  tm.Day = Day;
  tm.Month = monthIndex + 1;
  tm.Year = CalendarYrToTm(Year);
  return true;
}

And I got the following
"tmElements_t tm;" does not name a type.

According to example ReadTest/ReadTest.ino, you have to include
#include <TimeLib.h>

See also comment from Alexander below (unchecked by me) that Time.h needs to be referenced.

Added that to the code, and it tells me there is no such file or directory.

Maybe you used another library (you could try this one instead?) I never used this or the other library myself btw.

Arduino Studio also need to reference Time Library.

I'm pretty sure I used the right library, and it's in the Arduino library folder. Changed it to <TimeLib.h> and ran into the invalid library issue. I put on my TFT shield and tested the examples for that and it ran fine. Maybe something else that I am missing... First time wiring up a module.


text:
White screen when I perform grapicstest in ili9341
I get a white screen when I perform grapicstest in ili9341. I used the below code:
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

// For the Adafruit shield, these are the default.
#define TFT_DC 9
#define TFT_CS 10

// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// If using the breakout, change pins as desired
//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);

void setup() {
  Serial.begin(9600);
  Serial.println("ILI9341 Test!");

  tft.begin();

  // read diagnostics (optional but can help debug problems)
  uint8_t x = tft.readcommand8(ILI9341_RDMODE);
  Serial.print("Display Power Mode: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDMADCTL);
  Serial.print("MADCTL Mode: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDPIXFMT);
  Serial.print("Pixel Format: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDIMGFMT);
  Serial.print("Image Format: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDSELFDIAG);
  Serial.print("Self Diagnostic: 0x"); Serial.println(x, HEX);

  Serial.println(F("Benchmark                Time (microseconds)"));
  delay(10);
  Serial.print(F("Screen fill              "));
  Serial.println(testFillScreen());
  delay(500);

  Serial.print(F("Text                     "));
  Serial.println(testText());
  delay(3000);

  Serial.print(F("Lines                    "));
  Serial.println(testLines(ILI9341_CYAN));
  delay(500);

  Serial.print(F("Horiz/Vert Lines         "));
  Serial.println(testFastLines(ILI9341_RED, ILI9341_BLUE));
  delay(500);

  Serial.print(F("Rectangles (outline)     "));
  Serial.println(testRects(ILI9341_GREEN));
  delay(500);

  Serial.print(F("Rectangles (filled)      "));
  Serial.println(testFilledRects(ILI9341_YELLOW, ILI9341_MAGENTA));
  delay(500);

  Serial.print(F("Circles (filled)         "));
  Serial.println(testFilledCircles(10, ILI9341_MAGENTA));

  Serial.print(F("Circles (outline)        "));
  Serial.println(testCircles(10, ILI9341_WHITE));
  delay(500);

  Serial.print(F("Triangles (outline)      "));
  Serial.println(testTriangles());
  delay(500);

  Serial.print(F("Triangles (filled)       "));
  Serial.println(testFilledTriangles());
  delay(500);

  Serial.print(F("Rounded rects (outline)  "));
  Serial.println(testRoundRects());
  delay(500);

  Serial.print(F("Rounded rects (filled)   "));
  Serial.println(testFilledRoundRects());
  delay(500);

  Serial.println(F("Done!"));

}

void loop(void) {
  for(uint8_t rotation=0; rotation<4; rotation++) {
    tft.setRotation(rotation);
    testText();
    delay(1000);
  }
}

unsigned long testFillScreen() {
  unsigned long start = micros();
  tft.fillScreen(ILI9341_BLACK);
  yield();
  tft.fillScreen(ILI9341_RED);
  yield();
  tft.fillScreen(ILI9341_GREEN);
  yield();
  tft.fillScreen(ILI9341_BLUE);
  yield();
  tft.fillScreen(ILI9341_BLACK);
  yield();
  return micros() - start;
}

unsigned long testText() {
  tft.fillScreen(ILI9341_BLACK);
  unsigned long start = micros();
  tft.setCursor(0, 0);
  tft.setTextColor(ILI9341_WHITE);  tft.setTextSize(1);
  tft.println("Hello World!");
  tft.setTextColor(ILI9341_YELLOW); tft.setTextSize(2);
  tft.println(1234.56);
  tft.setTextColor(ILI9341_RED);    tft.setTextSize(3);
  tft.println(0xDEADBEEF, HEX);
  tft.println();
  tft.setTextColor(ILI9341_GREEN);
  tft.setTextSize(5);
  tft.println("Groop");
  tft.setTextSize(2);
  tft.println("I implore thee,");
  tft.setTextSize(1);
  tft.println("my foonting turlingdromes.");
  tft.println("And hooptiously drangle me");
  tft.println("with crinkly bindlewurdles,");
  tft.println("Or I will rend thee");
  tft.println("in the gobberwarts");
  tft.println("with my blurglecruncheon,");
  tft.println("see if I don't!");
  return micros() - start;
}

unsigned long testLines(uint16_t color) {
  unsigned long start, t;
  int           x1, y1, x2, y2,
                w = tft.width(),
                h = tft.height();

  tft.fillScreen(ILI9341_BLACK);
  yield();

  x1 = y1 = 0;
  y2    = h - 1;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = w - 1;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t     = micros() - start; // fillScreen doesn't count against timing

  yield();
  tft.fillScreen(ILI9341_BLACK);
  yield();

  x1    = w - 1;
  y1    = 0;
  y2    = h - 1;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = 0;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t    += micros() - start;

  yield();
  tft.fillScreen(ILI9341_BLACK);
  yield();

  x1    = 0;
  y1    = h - 1;
  y2    = 0;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = w - 1;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t    += micros() - start;

  yield();
  tft.fillScreen(ILI9341_BLACK);
  yield();

  x1    = w - 1;
  y1    = h - 1;
  y2    = 0;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = 0;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);

  yield();
  return micros() - start;
}

unsigned long testFastLines(uint16_t color1, uint16_t color2) {
  unsigned long start;
  int           x, y, w = tft.width(), h = tft.height();

  tft.fillScreen(ILI9341_BLACK);
  start = micros();
  for(y=0; y<h; y+=5) tft.drawFastHLine(0, y, w, color1);
  for(x=0; x<w; x+=5) tft.drawFastVLine(x, 0, h, color2);

  return micros() - start;
}

unsigned long testRects(uint16_t color) {
  unsigned long start;
  int           n, i, i2,
                cx = tft.width()  / 2,
                cy = tft.height() / 2;

  tft.fillScreen(ILI9341_BLACK);
  n     = min(tft.width(), tft.height());
  start = micros();
  for(i=2; i<n; i+=6) {
    i2 = i / 2;
    tft.drawRect(cx-i2, cy-i2, i, i, color);
  }

  return micros() - start;
}

unsigned long testFilledRects(uint16_t color1, uint16_t color2) {
  unsigned long start, t = 0;
  int           n, i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(ILI9341_BLACK);
  n = min(tft.width(), tft.height());
  for(i=n; i>0; i-=6) {
    i2    = i / 2;
    start = micros();
    tft.fillRect(cx-i2, cy-i2, i, i, color1);
    t    += micros() - start;
    // Outlines are not included in timing results
    tft.drawRect(cx-i2, cy-i2, i, i, color2);
    yield();
  }

  return t;
}

unsigned long testFilledCircles(uint8_t radius, uint16_t color) {
  unsigned long start;
  int x, y, w = tft.width(), h = tft.height(), r2 = radius * 2;

  tft.fillScreen(ILI9341_BLACK);
  start = micros();
  for(x=radius; x<w; x+=r2) {
    for(y=radius; y<h; y+=r2) {
      tft.fillCircle(x, y, radius, color);
    }
  }

  return micros() - start;
}

unsigned long testCircles(uint8_t radius, uint16_t color) {
  unsigned long start;
  int           x, y, r2 = radius * 2,
                w = tft.width()  + radius,
                h = tft.height() + radius;

  // Screen is not cleared for this one -- this is
  // intentional and does not affect the reported time.
  start = micros();
  for(x=0; x<w; x+=r2) {
    for(y=0; y<h; y+=r2) {
      tft.drawCircle(x, y, radius, color);
    }
  }

  return micros() - start;
}

unsigned long testTriangles() {
  unsigned long start;
  int           n, i, cx = tft.width()  / 2 - 1,
                      cy = tft.height() / 2 - 1;

  tft.fillScreen(ILI9341_BLACK);
  n     = min(cx, cy);
  start = micros();
  for(i=0; i<n; i+=5) {
    tft.drawTriangle(
      cx    , cy - i, // peak
      cx - i, cy + i, // bottom left
      cx + i, cy + i, // bottom right
      tft.color565(i, i, i));
  }

  return micros() - start;
}

unsigned long testFilledTriangles() {
  unsigned long start, t = 0;
  int           i, cx = tft.width()  / 2 - 1,
                   cy = tft.height() / 2 - 1;

  tft.fillScreen(ILI9341_BLACK);
  start = micros();
  for(i=min(cx,cy); i>10; i-=5) {
    start = micros();
    tft.fillTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
      tft.color565(0, i*10, i*10));
    t += micros() - start;
    tft.drawTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
      tft.color565(i*10, i*10, 0));
    yield();
  }

  return t;
}

unsigned long testRoundRects() {
  unsigned long start;
  int           w, i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(ILI9341_BLACK);
  w     = min(tft.width(), tft.height());
  start = micros();
  for(i=0; i<w; i+=6) {
    i2 = i / 2;
    tft.drawRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(i, 0, 0));
  }

  return micros() - start;
}

unsigned long testFilledRoundRects() {
  unsigned long start;
  int           i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(ILI9341_BLACK);
  start = micros();
  for(i=min(tft.width(), tft.height()); i>20; i-=6) {
    i2 = i / 2;
    tft.fillRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(0, i, 0));
    yield();
  }

  return micros() - start;
}

Please pare down your code to the absolute minimum. There is lots of code in there that is obviously superfluous.

Are you sure you have wired everything correctly? In particular:

In most cases I have seen, the source of the problem was incorrect wiring of MOSI and SCLK. Do not trust the default constructor, better use the constructor that specifies the values of those pins.
Check that the reset pin on your 9341 board is wired correctly.
Power the 9341 with 5V; if you feed it 3.3V, the voltage regulator will not be able to supply a high enough voltage for the controller to work correctly.

You also haven't mentioned what you are running this on!

yes m using 5V only and my wiring is proper also i changed the position in breadboard so many times to make sure if the problem is coming from breadboard but still nothing happened please help


text:
Is it possible to have two serialEvent() in Arduino code?
I am developing a code on Arduino and need to implement a condition that if data is available form "serial2" then only get the input for "Serial" terminal of Arduino.
I have tried with below code, but its behavior is when I am sending something from "serial" terminal of arduino, control goes into the loop "serialEvent()" otherwise even if I am sending the data over "serial2" it is not entering in that loop.
Below is my code snippet:
void serialEvent()
{
  int DATAaddressMSb, DATAaddressLSb;
  digitalWrite(DIR485, LOW);
  delay(100);
  delay(10);
  while (Serial2.available()>0)
  {
    Serial.println("serial2 data available");
    int i = 0;
    int bufferIn1[9] = { int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00) };
    bufferIn1[i] = Serial2.read();
    Serial.print(bufferIn1[i], DEC);
    Serial.print(" ");
    if(i == 0){Serial.print("BUFFER VAL 0");
    Serial.print( bufferIn1[i], DEC);}
    if(i == 1){Serial.print("BUFFER VAL 1");
    Serial.print( bufferIn1[i], DEC);}
    if(i == 2){Serial.print("BUFFER VAL 2");
    Serial.print( bufferIn1[i], DEC);}
    i++;
  }

  while (Serial.available()&& pos < sizeof my_str - 1) {
    char c = Serial.read();
    if (c == '\n') {            // \n means "end of message"
            my_str[pos] = '\0';     // terminate the buffer
            pos = 0;                // reset to start of buffer
            String str((char*)my_str);    // converte char array in string
            if (str == "PCB-CODE") { Serial.println(SN_CODE); }
            if (str == "FW-VERSION") { Serial.println(FW_ver); }
            if (str == "STOP" ) { TESTcode = 0; IDcode = 999; }
            if (str == "TEST1") { TESTcode = 1; delay(6000); Serial.println("Enter ID "); }
            if (str == "TEST2") { Serial.println("Initialising Board ");  delay(6000); TESTcode = 2; }           // For all tests

            if (str == "ID0") { IDcode = 999; }
            if (str == "ID1") { delay(60); IDcode = 1; }       // Test for FW version
            if (str == "ID2") { IDcode = 2; }       // Test for 3.3V
            if (str == "ID3") { IDcode = 3; }       // Test for Main power
            if (str == "ID4") { delay(50); IDcode = 4; }       // Test for +15V
            if (str == "ID5") { IDcode = 5; }       // Test for +10V
            if (str == "ID6") { IDcode = 6; }       // Test for +8V
            if (str == "ID7") { IDcode = 7; }       // Test for +5.5V
            if (str == "ID8") { IDcode = 8; }       // Test for +1.2V
            if (str == "ID9") { IDcode = 9; }       // Test for +2.5V
            if (str == "ID10") { IDcode = 10; }     // Test for -15V
            if (str == "ID11") { IDcode = 11; }     // Test for POW_LIGHT
            if (str == "ID12") { IDcode = 12; }     // Test for +s_stab
            if (str == "ID13") {delay(50); IDcode = 13; }     // Test for +CELLA
            if (str == "ID14") { IDcode = 14; }     // Test for FPGA_GPIO
            if (str == "ID15") { IDcode = 15; }     // Test for DAC_OUT
            if (str == "ID16") { IDcode = 16; }     // Test for CURRENT_LOOP
            if (str == "ID17") {delay(50); IDcode = 17; }     // Test for Torque signal
            if (str == "ID18") { IDcode = 18; }     // Test for EXT_TRIGGER
            if (str == "ID19") { IDcode = 19; }     // Test for Encoder
            if (str == "ID20") { IDcode = 20; }     // Test for RAM
            if (str == "ID21") { IDcode = 21; }     // Test for SD Card
            if (str == "ID22") { IDcode = 22; }     // Test for Ethernet
            if (str == "ID23") { IDcode = 23; }     // Test for CAN
            if (str == "ID24") { IDcode = 24; }     // Test for I2C
     for( int i = 0; i < sizeof(my_str);  ++i )    // resetta la stringa ricevuta         // reset the received string
          my_str[i] = (char)0;
        }
        else {my_str[pos++] = c;}
  }
 }

Please guide. Thank you........

ignore the SerialEvent and put this code in loop(). it is nothing more then if (Serial.available()) called after the loop() function

Relevant Arduino source code: https://github.com/arduino/ArduinoCore-avr/blob/b7c607663fecc232e598f2c0acf419ceb0b7078c/cores/arduino/HardwareSerial.cpp#L64-L85

According to https://www.arduino.cc/en/Reference/SerialEvent
Arduino Mega handles:
void serialEvent1(){
//statements
}

void serialEvent2(){
//statements
}

void serialEvent3(){
//statements
}

Every other Arduino has only single:
void serialEvent(){
//statements
}


text:
How do I make a counter that counts the amount of active inputs
I want to make a direction guide using green, yellow and red LEDs. The lights need to change when ever the active input1 reaches a set value, for example:

Green when the value is lower than 12;
Yellow when the value is higher than 11 and lower than 20;
Red when its higher than 19.

I've been searching for a few days but I couldn't find any references.

1 By active inputs I mean, a series of buttons being pressed at the same time, if there is 29 buttons then when less then 12 of them is pressed the green light would be turned on.

The reference you would look for would be something on the C or C++ language. That would describe the basic structure of "conditional statements" like if (x < 5) {...} and so on.

What do you mean by "active input"? What kind of input, and what does the value indicate?

You need something like:
const int BUTTON_MAX = 29;
const int button[BUTTON_MAX] = { 5, 6, 7, ... };
const int GREEN_LED = 2;
const int YELLOW_LED = 3;
const int RED_LED = 4;
int current_led;

void setup()
{
   // Setup inputs (buttons)
   for (int i = 0; i < BUTTON_MAX; i++) pinMode(button[i], INPUT_PULLUP);

   // Setup outputs (led)
   pinMode(GREEN_LED, OUTPUT);
   pinMode(YELLOW_LED, OUTPUT);
   pinMode(RED_LED, OUTPUT);

   // Initial state
   current_led = GREEN_LED;
   digitalWrite(GREEN_LED, HIGH);
   digitalWrite(YELLOW_LED, LOW);
   digitalWrite(RED_LED, LOW);
}

void loop()
{
   // Count number of active buttons
   int count = 0;
   for (int i = 0; i < BUTTON_MAX; i++) count += digitalRead(button[i]);

   // Map number of active buttons to led
   int new_led;
   if (count < 12)
      new_led = GREEN_LED;
   else if (count < 20)
      new_led = YELLOW_LED;
   else
      new_led = RED_LED;

   // Check for change and update
   if (new_led != current_led) {
      digitalWrite(current_led, LOW);
      digitalWrite(new_led, HIGH);
      current_led = new_led;
   }

   // Add a few milli-seconds for debounce
   delay(20);
}

This seems like a decent answer, ignoring whatever "active inputs" means...

@DuncanC by active inputs i mean, a series of buttons being pressed at the same time, if there is 29 buttons then when less then 12 of them is pressed the green light would be turned on. not sure if this helps.

@oliversindahl thanks for the info. That allows an update to the answer :)


text:
AtTiny analog read always 1023
I am trying to replicate Low power LED firefly project. So what I'm trying to do is to do an analog read from a LED, to detect light. To simplify it a bit, I am using different pins and different leds for IN and OUT. The code:
#define PIN1 don't use this pin! /*this is RESET*/
#define PIN2 3
#define PIN3 4
#define PIN4 don't use this pin! /*this is GND*/
#define PIN5 0
#define PIN6 1
#define PIN7 2
#define PIN8 don't use this pin! /*this is VCC*/
#define ANL1 PIN7
#define ANL2 PIN3
#define ANL3 PIN2

// the setup function runs once when you press reset or power the board
void setup() {
  digitalWrite(PIN3, LOW);
  pinMode(PIN3, INPUT);
}

#define BLINK true
// the loop function runs over and over again forever
void loop() {

  const int value = analogRead(PIN3);
  if(value>=1023) {
    pinMode(PIN2, OUTPUT);
    digitalWrite(PIN2, HIGH);
    delay(500);
    digitalWrite(PIN2, LOW);
    delay(3);
  }
  else {
    delay(1);
  }
}

This is the setup. I am using much smaller resistor, but I'm still getting 1023 on analog read, as indicated by the output led always being on:

simulate this circuit – Schematic created using CircuitLab
What's wrong?

In this article the following steps are used when using an LED as a light detector:

Light up the LED by making the anode positive (logic one) and the
cathode negative (logic zero) - this fully discharges the LED as a
capacitor.
Charge up the capacitor by making the anode negative and the cathode
positive, as this is a small capacitor it will take no time at all
in other words for as short a time as you can.
Put the diode into the measurement mode, by making the anode
negative (it already is) and the cathode connected to an analogue
input.
Make a measurement of the analogue voltage, this is a reference
level to be used later.
Wait while the photon current is integrated - the longer the more
sensitive but too long and effects other than photo current
dominate.
Measure the voltage again and subtract it from the reference value
you took before the integration time. This figure is your light
reading.

Looking at the code in the above question it is not apparent where you switch from forward bias to revers bias.  Also, it does not appear there are two samples taken and the difference between the two samples is found.

Thanks for the explanation. But I was more concerned about the fact that the analog read doesn't return zero, or close to zero, when it's shorted to GND via the resistor.

Since you are not using "value" to, say, dimension an array, then you should not use "const".  This may be the root of the problem you are having.  Also, ADC are not all that accurate.  If you don't take several readings and average them then you usually only get a few significant bits out of the range of the ADC.


text:
How do I know if GY-521 MPU6050 has been calibrated properly?
I am planning to use the accelerometer of MPU6050 for a project.
I know that before using module (I am using GY-521 MPU6050), one needs to calibrate it.
I am using code by Luis Rodenas for calibration: https://sites.google.com/view/autoaero/code/auto-calibration-mpu6050
This code returns following offsets for my module:
-1123 -4100 1562 111 8 -1

Offsets are in Ax,Ay,Az,Gx,Gy,Gz format.
I am using these offsets in MPU6050_raw.ino example of i2cdevlib after making necessary adjustments. Here is the sketch
    // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class
// 10/7/2011 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//

// 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.h"

// 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 InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 accelgyro;
//MPU6050 accelgyro(0x69); // <-- use for AD0 high

int16_t ax, ay, az;
int16_t gx, gy, gz;

// uncomment "OUTPUT_READABLE_ACCELGYRO" if you want to see a tab-separated
// list of the accel X/Y/Z and then gyro X/Y/Z values in decimal. Easy to read,
// not so easy to parse, and slow(er) over UART.
#define OUTPUT_READABLE_ACCELGYRO

// uncomment "OUTPUT_BINARY_ACCELGYRO" to send all 6 axes of data as 16-bit
// binary, one right after the other. This is very fast (as fast as possible
// without compression or data loss), and easy to parse, but impossible to read
// for a human.
//#define OUTPUT_BINARY_ACCELGYRO

#define LED_PIN 13
bool blinkState = false;

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
    // it's really up to you depending on your project)
    Serial.begin(115200);

    // initialize device
    Serial.println("Initializing I2C devices...");
    accelgyro.initialize();
    accelgyro.setFullScaleAccelRange(3);
    // verify connection
    Serial.println("Testing device connections...");
    Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");

    // use the code below to change accel/gyro offset values

    Serial.println("Updating internal sensor offsets...");
    // -76 -2359 1688 0 0 0
    Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
    Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
    Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
    Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
    Serial.print("\n");
    accelgyro.setXGyroOffset(111);
    accelgyro.setYGyroOffset(8);
    accelgyro.setZGyroOffset(-1);
    accelgyro.setZAccelOffset(1562);
    accelgyro.setXAccelOffset(-1123);
    accelgyro.setYAccelOffset(-4100);
    Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
    Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
    Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
    Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
    Serial.print("\n");

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

void loop() {
    // read raw accel/gyro measurements from device
    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

    // these methods (and a few others) are also available
    //accelgyro.getAcceleration(&ax, &ay, &az);
    //accelgyro.getRotation(&gx, &gy, &gz);

    #ifdef OUTPUT_READABLE_ACCELGYRO
        // display tab-separated accel/gyro x/y/z values
        Serial.print("a/g:\t");
        Serial.print(ax); Serial.print("\t");
        Serial.print(ay); Serial.print("\t");
        Serial.print(az); Serial.print("\t");
        Serial.print(gx); Serial.print("\t");
        Serial.print(gy); Serial.print("\t");
        Serial.println(gz);
    #endif

    #ifdef OUTPUT_BINARY_ACCELGYRO
        Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax & 0xFF));
        Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
        Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
        Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));
        Serial.write((uint8_t)(gy >> 8)); Serial.write((uint8_t)(gy & 0xFF));
        Serial.write((uint8_t)(gz >> 8)); Serial.write((uint8_t)(gz & 0xFF));
    #endif

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

This is the output at serial monitor when module is horizontal with package letters facing up.
So have I calibrated the accelerometer properly? Please help if you can see any anomaly.
Thanks.

consider looking at your acceleration and gyroscope data. if you have the device perfectly flat on the table you will find the gravitational force in some axis. tilt the whole setup and check if the g force now shows up in a different axis (hopefully the one you expect) then rotate the setup by 90 degrees around any axis. (always one at a time please!) if your gyro tells you that your rotational velocity per some measure of time roughly equals pi you know that everything works as expected. this actually works for every accelerometer and gyro so also these that you find on say the sparkfun 9dof board if you should ever come across those.
your cal can be tested by comparing a non cal-ed measurement with a cal-ed one. the differences between the expected value and the measured one should get smaller then.


text:
H Bridge for microcontroller power management?
Is it fine to use L298 N Dual H Bridge Stepper Motor Driver Module to control power of other ICs in a multiple microcontroller setup?
I intend to reduce power consumption in by powering communication ICs through the H bridge to allow switcching them off if not needed. Does a L298 based H bridge module like shown below supply clean stable DC current to someting like the ESP8266?
Module shown below contains condensators, i assume to reduce ripple effect created by L298.

While it may be possible to bend one of those to your proposed usage, it's far from ideal, for a number of reasons:

It's far more expensive than the single P-FET that you need to get the job done
It's risky: you can easily reverse the current through your components and blow them up
It imposes a ground offset which can cause you communication problems.

All you need is a single P-channel MOSFET (assuming you are switching 5V with a 5V logic signal) and a single resistor (10kΩ would be fine, but any large value is ok).

simulate this circuit – Schematic created using CircuitLab
Pull the GPIO LOW and the power switches on. As simple as that.
If you want to switch a higher voltage then simple use an N-channel MOSFET to pull the GPIO line LOW for you - which you then switch with your GPIO signal.


text:
FT232RL Chip pinout to flash Arduino Pro Mini
Looks I have a FTDI USB to TTL adapter that doesn't follow the standard Arduino FTDI pinout order. The chipset is FT232RL and here is the link to Amazon page.
https://www.amazon.com/Adapter-Serial-Converter-Development-Projects/dp/B075N82CDL#customerReviews
Please can someone tell me the right pinout to connect this to Arduino Pro Mini 3.3v Thanks!

All the pins are clearly labelled, and they are exactly the same as any other FT232 board. Where is the confusion?

This is the standard FTDI Basic connections. CTS is an input to the module and is typically just connected to Gnd as seen on the right side here from the Arduino Promini schematic (so the FT232 is always Clear(ed) To Send, i.e. no flow control is used).
DTR may be broken out on one of the side holes.  RTS may work for you in place of DTR to create the reset pulse to start the bootloader code.  If not,  you may have to cut the trace and wire the RTS header pin to DTR. DTR is pin 2 on the FT232, use a meter and confirm it goes to one of the side holes, that way  you don't  have to try a solder a wire on to a pin.

Thank you @CrossRoads for clearing this up. The DTR was indeed broken out on the side.


text:
Arduino Pro Micro - switch off LEDs
I am using a Arduino Pro Micro as a keyboard (USB HID device). Each time I press a key, the RX LED and TX LED light up. Can I switch them off in software?

Kind of.
You don't have to change pins_arduino.h.
Try the LED_BUILTIN_TX and the LED_BUILTIN_RX.
The pins are turned on and off by the code for the SerialUSB port. That can not be changed without changing the Arduino libraries. Setting that pin to INPUT in your sketch in the setup() function will turn them off:
pinMode(LED_BUILTIN_TX,INPUT);
pinMode(LED_BUILTIN_RX,INPUT);

If you have troubles with the LED_BUILTIN_TX and the LED_BUILTIN_RX, then you can use this as well:
bitClear(DDRD,5);
bitClear(DDRB,0);

The code for the SerialUSB port still writes to that pin, but once they are set as INPUT, that code will turn on and off the pullup resistor. That is no problem since those leds are connected to VCC.
To turn them on is also possible, but then those pins needs to be OUTPUT and LOW. They will not stay on when the SerialUSB port is used.

Kind of.
You would need to edit the pins_arduino.h file for the Pro Micro board to change the definitions of the TXLED0, TXLED1, RXLED0, RXLED1 and TX_RX_LED_INIT macros.
You want them to all be defined, but empty.
#undef TXLED0
#undef TXLED1
#undef RXLED0
#undef RXLED1
#undef TX_RX_LED_INIT

#define TXLED0
#define TXLED1
#define RXLED0
#define RXLED1
#define TX_RX_LED_INIT

That will remove the current definitions, and then create new empty definitions.  Without the empty definitions, you will get errors when compiling.


text:
Which pins are represented by these constants from ABR library?
The following code comes from AtTiny serial library that I want to use:
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

// change these to use another pin
#define TX_PORT PORTB
#define TX_PIN  PB0
#define TX_DDR  DDRB
#define TX_DDR_PIN DDB0

I have no idea which pins to connect. What do these constants mean and where are they documented?

On the ATTiny13 PB0 is on physical pin 5.

The mapping can be found in the io.h file but also in Arduino core files.
Below is the pin mapping:
                        ATtinyX4
                      +----U----+
  (VCC)-------------1-|VCC   GND|-14------------(GND)
  (D10)-------------2-|PB0   PA0|-13----------(D0/A0)
  (D9)--------------3-|PB1   PA1|-12----------(D1/A1)
  (/RESET)----------4-|PB3   PA2|-11----------(D2/A2)
  (D8)--------------5-|PB2   PA3|-10-------(D3/A3/SS)
  (D7/A7)-----------6-|PA7   PA4|-9---(D4/A4/SCL/SCK)
  (MISO/SDA/D6/A6)--7-|PA6   PA5|-8------(D5/A5/MOSI)
                      +---------+

The serial library uses:
#define TX_PIN  PB0

Which is ATtinyX4 Pin #2, or Arduino attiny core digital pin D10 https://github.com/damellis/attiny/blob/master/variants/tiny14/pins_arduino.h.
Cheers

Question is about ATTiny13

@Gerben No the tag. The actual source code mentioned is ATtinyX4. But in any case the same "lookup" is required.

All his other questions are about the 13A. I don't think that library will work on an ATTiny13A. At the very least, the library assumes it runs at 8MHz, while the 13A runs at 9.6MHz. He'd have to change the OCR0A = 103; with something like 123.

@Gerben Thanks for pointing that out. I know that the library isn't meant specifically for 13A, but I cannot find anything else, so I decided to try to get that to work.


text:
Does bool return an int?
I know that for the Arduino (and C in general) that for comparison sake, "false" is 0, while any non-zero integer is "true". The question that I have is does the bool data type "return" a concrete integer for "true" or "false"?
When I tried Serial.print(true == 1), it printed 1 (which I assumed to be "true"), but when I tried Serial.print(true == 2), it printed 0 (which I assumed to be "false"). When I tried Serial.print(false == 1), it printed 0 and Serial.print(false == 0) printed a 1.
I didn't know if "true" always evaluated to 1 and "false" always evaluated to 0, or if this is not supposed to happen.

Never use if(flag==1), don't even use if(flag==true), but use if(flag), when the variable flag is a bool or boolean. The bool is part of the c++ language and the boolean is made up by arduino. The Serial.print function prints integers and floats, but sadly not "true" or "false" for a bool, so it uses the integer value and prints "1" or "0".

@Jot, I was mainly seeing if it would be the same because I have function foo(int tf) where tf is either a 1 or a 0, and merely wanted to see if tf == true would be the same as tf == 1. But if the printer is translating true to 1, then it sounds like what I'm proposing is a bad idea.

If you look at Arduino.h, you'll see true, false and bool defined as:
#define true 0x1
#define false 0x0
typedef uint8_t boolean;

Using a simple test sketch, it appears that comparing true or false to anything besides a 1 or 0 does not "work".
void setup(){

  Serial.begin(9600);

  if(false == 0){Serial.println("false=0");}
  if(false == 1){Serial.println("false=1");}
  if(false == 2){Serial.println("false=2");}
  if(false == -1){Serial.println("false=-1");}
  if(true == 0){Serial.println("true=0");}
  if(true == 1){Serial.println("true=1");}
  if(true == 2){Serial.println("true=2");}
  if(true == -1){Serial.println("true=-1");}

}

void loop(){}

true is indeed 1, and false is 0.
This follows your tests:
(true == 1) -> prints 1, because 1 == 1
(true == 2) -> prints 0, because 1 != 2
(false == 1) -> prints 0, because 0 != 1

In C true and false are defines and a bool/boolean is a typedef (mostly to an int, unsigned int or unsigned char), where normally false is defined to 0 and true to 1 OR 255. So you cannot rely on a specific value.
In C++ the values of true and false are resp. 1 and 0, when casted to an int.

A 'bool' is defined data type based on (and identical to) an int. It's reason for existence is documentary: it's name describes how you intend to use it. There is no other difference.
'true' and 'false' are the constants 1 and 0, respectively. If you assign 'true' to a bool or any other integer type, it will get the value '1'. If you make a comparison or any other logical test (one that evaluates to true or false), that test results in a numerical value, either 1 or 0.
However you can evaluate (i.e. test) any integral value logically (true or false): if it is equal to zero the result will be false (0); otherwise the result will be true (1) - no matter what non-zero value the expression itself has. That is because the logical operators, '==', '!=', '>', etc., are (similar to) functions which can only return one of two values 'true' and 'false', regardless of the values of their inputs. That is another meaning of the bool datatype: when it is applied to a function, it implies to the compiler and to the reader that this function returns either true or false.


text:
Is my Realtime Clock Locking Up My Arduino? If so, how would I solve it?
I am having a very strange issue with the realtime clock in Arduino that I cannot seem to solve.  Basically, I have a program that logs data from a terrarium kit and saves each session to an SD card as a file named after the time the program started.  0
The problem with the program is that the code hangs on the statement before the setup section: “DateTime now = RTC.now().”  The realtime clock appears to be functioning correctly with the example program which makes this issue even more strange.  I am unsure if this is purely a software or hardware issue.  From scouring the internet, I have found people with a similar problem to mine where the RTC will freeze up the i2c bus on the Arduino.  However, I am unsure whether this is the issue plaguing me.  If this is indeed the issue plaguing my program, unsure of how to work around it.  I found an online solution here, however my program freezes upon launch so this would not work for me.
So far, I have tried:
-Replacing the coin-cell battery in the realtime clock (I am using 3 volt batteries)
-Replacing the datalogger shield with a new one
-Replacing the Arduino with a new one
-Checking to make sure that the jumpers were correctly soldered to the datalogger shield (Adafruit support checked mine through images and said they looked good)
I am running this program on IDE Version 1.6.9 with a program with the newer Adafruit datalogger shield on the Arduino Mega.
Any help would be greatly appreciated
//The libraries we need for our terrarium kit
//Download and install them all at this link:  https://drive.google.com/drive/folders/10XAFdYmnyz0dg9I6YYj80vJlHebFIZhN
#include <OneWire.h> //Import OneWire library
#include <DallasTemperature.h> //Import DallasTemperature library
#include <Adafruit_Sensor.h> //Import Adafruit Sensor library
#include <DHT.h> //Import first part of the DHT library
#include <TimerOne.h> //Import TimerOne library
#include <SPI.h>
#include <SD.h>  //this refers to an old SD library needed specifically for
#include "RTClib.h"  //this is from the rtc example folder code

//SD Card & Realtime Clock: Initialization
File logfile;
RTC_DS1307 RTC;

//Humidity Sensor: Constants
//This #define defines the pin that the DHT is plugged into
#define DHT_PIN 2
//This #define defines the type of the DHT
#define DHT_TYPE DHT22
//This tells the code that a DHT is plugged into port DHT_PIN and the DHT is of type DHT_TYPE
DHT dht(DHT_PIN, DHT_TYPE);

//Moisture Sensor: Variables
int MS_sigPin = A5; //Set the signal pin as analog pin 5
int MS_digPin = 7; //Set the digital pin as 2
float MS_upper = 0; //Declare highest value variable

//Other variables
int measurementNumber = 1; //Number of measurements taken

//Filename:
  DateTime now = RTC.now(); //Initialize the RTC
//  String seconds = (String)(now.second());  //Stores the seconds from the RTC upon setup as a string
 const String minutes = (String)(now.minute()); //Stores the seconds from the RTC upon setup as a string
 const String hours = (String)(now.hour());  //Stores the seconds from the RTC upon setup as a string
 const String days = (String)(now.day());  //Stores the seconds from the RTC upon setup as a string
 const String months = (String)(now.month());  //Stores the seconds from the RTC upon setup as a string
 const String years = (String)(now.year());  //Stores the seconds from the RTC upon setup as a string
 const String filename = "D_" + minutes + hours + days + months + years; //Create the file name as a timestamp

void setup() {

  int chipSelect = 10; //chipSelect pin for the SD card

  // put your setup code here, to run once:
  Serial.begin(115200); //Set the baud rate at 56700
//If RTC is already updated, the below is commented out
  RTC.begin();
  RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));//this is to force rtc update
//  if (!RTC.isrunning()) {
//
//    Serial.println("RTC is NOT running! Starting it now.");
//    RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
//
//  }// end rtc if

//{
//The below is copied from wired, contains a second try, hoping for sd success herein.
 pinMode(chipSelect, OUTPUT);
 digitalWrite(chipSelect, HIGH);
 SD.begin(chipSelect);
//  if (!SD.begin(10, 11, 12, 13)) {
//    Serial.println("Card failed, or not present");
//    delay(50);
//    Serial.println("Trying again...");
//    if (!SD.begin(50, 51, 52, 53)) {
//      Serial.println("Card failed, or not present");
//    }
//  }

 /******************************** CSV FORMAT ******************************/

//  Serial.print("Current Position: ");
//  Serial.println(logfile.position());
  if(logfile.position() == 0)//Below print header line for datafile
  logfile.println("Unix Time, Date, Time, Light, Humidity, Temperature");
  //logfile.println("uni,date,time,Temperature");

  /**************************************************************************/

//  sensors.begin();
//  sensors.setResolution(12);

  //Humidity Sensor:
   dht.begin();

  //Moisture Sensor:
  pinMode(MS_sigPin, OUTPUT); //Set the signal pin as an output
  pinMode(MS_digPin, OUTPUT); //Set the digital pin as an output
  digitalWrite(MS_digPin, HIGH); //Turn the digital pin on

  Serial.println("DIP THE MOISTURE SENSOR IN A CUP OF WATER MAKING SURE NOT TO SUBMERGE THE TOP OF IT INTO THE WATER, ENTER IN ANY KEY WHEN YOU ARE READY TO CALIBRATE"); //Print out useful information
  while (Serial.available() == 0) //Hang the program until the user inputs a key to continue
  {

  }
  Serial.println("Starting Calibration"); //Print out useful information
  Timer1.initialize(1000000); //Initialize an interrupt every 1 second
  Timer1.attachInterrupt(Calibrate); //When the interrupt is called run the “Calibrate” function

}
//Calibrate the moisture sensor
void Calibrate() //Function to calibrate the sensor
{
if (analogRead(MS_sigPin) > MS_upper) //If the value read by the sensor is higher than the past highest value
{
 MS_upper = analogRead(MS_sigPin); //Set the current value as the new highest value
  }
}

void loop() {

//Photocell: Variables
int photocellPin = A0; // the cell and 10K pulldown are connected to a0

  char fileCharStorage[(filename.length()+5)]; //+4 Characters to include ".csv"
  filename.toCharArray(fileCharStorage, filename.length()+5);
  fileCharStorage[filename.length()] = 'V'; //Set the file name
  fileCharStorage[filename.length()-1] = 'S'; //Set the file name
  fileCharStorage[filename.length()-2] = 'C'; //Set the file name
  fileCharStorage[filename.length()-3] = '.'; //Set the file name
  Serial.println(filename); //Print out the filename
  Serial.println(sizeof(fileCharStorage)); //Print the length of the array storing the file name
  logfile = SD.open(fileCharStorage, FILE_WRITE);  //Creates (or opens) a file names "MMHHDDMMYYYY.CSV"

  if (logfile)
  {
    Serial.println("The SD Card is functioning properly");
  }
  else
  {
    Serial.println("A Critical Error occured while trying to initialize the SD Card!");
  }
  //Realtime Clock
  DateTime now = RTC.now();

 //Photocell:
 int photocellReading = analogRead(photocellPin); //Variable that stores the amount of light detected by the photocell as an integer

  // This code gets the humidity from the DHT
  float dhtHumidity = dht.readHumidity();
  /*
  This code gets the temperature from the DHT
  */
  float dhtTemperature = dht.readTemperature();

  Serial.println(""); //Text Formatting
  Serial.println("Starting New Measurement (" + (String)measurementNumber + ")");
  Serial.println(""); //Text Formatting
  delay(1000);

  //Print out data from the number of measurements taken
  Serial.println("The Arduino has been active for " + (String)((measurementNumber*10)-10) + " seconds");
  measurementNumber++;

  //Print out data from the RTC
    Serial.print("Unix Time (Seconds since 1/1/1970): ");
    Serial.print(now.unixtime()); // seconds since 1/1/1970
    Serial.println(", ");
    Serial.print("RTC time: ");
    Serial.print(now.month(), DEC);
    Serial.print("/");
    Serial.print(now.day(), DEC);
    Serial.print("/");
    Serial.print(now.year(), DEC);
    Serial.print(",");
    Serial.print(now.hour(), DEC);
    Serial.print(":");
    Serial.print(now.minute(), DEC);
    Serial.print(":");
    Serial.print(now.second(), DEC);
    Serial.println("");
    Serial.println("");

  //Photocell:
  Serial.println("Data from the photocell:");
  Serial.print("Analog reading = ");
  Serial.print(photocellReading); // the raw analog reading

  if (photocellReading < 10) {
  Serial.println(" - Dark"); //says that if any number is lower than 10 then it prints out dark.
  } else if (photocellReading < 200) {
  Serial.println(" - Dim"); //says that if any number is lower than 200 then it prints out dim.
  } else if (photocellReading < 500) {
  Serial.println(" - Light"); //says that if any number is lower than 500 then it prints out light.
  } else if (photocellReading < 800) {
  Serial.println(" - Bright"); //says that if any number is lower than 800 then it prints out bright
  } else {
  Serial.println(" - Very bright"); //says that if any number higher than 800 then it prints out very bright
}
  Serial.println("");

// Humidity Sensor:
  Serial.println("Data from the humidity sensor:");
  Serial.print("Humidity: ");
  Serial.print(dhtHumidity);
  Serial.print(" %, Temp: ");
  Serial.print(dhtTemperature);
  Serial.println(" Celsius");
  Serial.println("");

  //Moisture Sensor:
  Serial.println("Data from the moisture sensor:");
  float percent = (analogRead(MS_sigPin)/MS_upper)*100; //Calculate moisture percentage
  Serial.println("Moisture = " + (String)percent + "%"); //Print out the moisture percentage

  Serial.println("");
  Serial.println("--------------------------------------------------");

    //Log everything onto the SD card
    logfile.print(now.unixtime()); // seconds since 1/1/1970
    logfile.print(", ");
    logfile.print(now.month(), DEC);
    logfile.print("/");
    logfile.print(now.day(), DEC);
    logfile.print("/");
    logfile.print(now.year(), DEC);
    logfile.print(",");
    logfile.print(now.hour(), DEC);
    logfile.print(":");
    logfile.print(now.minute(), DEC);
    logfile.print(":");
    logfile.print(now.second(), DEC);
    logfile.print(", ");
    logfile.print(photocellReading);
    logfile.print(", ");
    logfile.print(dhtHumidity);
    logfile.print(", ");
    logfile.print(dhtTemperature);
    logfile.println();
    logfile.close();
//  Delay by 1+9 (10) seconds between measurements
  delay(9000);
}

I'm guessing that you can't call RTC.now() before setup like that.
It would be helpful if you told us what RTC you were using, and provided a link to the library you were using for it.
At a guess, since I don't have that info, you should probably change the declaration like this:
  //Filename:
  DateTime now;

And then in your setup():
RTC.begin();

if (!RTC.isrunning()) {
  Serial.println("RTC is NOT running! Starting it now.");
  RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
} // end rtc if
now = RTC.now(); //Initialize the RTC


text:
Reading text line by line from SD
Why does the following code return this error?  How can I make this work?

Error: exit status 1 invalid conversion from 'const char*' to 'char'
  [-fpermissive]

#include "FS.h"
#include "SD.h"
#include "SPI.h"

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

  if (!SD.begin(33)) {
    Serial.println("Card Mount Failed");
  } else {
    Serial.println("Card Mount Succeeded");
  }

  File offline = SD.open("/offlineLog.txt", FILE_READ);

  while (offline.available()) {
    String line = offline.readStringUntil("\n");
    Serial.println(line);
  }
}

The docs say that stream.readStringUntil returns a string...

The error has nothing to do with what readStringUntil returns. It has to do with what parameters it accepts.
The function expects a single character to look for. Instead you are passing it a string (C string) containing one character.
In C you represent a string (char *) using "", and a single character (char) using ''.
Since readStringUntil expects a char, not a char *, you need to use '':
String line = offline.readStringUntil('\n');

Thank you!  I wish that error message was more descriptive.


text:
How can I discard power from a device I want to read from?
I want to read the data line from a device that normally interfaces with a controller. It has 3 pins, 3.3v power, gnd, and data. I don't need the power line since the Arduino will be USB powered and I obviously don't want to just connect it straight to ground. What would be the best way to handle this without introducing extra hardware components. Can I just connect the power to an input pin, and then I can use that to see if the device is on?
I'm using an Arduino Mega2560

What is the "device that normally interfaces with a controller"? If the device is meant to talk to a controller or Arduino and provides power, ground and data, it's likely that you now need to provide the 3.3V so the device has power to operate. But perhaps it's a passive device? Tell us more.

No, I'm connecting to the controller socket of a Nintendo 64. The Nintendo is powered, and normally supplies power to a controller. I want my Arduino to be a controller.

Only connect data and gnd. Assuming the data pin is an output of the N64 and the Arduino only reads it. Otherwise you would need some voltage shifting circuit, as the N64 is 3.3V and the Mega is 5V. Beside that, I'd add a resistor between the data and the arduino INPUT, so you can't damage any of the two device if they aren't power on and off at exactly the same time.

You don't need to "discard" power. You just ignore it.
If you don't need a connection, then don't connect it.  The only important connection is the ground connection. Everything else can be used, or not used, at your discretion.
There's nothing "magical" about a power connection. It's just a voltage that comes from a source that happens to be able to provide more current.  If you want to use it to power something, you can. If you want to just sense what the voltage is, you can. If you want to ignore it, you can.
It's not like a mountain: just because it's there, it doesn't mean you have to climb it...

I believe you want to check whether your device is on or not without drawing power from it. Something like the following circuit could be useful:

simulate this circuit – Schematic created using CircuitLab
R2 limits the current going into Arduino input pin. Resistor with value around 1K should be good given the voltages you mentioned. Arduino can read the input pin to see whether the device is on or off.
R1 pulls Arduino input pin to ground in when the device is off. This gives a "0" value at the input pin. R1 can be a high value ~10K. High value would limit current leakage to ground via R1.
Though this answer won't exactly satisfy your requirement of not using additional components.


text:
facing issue while compiling code
This following error message I am getting while compiling:
Arduino: 1.6.8 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

In file included from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwip/opt.h:51:0,

                 from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwip/init.h:40,

                 from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/IPAddress.h:27,

                 from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src/ESP8266WiFi.h:31,

                 from C:\Users\Shree\Documents\Arduino\libraries\firebase-arduino-master\examples\FirebaseDemo_ESP8266\FirebaseDemo_ESP8266.ino:20:

C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwipopts.h:1301:2: error: #error TCP_MSS must be defined

 #error TCP_MSS must be defined

  ^

C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwipopts.h:2381:2: error: #error LWIP_IPV6 must be defined

 #error LWIP_IPV6 must be defined

  ^

C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwipopts.h:3534:2: error: #error LWIP_FEATURES must be defined

 #error LWIP_FEATURES must be defined

  ^

In file included from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src/ESP8266WiFiSTA.h:29:0,

                 from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src/ESP8266WiFi.h:34,

                 from C:\Users\Shree\Documents\Arduino\libraries\firebase-arduino-master\examples\FirebaseDemo_ESP8266\FirebaseDemo_ESP8266.ino:20:

C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/include/user_interface.h:34:2: error: #error LWIP_OPEN_SRC must be defined

 #error LWIP_OPEN_SRC must be defined

  ^

C:\Users\Shree\Documents\Arduino\libraries\firebase-arduino-master\examples\FirebaseDemo_ESP8266\FirebaseDemo_ESP8266.ino:21:29: fatal error: FirebaseArduino.h: No such file or directory

 #include <FirebaseArduino.h>

                             ^

compilation terminated.

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
***************************

please help me out to solve this issue.

are all options set in tools menu? it is better to use esp8266 Arduino package 2.4.2 until 2.5.1 is released

Can you please provide the code?

at a guess you're including some headers in the wrong order, or haven't included a required header at all ... without code, I'm guessing

ok I will try with esp866 2.4.2. I am trying to compile example of FirebaseDemo_ESP8266. Yet no any code updated.

Hey guys I have run my example with esp8266 2.4.2 version now I'm getting following error while compiling- C:\Users\Shree\Desktop\FirebaseDemo_ESP8266ex\FirebaseDemo_ESP8266ex.ino:21:29: fatal error: FirebaseArduino.h: No such file or directory
#include <FirebaseArduino.h>
                         ^

compilation terminated.
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).


text:
Problem with arduino starter kit project 7

Can someone pls help me only the two buttons clossest to the big green wire work and i don^t know why i have already tried swapping buttons
EDIT 1:
my code

and i know the first two are working because they generate a tone with the piezo
the third one does nothing and the last one only makes static noises

Why bother, I don't like multiple buttons with resistors for an analog value. I think your circuit is okay. It could be a bad contact of the breadboard.

How can you tell, that they  don't work? Please explain more. And please show us your code. You can edit your question to add these information by clicking at the edit button under your question. Please format the code correctly, by selecting it and clicking the {} button

@Jot This is a starter kit project. It teaches how you can multiplex multiple buttons into a single analog input and figure out which button(s) are being pressed from a single line. It might not be something you want/need to do, but it's still a worthwhile concept to learn.

please do not post a picture of the code .... post the code text .... use the {} button to format it

your code contains a serial.print() command .... please open the serial monitor in the arduino IDE and find out what values are being printed for each button press .... add those values to your question above

@DuncanC but I still don't like it. The contacts of the buttons can get dirty, multiple buttons can be pressed, and with 1MΩ it is very sensitive for electrical noise. Avoiding troubles is more important to learn.

I still think it's a worthwhile technique to learn. As for the resistors, I wonder why those values were chosen. I'd be inclined to use power-of-two values (1KΩ, 2KΩ, 4KΩ, 8KΩ) That way you could decode single and multiple button presses.

I see the problem. The connections to the first 2 buttons are correct. You're missing a yellow wire linking the output of the bottom 2 buttons to AO however, so the 3rd and 4th buttons are not connected to your A0 pin at all. Add a yellow wire between row 24 and row 20 on your breadboard.
EDIT:
I see now that there is a green wire connecting rows 24 and 20 together. However, that is the likely place where things go wrong. I would suggest taking a couple of jumpers and connecting them to a multimeter set to continuity mode. Put one in row 28, and then test continuity to row 24, row 20, and row 16.
One of your wires may not be seated into the breadboard properly, or you may even have a bad row on your breadboard. I've seen that before.
EDIT #2:
A multimeter is your friend. If you don't have one, you should get one, and learn how to use it. It's invaluable for troubleshooting circuits. (Get one that has a continuity mode that beeps when it detects continuity, and that has auto-ranging voltage and resistance measurements.)

thank you this really helped me think what if it is the breadboard so i took of the sticky backside and there were some loose pieces of metal i pushed on these pieces and now it works

only problem i have now is that the analog read value from the when i press the last button isn't a steady 1023 but even if i connect the analog directly to the 5v line it isn't steady so i think that should be solved in code but i am not sure

Yes, I would suggest not matching a specific value. Write your code to check for a range of analog values. Your circuit is a voltage divider, and the button with no resistor (the bottom one in your illustration) will give a value close to, but not quite, 5V. I'd suggest looking for a value ≥1020 for that button. Check the value you get for the other buttons and implement ranges with upper/lower bounds for those.

thanks alot for the reply the value >= 1020 made it work perfectly for me. Again thanks for your help


text:
Arduino_Debug doesn't successfully upload sketch to Arduino if JAVA is not installed
I use arduino_debug to upload my sketch to an Arduino Mega 2560 and to an Arduino Due from my application (Windows).
I saw the following issue:
When JAVA is not installed or it was installed only after the Arduino SW installation, the command:
arduino_debug --port COM6 --upload mysketch.ino

doesn't successfully to upload the sketch. My Arduino is connected to COM6 (I verified it) and the sketch's path is correct.
I got the following output:
Initializing packages...

Preparing boards...

Verifying...

Sketch uses 6222 bytes (19%) of program storage space. Maximum is 32256 bytes.
Global variables use 318 bytes (15%) of dynamic memory, leaving 1730 bytes for local variables. Maximum is 2048 bytes.

Uploading...

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x87

An error occurred while uploading the sketch

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x87

Has anyone seen this issue? Does anyone know why JAVA must be installed?

Have a look at this question

arduino_debug.exe is a build of Arduino IDE to debug the Arduino IDE. So normally you should use arduino.exe command for CLI too. The Arduino IDE is a Java application. It has Java bundled in installation. In your case I would guess that the reset of the board is not invoked for some Java related reason.

The error message is not related to Java, it's usually either wrong COM port being selected, wrong bootloader or a temporary glitch that resolves when you try to reupload.


text:
How do you combine 2 different sketches together
(Before you down-vote this, note that it is a "ringer" to answer a FAQ, with a self-answer.)
This question comes up all the time. How do you combine 2 different sketches together? Say I have a sample sketch for a DTH temp/humidity sensor and another sketch for a LCD sensor. How do I combine them?

Possible duplicate of How to combine two different sensor sketches to one complete sketch?

This question comes up all the time. I'll explain what you need to do in general terms. Try it, and if you have problems, post a question showing your 2 starting sketches, your attempt at combining them, and detailed info on what goes wrong.
There are 3 basic parts to the main.ino file of an Arduino sketch:

The declarations:

#includes
#defines
global variables

The setup() function
The loop() function.

You need to merge those parts separately.

You should merge the subsections of the declarations together (Put all the #includes together, all the #defines together, and all the global variables together. Remove any duplicate #includes.

If there are any duplicate #defines or global variables, you need to figure out how to resolve that. If the symbol and the name are the same

The same applies to the two setup()-functions you want to merge. Also, duplicate parts usually need to be there only once (considering things like Serial.begin(...)).
Also the two loop()s are combined the same way, but if you make use of delay()s you must keep in mind that these will sum up in the final sketch, making it slower than the initial sketches were. It might also might (probably won't) work correctly. You will likely need to refactor your code to use millis() instead of delay().

After combining two sketches this way your global variables will be shared. You'll need to resolve any naming conflicts, or rename global variables that are different in your source sketches but should be the same. You may also have shared resources like sensors and LCD displays.
(Note that if the 2 sketches use the same resource for different things it gets more complicated, e.g. using the same pin for different purposes, using the same timer in both sketches, or using the same interrupt. Those things will require analysis and case-by-case changes.)

See for example this answer with examples

To isolate some conflicts in the code, you can rename the bits setupLCD(), setupDTH(), loopLCD(), loopDTH() and call and manage the interactions in setup(){setupLCD();setupDTH();} and loop(){loopLCD(); loopDTH();}

@DaveX, not a bad idea, although that won't help with conflicts in globals.

@DuncanC -- agree.  As you say, conflicts will require analysis and have to be dealt with on a case-by-case basis.


text:
Wanted to control 2 servos with serial read
I want to use 2nd servo only when 1st is in up state by asking user whether he wants to fire or not.(code in bold is not working )
#include <Servo.h>

    Servo myservo;
    Servo trigervo;
    int pos = 0;
    int u = 0, p = 0, t = 0;
    int incomingByte = 0; // for incoming serial data

    void setup() {
      Serial.begin(9600);
      myservo.attach(9);
      trigervo.attach(10);
      pinMode(13, OUTPUT);
      myservo.write(0);
    }

    void loop() {
      if (Serial.available() > 0) {
        // read the incoming byte:
        incomingByte = Serial.read();
        Serial.print("I received: ");
        if (incomingByte == 111 && u == 0) {
          for (pos = 0; pos <= 80; pos += 1) {
            myservo.write(pos);
            delay(5); //
            digitalWrite(13, HIGH);
          }
          u = 1;
          p = 0;
          Serial.println(incomingByte, DEC);
          Serial.print("Want to Shoot? \n");
          Serial.print("1\n");
          ***t = Serial.read(); // from here
          if (t == 107) {
            Serial.print("2\n");
            trigervo.write(60);
            trigervo.write(0);
          } // to here, it is not working***
        } else if (incomingByte == 102 && p == 0) {

          for (pos = 100; pos >= 0; pos -= 1) {
            myservo.write(pos);
            delay(7);
            digitalWrite(13, HIGH);
          }
          u = 0;
          p = 1;
          Serial.println(incomingByte, DEC);
        }
        Serial.println(incomingByte, DEC);

      }
    }

read() doesn't wait. it returns -1 if there is nothing in the RX buffer

you forgot to ask a question ... you also forgot to describe what happens when you run the program

Without knowing, what exactly you want it to do (since you didn't tell us), I see 2 problems in your code:

The code around the line marked with "from here" will ask the user over Serial, if he wants to shoot, but directly after it, it will read a value, without waiting for the user to input something. Serial.read() will not wait for data to arrive, it will just return -1 if nothing is in the buffer. You have to check, if there is actually something in the buffer with Serial.available() and only proceed, if there is actually data to read.

In the following if-statement, you first write the value 60 to the servo and directly after it, without any delay, the value 0. The servo doesn't have enough time to get to 60 - or to even start to move - before you tell him to go to 0. The servo needs time for movements.

Apart from the specific problems with your code, I would use a finite state machine (FSM), to implement it, instead. You declare a global state variable, which represents the possible states, in which your machine can be. If I assume some type of gun/shooting device, these states could be ASK_USER_TO_POSITION_GUN' and 'ASK_USER_TO_SHOOT'. In each state you check the Serial interface (first with Serial.available()then reading withSerial.read()` if it returns something greater than 0) and based on that input you first take the appropriate action and then do the state transition, by changing the state variable.
As example of the general structure:
int state = 0;

void loop(){
    switch(state){
        case 0:
            if(Serial.available()>0){
                int input = Serial.read();
                //take appropriate action
                state = 1; //do state transistion
            }
            break;
        case 1:
            if(Serial.available()>0){
                int input = Serial.read();
                //take appropriate action
                state = 0; //do state transition
            }
            break;
    }
}

Depending on the exact actions to do, you can also tune this, by reading Serial outside of the switch statement and in the case statement only check the input variable. In this case reset the input variable after every interaction.
EDIT: For giving a better explanation about finite state machines, I've drawn a graphical representation of the states. Mostly it is way easier to code, when you first have drawn such a graph to visualize the codes functionality. Note, that this is the logic from your code. You may want it to work another way, but this is beyond the scope and only for understanding. Also note the different numbers of the states than I used above, which I only change, because I needed more states.
See first this graph:

We begin in state 0, where we are waiting for user input through serial. If we go some input, we make a decision: If the value is 111, we will transition to the next state (state 1) to position the gun, else we will wait again for more input. In stage 1, we are positioning the gun and go directly to state 2. There we are again waiting for user input. If we received something, we will again make a decision: On the value 107 we will do the transition to state 3 to shoot, else we will go to state 0, to ask again for positioning, like we did before. In state 3 we are shooting and directly go to state 0 again. This is rather strict division into states.
Since in state 1 and 3 we are only doing a short action and then going directly to another state, we might cut those states away, implementing the corresponding code in the transition from state 0 to 2 and vice versa. This is the logic from my FSM code example above (action together with transition). The graph would look like this:

Which version you should implement depends on other factors. If you are OK with the action code to be blocking, you can implement version 2, since it has less states. If you want to write the action in a non-blocking style, you might find version 1 easier to implement.

As you have asked I have changed the question to be pinpointed , please help me......

The answer stays the same. Your direct problems are the two stated above.  Is this helping? If not: What prevents you from implementing this? Maybe I can write the answer more understandable, if I knew, what isn't clear about it.

In case 0, I want to get value through serial read again and implement it by calling a function , in this case calling a trigger function.

I rejected your edit, because that is not the way a FSM works. In the states you are waiting for user input. Instead of directly (still in case 0) trying to read more data, you make a transition to the next state, where you are waiting for the new data. That makes the code way better structured and also the waiting for user input will not block the code execution, in case, that you want to do something simultaneously (like blinking an LED or other tasks). I will add a graphical representation of the FSM for your case, so it is better understandable.

Ok now I  am getting the idea of it


text:
Question about a code
This code is used to toggle an arduino on and off , the problem is that i can't comprehend it at all. can someone explain to me how does it work ?
New = digitalRead(button);
  if ( New!=old)
  {
    if ( New == HIGH ){
      if (LEDstatus == LOW)
    {  digitalWrite(LED,HIGH);
    LEDstatus = HIGH;
    }
    else
    {
      digitalWrite(LED,LOW);
      LEDstatus=LOW;
    }
    }
    old=New;
  }

It doesn't toggle an Arduino on and off. It toggles an Arduino's output pin on and off on button presses.

First, fix the indentation:
New = digitalRead(button);
if ( New!=old) {                        // If the button state has changed
    if ( New == HIGH ) {                // If the button is now in the pressed state
        if (LEDstatus == LOW) {         // If the LED was off
            digitalWrite(LED,HIGH);     // Turn the LED on
            LEDstatus = HIGH;           // Remember the LED state for next time
        } else {                        // The LED was on, so turn it off
            digitalWrite(LED,LOW);
            LEDstatus=LOW;              // Remember the LED state for next time
        }
    }
    old=New;
}

That makes the code a whole lot easier to understand.
It only does something when the button is pressed (switches to HIGH state). It doesn't do anything when you release the button.
Each button press changes the state of the LED.
if it was off, it turns it on. If it was on, it turns it off.