text:
Make a GET Request GPRS
I'm building a weather station that sends the data to a webserver via GET request.
I was wondering if you guys can look into my code and help me.
I looked all over the internet and can't find what's wrong. I'm using an Arduino mega, an Arduino/Telefonica GSM shield and an EE sim card. Thank you very much!

#include <GSM.h>

GSM gsmAccess;
GPRS gprs;
GSMClient client;

const boolean gprsCheck = true;

char server[] = "";

int value = 112358132134;

void setup(){

  Serial.begin(19200);

  if(gprsCheck) {

    boolean notCon = true;

    Serial.println("Establishing connection...");

    while(notCon) {

      if((gsmAccess.begin("") == GSM_READY) & (gprs.attachGPRS("everywhere","eesecure","secure") == GPRS_READY)) {

        notCon = false;

        Serial.println("GPRS connection successful.");
        Serial.println("");
      }

      else {

        Serial.println("GPRS connection failed. Trying again.");
        Serial.println("");

        delay(1000);
      }
    }
  }

  if(!client.available() && !client.connected()) {

    client.stop();
  }

  if (client.connect(server, 80)) {

    Serial.println("Connection successful.");

    client.print( "GET /add.php?");
    client.print("value=");
    client.print(value);
    client.print(" HTTP/1.1\n");
    client.print("Host: ");
    client.print(server);
    client.print("\nConnection: close\n\n");
    client.stop();
    client.stop();

    Serial.println("Data sent.");
  }

  else {

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

void loop() {
}

You never said what is happening that is wrong. Please describe the actual problem and also include the serial output.

It does not work as I wanted. I want it to run the url just like a brower would do (i got this from arduino.cc: A typical web request looks like "GET pathname HTTP/1.0". print will send the message, just as a browser would.) And when i type on a browser the url i want the arduino to perform, it works just fine. There's no error message.

Either you have implemented this incorrectly, your server is not reachable from your mobile provider, or your GSM device is not in communication with its mobile network, or your arduino is not in communication with your GSM device.  Think about other tests you can run to identify which sort of issue you have.

I say this because you think the code is fine?

int value = 112358132134; - the largest number an int can hold is 32767. Why are you calling client.stop(); twice?


text:
FIltering, FXOS8700, FXAS21002C optimization
I'm working on an inverse pendulum project, and am using an adafruit NXP_FXOS8700_FXAS21002 along with an Arduino due, and an esp8266 (two separate projects, same code however). I'm using a Magdwick filter, which works pretty ok, however I've noticed that small angle displacements (less than 0.1 rads) don't seem to show up. Since I'm working on the inverse pendulum, even the smallest of displacements need to be seen and I think my coding and/or filter is likely the culprit, Filtering of course is required, but it can't be too aggressive because it'll add a phase shift and my regulator won't work.
So My question is, is there a better way to filter/acquire my angle displacements/measurements than what I'm currently doing now? I did at one point completely remove the filter and calculate the angle via:
theta = atan2(ay, ax);

However there were angle "spikes" for lack of a better word during quick angle changes that caused the regulator to over compensate and be completely unstable
Here is my truncated code relevant to sensor and the Madgwick filter, however I can include if requested, the entire program.
update
As noted in the comments, I am using the the Adafruit implementation of the Madgwick filter. However I am of course completely willing to use another filter, (kalman?) or any other.
On top of that, here is a youtube video of the system hanging in the stable equilibrium, Here the regulator works in the current code implementation, however for small disturbances, the angle doesn't update accurately enough, in this position it doesn't matter, however in the inverse (angle Pi) this is critical and the cause of my initial question.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Madgwick.h>
#define NXP_FXOS8700_FXAS21002
#include <Adafruit_FXAS21002C.h>
#include <Adafruit_FXOS8700.h>
Madgwick filter;
float offsetAngle, offsetOmega;
Adafruit_FXAS21002C gyro = Adafruit_FXAS21002C(0x0021002C);
Adafruit_FXOS8700 accelmag = Adafruit_FXOS8700(0x8700A, 0x8700B);

// Offsets applied to raw x/y/z mag values
float mag_offsets[3]            = { -1.28F, -39.23F, -1.78F };
// Soft iron error compensation matrix
float mag_softiron_matrix[3][3] = { {  0.940,  0.056,  0.012 },
  {  0.056,  0.932, -0.023 },
  {  0.012, -0.023,  1.146 }
};
float mag_field_strength        = 42.35F;
// Offsets applied to compensate for gyro zero-drift error for x/y/z
float gyro_zero_offsets[3]      = { 0.0F, 0.0F, 0.0F };

in setup()
  Serial.println(F("Adafruit AHRS Fusion Example")); Serial.println("");
  // Initialize the sensors.
  if (!gyro.begin())
  {
    /* There was a problem detecting the gyro ... check your connections */
    Serial.println("Ooops, no gyro detected ... Check your wiring!");
    while (1);
  }
  if (!accelmag.begin(ACCEL_RANGE_2G))
  {
    Serial.println("Ooops, no FXOS8700 detected ... Check your wiring!");
    while (1);
  }
 filter.begin(50);

And in void()
  sensors_event_t gyro_event;
  sensors_event_t accel_event;
  sensors_event_t mag_event;
  gyro.getEvent(&gyro_event);
  accelmag.getEvent(&accel_event, &mag_event);

  float ax = accel_event.acceleration.x;
  float ay = accel_event.acceleration.y;
  float az = accel_event.acceleration.z;

  // Apply mag offset compensation (base values in uTesla)
  float x = mag_event.magnetic.x - mag_offsets[0];
  float y = mag_event.magnetic.y - mag_offsets[1];
  float z = mag_event.magnetic.z - mag_offsets[2];

  // Apply mag soft iron error compensation
  float mx = x * mag_softiron_matrix[0][0] + y * mag_softiron_matrix[0][1] + z * mag_softiron_matrix[0][2];
  float my = x * mag_softiron_matrix[1][0] + y * mag_softiron_matrix[1][1] + z * mag_softiron_matrix[1][2];
  float mz = x * mag_softiron_matrix[2][0] + y * mag_softiron_matrix[2][1] + z * mag_softiron_matrix[2][2];

  // Apply gyro zero-rate error compensation
  float gx = gyro_event.gyro.x + gyro_zero_offsets[0];
  float gy = gyro_event.gyro.y + gyro_zero_offsets[1];
  float gz = gyro_event.gyro.z + gyro_zero_offsets[2];

  // The filter library expects gyro data in degrees/s, but adafruit sensor
  // uses rad/s so we need to convert them first (or adapt the filter lib
  // where they are being converted)
  gx *= 57.2958F;
  gy *= 57.2958F;
  float gzz = gz * 57.2958F;
  // Update the filter
  filter.update(gx, gy, gzz, ax, ay, az, mx, my, mz);
  theta = ((filter.getPitch() * (PI / 180)) - PI / 4);

I greatly appreciate the help!

Do you use this: https://github.com/adafruit/Adafruit_AHRS Please add a link to that in your question. Some sensors have a filter inside to reduce noise. Can you test the raw values from the sensors? All the libraries and the calculations are with float, you gonna lose some accuracy. The Arduino Due can use double precision. There is a weird calculation in invSqrt. Can someone look into that to see if that bit operation on a float is correct? https://github.com/adafruit/Adafruit_AHRS/blob/master/Madgwick.cpp#L231 Where are the sensors located? Can you show a photo or draw a picture?

Ah, yes that was my madgwick implementation, I will add it to the question...I did mention that in the question, I did use raw accel values to calculate the pitch, resulting in a 'spike' for lack of better word before the actual angle is then correctly displayed/calculated.
Yes, I will add a photo/video.

An accelerometer is sensitive for small changes and vibrations (and is noisy). The gyro drifts. When also a magnetometer is added, the AHRS filter can make a good steady output. The AHRS filter is for objects like a plane. You only need the angle (in one dimension).

Ahh, yes, actually that makes sense, my system is a 1 dof system, in reality I only need the angle...the suggestion would be to only filter the resulting calculated angle from atan2? to reduce noise? or filtering the accel ax and ay components then calculating?

Is the module powered with 3.3v? Are sda and scl the pink and grey wires? Then please split those wires, the i2c bus has troubles with crosstalk. How long are the wires to the esp8266? If the i2c fails, will that be detected? I think that the main problem is the motor vibrations. The accelerometer is very sensitive for that. The magnetometer might also be influenced by the motor. That adds up to 7 possible problems, and I might have overlooked the real cause.

I don't have the machine in front of me at the moment, however, I will look at all your mentioned points, and also capture some screen shots and consider a more specific question, though, I'll wait a bit and see if someone has an answer. Thanks for the suggestions!

I was hoping that someone else joined, but so far no luck. There is too much going on. You can wait for someone else. You could try to eliminate a few possible problems in your project. For example dampen the motor or the sensor with rubber/foam for a test. You have to be sure that i2c problems are detected and that you always get real data from the sensor. Perhaps the magnetometer does more harm than good due to magnetic noise by the motor. You might start a new question how to measure the angle better. Perhaps there are precise rotary encoders.

source: Stack Exchange

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

sort: votes


text:
ESP8266 WiFi Module disconnects from WiFi itself

#define id "qwerty"
#define password"123456789"
int relayPin= 4;
void setup()
{
  Serial.begin(115200);

  Serial.println("AT");
  pinMode(13, OUTPUT);
  pinMode(relayPin, OUTPUT);
  delay(3000);

  if (Serial.find("OK")) {
    Serial.println("AT+CWMODE=1");
    delay(2000);
    String connectionCommand= String("AT+CWJAP=\"") + id+ "\",\"" + password+ "\"";
    Serial.println(connectionCommand);
    delay(5000);
    Serial.println("AT+CIFSR");
    delay(50);
    Serial.println(Serial.read());
  }

  Serial.print("AT+CIPMUX=1\r\n");
  delay(200);
  Serial.print("AT+CIPSERVER=1,80\r\n");
  delay(1000);
}
void loop() {
  if (Serial.available() > 0) {
    if (Serial.find("+IPD,")) {
      String metin = " Hello World ";
      metin += "
<button type='button'>ON</button>";
      metin += "
<button type='button'>OFF</button>";
      String cipsend = "AT+CIPSEND=";
      cipsend += "0";
      cipsend += ",";
      cipsend += metin.length();
      cipsend += "\r\n";
      Serial.print(cipsend);
      delay(500);
      Serial.println(text);
      lock_open_close();
      //Serial.println("AT+CIPCLOSE=0");

    }
  }
}

void lock_open_close() {
  String coming= "";
  char readonserial;
  while (Serial.available() > 0) {
    readonserial= Serial.read();
    coming+= readonserial;

  }
  Serial.println(coming);
  if ((coming.indexOf(":GET /?pin=on") > 1)) {
    digitalWrite(13, HIGH);
    digitalWrite(relayPin, HIGH);
    delay(200);
  }
  if ((coming.indexOf(":GET /?pin=off") > 1)) {
    digitalWrite(13, LOW);
    digitalWrite(relayPin, LOW);
    delay(200);
  }
}

Here's my code. I connected ESP8266 with a relay and a solenoid lock, so that I am expecting to control the lock with the buttons. But ESP8266 disconnects itself. Any suggestions?
Thanks a lot.
Sincerely,
Y.

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


text:
Due as USB Host timing issues
I own a UDOO Quad board which features two CPUs (SAM3X8E like Arduino Due and a ARM Cortex-A9) connected with an internal OTG USB.
I am trying literally for months to use the USB Host Shield Library (https://github.com/felis/USB_Host_Shield_2.0/) in order to make the Due act as a USB host to the other CPU (which runs Android). The Due runs well a piece of code collecting some data every X milliseconds within a built-in timer's ISR.
What I want to achieve is to send this data collected by the ISR to the other CPU via the USB connection of the two; but there seems to be an issue with the Usb.Task() call. This Usb.Task() needs to be executed from within the Loop() but it seems to need much more time than the timer's frequency. So eventually it is never executed.
Please note that all of the above work when the interrupt is not involved; Usb.Task() works perfectly from the Loop() (data to/from the other CPU can be both sent and received).
Bits from the code:

void readPlantStatus() {
  if (analogRead(E2_STATUS)*(3.3/1023.0) > 2.0) e2_reached = true;
  else e2_reached = false;
  if (analogRead(F2_STATUS)*(3.3/1023.0) > 2.0) f2_reached = true;
  else f2_reached = false;
  if (analogRead(T2_STATUS)*(3.3/1023.0) > 2.0) t2_reached = true;
  else t2_reached = false;
  if (analogRead(E3_STATUS)*(3.3/1023.0) > 2.0) e3_reached = true;
  else e3_reached = false;
  if (analogRead(F3_STATUS)*(3.3/1023.0) > 2.0) f3_reached = true;
  else f3_reached = false;
}

void TC3_Handler() {
  TC_GetStatus(TC1, 0);
  readPlantStatus();
  writeToController();
  readFromController();
  controlPlant();
}

void loop()
{
  Usb.Task();
}

Any help would be greatly appreciated!

USB may well not be suited to your task - it is generally not good at moving tiny bits of data frequently.  You could look at trying to transfer the data in larger packet-sized buffers asynchronously to your sampling which would be more fitting to the design of USB (but may indeed make for some tricky programming) or you could look at using a UART - at a decent baud rate such as 115200 that can actually be faster for short messages than USB since you can basically talk any time you've finished what you were previously sending.

Thank you Chris for your quick comment. I guess I will have to look into the UART option as you proposed.

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


text:
Turn Arduino on with timer every 24h
I'm currently working on an Arduino project that sends the charge of my car battery once a day via an ESP8266 to me. During the winter I don't drive my car, and I would like to get informed when the battery drops beyond a critical value, so I can charge it and prevent damage.
So energy efficiency is important for the project, so it doesn't discharge the battery itself. I read a lot about sleep mode, efficient drop down regulators etc. These all have in common that the voltage regulator is always running, which is not what I want.
I'm looking for some kind of "swich-on-timer circuit". It should count down 24 hours and then turn on a relay or MOSFET, which connects the voltage regulator to power and with that turns on the Arduino and the ESP8266. When the Arduino has finished with the transmission, it resets the timer, which disconnects the voltage regulator from power, and so on. Of course, the timer circuit should use only very little power.
Does anybody know a circuit like that? I searched on AliExpress with all variations of words that came to my mind, without success. Or maybe an IC which can be used (easily) to create such a circuit?

Not all voltage regulators are the same. Some will only use a few micro-amps.

Thinking out of the box... Won't a standard timer-switch suffice?

One approach would be use of a DS3231 (Precision Real Time Clock) module.  Such modules sell on Ebay for under $1.  Search for ds3231 arduino.
Typically, these modules have a six-pin connector, with pins labeled 32K, SQW, SCL, SDA, VCC, and GND.  As noted in DS3231 specs, the INT/SQW pin is used either for square-wave output or for interrupt output.  On page 13 of specs, in the Control Register section, it says:

Bit 2: Interrupt Control (INTCN). This bit controls the INT/SQW signal. When the INTCN bit is set to logic 0, a square wave is output on the INT/SQW pin. When the INTCN bit is set to logic 1, then a match between the time-keeping registers and either of the alarm registers activates the INT/SQW output (if the alarm is also enabled).

Initially, you would run a sketch to set up the DS3231: turn on a daily alarm, enable an interrupt rather than square wave, set the current time, etc.  Then, load an operational program that reads car-battery voltage each time it runs, and acts appropriately.
The DS3231 INT/SQW pin would be wired to the gate of a P-channel mosfet that switches 12V power to the Arduino.  The P-fet would turn on when the alarm's open-drain output pin INT/SQW turns on.  The operational program does its business and then clears the DS3231 interrupt flag, to shut down power until the next alarm occurs.  (For debugging, set briefer intervals than a day; for example, once a minute, as described in Table 2, Alarm Mask Bits, on page 12 of specs.)
Typically, the DS3231 draws 0.84 μA when running from a 3.3V battery, or 1 μA from 5V.  See Electrical Characteristics, page 3 of specs.

The P-fet gate probably should be pulled up to +12 through something like a 1 megohm resistor; else it would be effectively open when  the INT/SQW pin is off, and could float to arbitrary levels

The timer or timer-circuit itself would have to draw some current. Any of the pico-power AVR chips draw very little current in sleep mode - in the 10s of micro-amps for the 328, if I recall correctly. Sleeping an AVR for the least current draw needs just about everything shut down but the watchdog timer, and the maximum WDT period is 8 sec. A library like Narcoleptic will manage longer periods for you. What you would need to do though, is to provide a much more efficient regulated power supply than the one built onto the Arduino board (if that is what you'll be using). That done, the Arduino's load on your car battery should be microscopic.
One possible design for an efficient supply is an array of alkaline batteries, say 3 in series for a 4.5 output (while fresh) times 2 or more such strings in parallel, connected directly to the 5v bus.
I haven't done the power budgeting to know the capacity you'd need and whether you'd need D cells or could make a practical array from smaller ones, say AAs, but that is a way to achieve zero load on the car battery (discounting the car-battery voltage sensor's requirement). You might want to include the Arduino battery-array's health in the daily report, or, for the price of a few Alkalines, you might so over-design the Arduino battery that monitoring it would become unnecessary.
A couple of data points suggest a separate battery is a feasible approach:

A single 9v Alkaline runs a smoke detector for over a year including over-wintering in an unheated attic (in my own experience), and 9v Alkalines are not known for their capacity.
My digital setback thermostat has run for a couple of years on 2 AA cells, before a) they died, and b) I wised-up and started changing them annually. :)

I have an ATmega48 (very similar to the 328P) running off a couple of AA cells since June 2012. It's awake for a little more than 4 minutes per day, sleeping the rest of the time. Not changed the batteries so far.

That's an impressive run-time - thanks for the additional data point, @EdgarBonet! I expected a sleeping Arduino and an Alkaline battery pack could be a "set-it-and-forget-it" system but without calculating out the energy consumption, I didn't guess it would perform that well. So, @DirkPitt, there's some real-world support data.

It's not a full Arduino: I could not manage to get below ~ 40 mA with my Uno, whereas the bare ATmega in SLEEP_MODE_PWR_SAVE, with only the async timer active, took something like 2 µA.

Consider using "Adafruit TPL5110 Power Timer"
https://learn.adafruit.com/adafruit-tpl5110-power-timer-breakout/overview

This is more of a comment.  If you want to leave it as an answer, please add further explanation of your solution.

you can use a timer switch. you can buy it from ebay for around 5 euros. i am using this one
https://www.ebay.com/itm/CN101-DC-12V-16A-Digital-LCD-Power-Programmable-Timer-Time-Relay-Switch-New/401190616827?hash=item5d68d2fefb:g:K3sAAOSwNRdX3ggT
i have also tried ds3231 but the arduino is on standby mode and it consume energy. this is the best solution i found

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

authors: يوسف الشراري


text:
Arduino bug when "myFile = SD.open" is inside loop()
My Arduino resets / bugs each time I put myFile = SD.open in loop().
In setup() it works fine.
I have a 20*4 LCD and an RTC connected to I2C, an SD card reader connected to SPI, and a fingerprint sensor.
Here is my code:
#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <SD.h>
#include <DS3231.h>;

LiquidCrystal_I2C lcd(0x3f,20,4);
DS3231  rtc(SDA, SCL);
SoftwareSerial mySerial(2, 3);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
Sd2Card card;
SdVolume volume;
SdFile root;

int etat = 0;
int getFingerprintIDez();
const int chipSelect = 10;
SDFile myFile;

void setup() {
  lcd.init();
  lcd.backlight();
  rtc.begin();
  finger.begin(57600);
  SD.begin();

  // Reglage Heure
  //rtc.setDOW(TUESDAY); // Set Day-of-Week to SUNDAY
  //rtc.setTime(10, 57, 0); // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(24, 11, 2016);   // Set the date to January 1st, 2014
  if (finger.verifyPassword()) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Capteur Initialise");
  } else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Capteur Deconnecte");
  }
  delay(2000);
  if (SD.exists("data.csv")) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("data.csv OK.");
    delay (1000);
  } else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Creating data.csv...");
    myFile = SD.open("data.csv", FILE_WRITE);
    myFile.close();
    delay (1000);
  }
}

void loop() {
  if (etat == 0) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Put Finger");
    getFingerprintIDez();
  }
  if  (etat == 1) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("ID #");
    lcd.setCursor(4,0);
    lcd.print(finger.fingerID);
//  myFile = SD.open("data.csv", FILE_WRITE);
//  myFile.print(rtc.getDateStr(1));
//  myFile.print("\t");
//  myFile.print(rtc.getTimeStr(1));
//  myFile.print("\t");
//  myFile.println(finger.fingerID);
//  myFile.close();
    lcd.setCursor(0,2);
    lcd.print("Loged");
    etat = 0;
  }
  delay(1000);
}

int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Found ID #");
  lcd.setCursor(14,0);
  lcd.print(finger.fingerID);
  etat = 1;
  return finger.fingerID;
  delay(1000);
}

Each time I uncomment lines using SD, the Arduino resets at the end of the loop.
What is the problem?

You shouldn't repeatedly open the file, even if you close it in between.  Both the nature of flash based storage and the limitations of object oriented techniques in an Arduino's tight memory mean you should avoid unecessary operations like that.  Also you should check the validity of the file object before you try to do operations on it.

The solution to your problem is to extend your 2 states machine in a multiple states machine.
Declare the enum eState before setup():
typedef enum e_State {
    STATE_START = 0,    // starting the loop (add some initialisation)
    STATE_READ_FINGER,  // Step1: read the finger print
    STATE_DISP_FINGER,  // Step2: display the finger print
    STATE_OPEN_LOGGER,  // Step3: open the log file
    STATE_WRITE_LINE,   // Step4: append a timestamp finger print
    STATE_CLOSE_LOGGER  // Step5: close the log file
} eState;

And update the loop() function with the state-machine:
void loop()
{
    static eState LoopState = STATE_START; // to store the current state

    eState NextState;  // for the next loop

    switch (LoopState) {
    case STATE_START:
        // add additional settings
        NextState = STATE_READ_FINGER;
        break;
    case STATE_READ_FINGER:
        etat = 0; // keep use your 'etat'
        // or return a boolean from your 'getFingerprintIDez()'
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Put Finger");
        getFingerprintIDez();
        if (etat == 1) {
            NextState = STATE_DISP_FINGER;
        }
        break;
    case STATE_DISP_FINGER:
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("ID #");
        lcd.setCursor(4,0);
        lcd.print(finger.fingerID);
        NextState = STATE_OPEN_LOGGER;
        break;
    case STATE_OPEN_LOGGER:
        myFile = SD.open("data.csv", FILE_WRITE);
        if (myFile) {
            // record only if file is opened
            NextState = STATE_WRITE_LINE;
        }
        else {
            lcd.setCursor(0,0);
            lcd.print("Can't open file");
        }
        break;
    case STATE_WRITE_LINE:
        myFile.print(rtc.getDateStr(1));
        myFile.print("\t");
        myFile.print(rtc.getTimeStr(1));
        myFile.print("\t");
        myFile.println(finger.fingerID);
        myFile.flush();
        NextState = STATE_CLOSE_LOGGER;
        break;
    case STATE_CLOSE_LOGGER:
        myFile.close();
        lcd.setCursor(0,2);
        lcd.print("Loged");
        NextState = STATE_READ_FINGER;
        etat = 0;
        break;
    default:
        NextState = STATE_START;
    }
    // next loop()
    LoopState = NextState;
    delay(200);
}


text:
sending midi to software using arduino
Friends Here is what i want to ask.
I have a midi keyboard that is casio cps7. Its an old model so its not a USB midi keyboard.
I use it with a cheap midi to usb cable.
I just wanted to use my arduino to act like a midi to USB adapter. So, i can use my midi keyboard with that too.
I found some tutorials that uses this arduino like usb serial device. And there is also a code for it. The code itself has a command to play midi notes.
We receive serial signals from arduino and convert them into midi (by using another software that is serial midi converter, there is also virtual midi port for it which is midi-yoke). Thats how i used my arduino board once but the program code for it (what i installed) plays its own notes. I just want to send my midi out (from my keyboard casio cps7) to pc as serial via arduino. Thanks
I hope you guys now understand what i wanted to say :)

You want to do what? What keyboard? Which Arduino? Do you have MIDI conversion hardware? I think the change should be in the program code - what code? I already have installed midi yoke - what yoke? Link? I already have installed ... serial midi coverter in pc - what midi converter? Link? Please read How do I ask a good question?

So you want to connect the Uno's first UART to the PC, and the second UART to the keyboard, and let the Uno act as a bridge?

Yes u got that right. I want to use arduino uno to act like interface to pc over usb for my 5pin midi out of my casio cps7 keyboard


text:
Array values won't tokenize
char *p = I2CinBuffer; // array contains "string" "," "string"

but
char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
char *str;       // Temp store for each data chunk
int count = 0;

while ((str = strtok_r(p, ",", &p)) != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
}

does not enter while loop.
Many thanks but the hard coding of the values "6,100" give correct results as it stands. However, I am now aware that the Arduino code is working in C strings and I2CInBuffer is a C string on which the "strtok" or "strok_r" functions will NOT work. My question now is how to parse the C string I2CinBuffer to obtain 2 values separated by a comma i.e. "6, 100".

You're not using strtok_r properly.  You have to treat the first call to strtok_r differently to all subsequent calls, and I don't know what you're trying to do with the &p parameter - that could never work since you're breaking the source pointer with that.
According to the manual page:

The strtok_r() function is a reentrant version strtok().  The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.
On  the  first  call to strtok_r(), str should point to the string to be parsed, and the value of saveptr is ignored.  In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call.

Unless you're doing concurrent tokenising of multiple strings there is no reason to use the reentrant version of strtok.  Instead you should just go:
char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
int count = 0;

char *str = strtok(p, ",");
while (str != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
    str = strtok(NULL, ",");
}

Note how the first call, outside the while loop, passes the string to parse.  All subsequent calls (inside the while loop) pass NULL as the string to parse so it continues from the last point in the string rather than starting the string afresh every time from the start (with a broken string since strtok() is a destructive function).

A sequence of calls to strtok() that operate on the same string maintains a pointer that determines the point from which to start searching for the  next token.   The  first  call  to strtok() sets this pointer to point to the first byte of the string.  The start of the next token is determined by scanning forward for the next nondelimiter byte in str.  If such a byte is found, it is taken as the start of the next token.  If no  such  byte  is  found,  then there are no more tokens, and strtok() returns NULL.  (A string that is empty or that contains only delimiters will thus cause strtok() to return NULL on the first call.)

It is considered destructive because:

The end of each token is found by scanning forward until either the next delimiter byte is found or until the terminating null  byte  ('\0')  is  encountered.   If  a  delimiter byte is found, it is overwritten with a null byte to terminate the current token, and strtok() saves a pointer to the following byte; that pointer will be used as the starting point when searching for the next token.  In this case, strtok() returns a pointer to the  start  of  the found token.

So in other words, your string that started out as:
foo,bar,baz\0

ends up, after tokenizing, as:
foo\0bar\0baz\0

So after the first tokenizing, if you try and pass the string again as the first parameter, instead of "foo,bar,baz", it actually only sees "foo" since the string now ends after foo.
If you wanted to use the reentrant version you'd need to create a separate pointer variable for the save pointer and pass that as the third argument:
char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
int count = 0;
char *saveptr;

char *str = strtok_r(p, ",", &saveptr);
while (str != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
    str = strtok(NULL, ",", &saveptr);
}

Note that you still need to use the same "pass the string on the first call and pass NULL on all other calls" methodology since it is still destructive.

Many thanks but the hard coding of the values "6,100" give correct results as it stands. I am now aware that the Arduino code is working in C strings. I2CInBuffer is a C string.

@impartit The big question, then, is what is I2CinBuffer and how is it generated?

My question now is how to parse the C string I2CinBuffer to obtain 2 values separated by a comma i.e. "6, 100".

Example code:
int parseit (char * p, int * results, const int maxSize)
{
  int count = 0;
  char *str = strtok (p, ",");   // separate at each "," delimiter
  while (str != NULL && count < maxSize)
    {
    results [count++] = atoi (str);      // Add to array
    str = strtok(NULL, ",");
    }  // end of while
  return count;
}  // end of parseit

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  const int MAX_INTEGERS = 5;
  int inParse [MAX_INTEGERS];
  char  I2CinBuffer [50];

  strcpy (I2CinBuffer, "6,100");
  int found = parseit (I2CinBuffer, inParse, MAX_INTEGERS);
  for (int i = 0; i < found; i++)
    {
    Serial.print (i);
    Serial.print (" = ");
    Serial.println (inParse [i]);
    }  // end of for

}  // end of setup

void loop ()
{
  // rest of code here
}  // end of loop

Results from running it:
0 = 6
1 = 100

Thanks Nick that's great also but I don't wish to hard code the values "6, 100". The two comma separated values will vary and be received into I2CinBuffer from an external python script by a 'write_List' function using I2C.

Doing a strcpy was purely an example for showing the technique. In practice the contents of that would be what you received from wherever.

I2CinBuffer already contains "6, 100" so how will "strcpy (I2CinBuffer, "6,100");"  work.

If it already contains what you want, just omit that line. Be aware, as other answers have stated, that strtok destructively tokenizes. It replaces each delimiter with 0x00 so that afterwards, the variable has been altered. In other words, you can't tokenize it twice. This may or may not matter to you. As an example, if you wanted to display what you received, for debugging purposes, do that before calling strtok, not afterwards.

I am told  by Adafruit support that "strtok won't work on a string object which is what I2CinBuffer is to the Arduino". The data in I2CinBuffer receives the comma separated values from a Python write_list function (Adafruit_I2C.py library file). If I hard card the values as "strcopy(I2CinBuffer, "6,100") the existing strok_r function works just fine. Do you have time to look at the original source code at "http://letsmakerobots.com/blog/unixguru/controlling-raspberry-pi-arduino-bot-internet-part-1-3.? The author does not respond to my emails.

They may be referring to a String object, not a C string. There is a difference. I can't see relevant code on that page. Please amend your question and post a complete sketch that demonstrates the issue. Posting snippets doesn't really help here. It doesn't have to be the whole thing, just enough to demonstrate the problem.


text:
Arduino Comms disrupted, prevents program loading (catch 22)
I have written some software which, when loaded onto an Arduino Micro, blocks communications for some reason. Lets stipulate that there is something wrong with it.
Using the Ardiono IDE on Windows 10, and (ex internet) pressing the board's reset button twice within 5 seconds of power-up, then (device manager) a comms port comes into existence for 2 seconds, presumably under control of the micro-controller's bootstrap program.
In the IDE, you can only select an existing comms port. As above, a comms port comes into existence for 2 seconds.
The download button causes compilation and downloading to the comms port - typically taking 8 seconds.
Thus, one can only replace the duff program by selecting the briefly available comms port, compiling and downloading to it, which takes longer that the port availability window.
And so replacing the duff code with anything is impossible. Have I missed something here? Does anyone have some "emergency" code that waits for a port to appear and immediately loads something innocuous?
BTW the Tags restriction is preventing me from using meaningful tags.

try this: In Preferences turn on verbose output for Upload. while the board tries to Upload and can't find the right port, reset the board. perhaps it changes the port back to the one set in Tools menu and upload starts

That was very interesting. I did as you said, it failed, but then a message with the Arduino infinity/dipole symbol turned up at the bottom of the screen, saying "download to use ...". I did so, let it run, and it then ran, finding the new  comms port

I would suggest:

Turn on verbose compilation in the IDE.
Set up as you have been with the right port selected and go to upload - it will fail as normal
Find the avrdude command in the verbose output and copy the full command and its parameters
Open a command prompt or terminal window and paste in the command you copied (but don't run it yet).
Press reset twice to trigger the serial port creation
Run the command you pasted. It should immediately start uploading and "fix" your problem.

Thanks for your response, as see my previous one. Running the new verbose download, everything worked immediately, and the operations looked very much as you described above. I think someone at Arduino sent me this code change, which was just the job. Thanks all!


text:
Reverse DC motor direction every second automatically
I have the Arduino Starter Kit and I'm on project 10 Zoetrope. I've removed the switch that changes the direction as I don't want the reverse to happen when I press a switch. I want the reverse to happen based on time.
For example using code, I want the reverse to happen every second (the motor moves clockwise for the first second, counterclockwise for the next second, clockwise for the third second etc.)
I've search for solutions but I haven't found anything yet. I had no luck with the millis function as well.

Consider code of the following form.
// Declare some globals
byte direction=0, second, prev=0;

void loop() {
  second = millis()/1000;
  if (prev != second) {
    prev = second;
    direction = second & 1; // Direction is 0 or 1
    OutputTheNewDirection(direction);
  }

More generally, suppose you want to make a pattern of clockwise for j time units, alternating with counterclockwise for k time units.  Suppose a time unit is m milliseconds long.  You can use code as in the following example, where m is 500, j is 10, and k is 1.
// Declare some globals and constants
byte direction=0, tunit, prev=0;
enum { m=500, j=10, k=1 };

void loop() {
  tunit = (millis()/m) % (j+k);
  if (prev != tunit) {
    prev = tunit;
    direction = tunit < j; // Direction is 0 or 1
    OutputTheNewDirection(direction);
  }

As my coding skills are not the best i think i can figure this out. What if i want to change the direction as the time passes by. For example i want the direction to be clockwise when i press the on/off switch then after 5 seconds change it to counterclockwise then after half a second change to clockwise etc.

@paul, see edited answer for 5 seconds CW alternating with half a second CCW


text:
Combining mysensors with SD card (on an Ethernet Shield v2)
I'm trying to combine a MySensors network with the usage of a SD card. Currently I'm working with the SD card reader on the EthernetShield v2.
The NRF24L01+ chip I'm using is also using SPI but we used Soft-SPI to change the pins that is uses so I'm not using pin 4 or 10 (that are used to select the SD card as far is I know).
To read from the SD card I'm using the SdFat library.
When I exclude the following part of code, the messages are getting send and I don't have any weird resets:

if (!SD.begin(SD_CS_PIN)) {
    Serial.println("initialization failed!");
    return;
  }

But the card keeps resetting after booting and it gives these logs:
0;255;3;0;9;!TSF:MSG:SEND,0-0-15-15,s=0,c=1,ne.
0;255;3;0;9;MCO:BGN:INIT OK,TSP=1
14;Gateway startup complete.
0;255;0;0;18;2.1.1
0;255;3;0;9;MCO:BGN:STP
initialization done.
0;255;3;0;9;MCO:BGN:INIT OK,TSP=1
0;255;3;0;9;MCO:BGN:INIT GW,CP=RNNGA--,VER=2.1.1
0;255;3;0;9;TSM:INIT
0;255;3;0;9;TSF:WUR:MS=0
0;255;3;0;9;TSM:INIT:TSP OK
0;255;3;0;9;TSM:INIT:GW MODE
0;255;3;0;9;TSM:READY:ID=0,PAR=0,DIS=0
0;255;3;0;9;MCO:REG:NOT NEEDED
0;255;3;0;14;Gateway startup complete.
0;255;0;0;18;2.1.1
0;255;3;0;9;MCO:BGN:STP
initialization done.
0;255;3;0;9;MCO:BGN:INIT OK,TSP=1
0;255;3;0;9;!TSF:MSG:SEND,0-0-15-        15,s=0,c=1,t=24,pt=0,l=25,sg=0,ft=0,st=NACK:Message Gateway -> Pongno
0;255;3;0;9;MCO:BGN:INIT GW,CP=RNNGA--,VER=2.1.1
0;255;3;0;9;TSM:INIT
0;255;3;0;9;TSF:WUR:MS=0
0;255;3;0;9;TSM:INIT:TSP OK
0;255;3;0;9;TSM:INIT:GW MODE
0;255;3;0;9;TSM:READY:ID=0,PAR=0,DIS=0
0;255;3;0;9;MCO:REG:NOT NEEDED
0;255;3;0;14;Gateway startup complete.
0;255;0;0;18;2.1.1
0;255;3;0;9;MCO:BGN:STP
initialization done.
0;255;3;0;9;MCO:BGN:INIT OK,TSP=1

The code:
#define MY_DEBUG

#define MY_SOFTSPI
#define MY_RF24_CE_PIN 11
#define MY_RF24_CS_PIN 6
#define MY_SOFT_SPI_SCK_PIN 8
#define MY_SOFT_SPI_MISO_PIN 9
#define MY_SOFT_SPI_MOSI_PIN 7

#define MY_RADIO_NRF24
#define MY_RF24_CHANNEL 69
#define MY_NODE_ID 0
#define MY_GATEWAY_SERIAL

#include <MySensors.h>
#include <SPI.h>
#include "SdFat.h"
SdFat SD;

#define SD_CS_PIN 4

File myFile;
#define PONGNODEID 15

MyMessage msg(MY_NODE_ID, V_VAR1);

void setup() {
  // Open serial communications and wait for port to open:

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  msg.setDestination(PONGNODEID);

  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);

  if (!SD.begin(SD_CS_PIN)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

}

void presentation() {}

long lastSent = 0;

void loop() {
  if (millis() - lastSent >= 3000) {
    lastSent = millis();
    send(msg.set("Message Gateway -> Pongnode"), true);
  }
}


text:
Threshold to wake up signal
I have a sketch to put to sleep and wake up an Arduino Pro Mini 5V, but the problem is that sometimes when it is moved fast it wakes up itself, thing that I do not want. I have it configure to be waken up in the pin 2 by a rising signal using an interruption:

#define wakePin 2        // pin used for waking up

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

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

  pinMode(RLEDPIN, OUTPUT);
  pinMode(GLEDPIN, OUTPUT);
  pinMode(BLEDPIN, OUTPUT);
  pinMode(wakePin, INPUT);

  attachInterrupt(0, wakeUpNow, RISING );
}

void sleepNow()         // here we put the arduino to sleep
{

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register  // so sleep is possible. just a safety pin

    attachInterrupt(0,wakeUpNow, RISING); // use interrupt 0 (pin 2) and run function  // wakeUpNow when pin 2 gets LOW

    sleep_mode();            // here the device is actually put to sleep!! // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep: // disable sleep...

    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the // wakeUpNow code will not be executed  // during normal running time.

}

void loop()
{
    digitalWrite(GLEDPIN, HIGH); //set green led high
    digitalWrite(BLEDPIN, HIGH); //set blue led high
    digitalWrite(RLEDPIN, HIGH); //set red led high

  times = millis();

  if((times-times_f)>=12000)
  {
    times_f=times;
    Serial.println(times-times_f);
    digitalWrite(GLEDPIN, LOW); //Reset the LED's
    digitalWrite(BLEDPIN, LOW);
    digitalWrite(RLEDPIN, LOW);
    sleepNow();
  }
}

I think the problem is that it has a bit of rising signal while moving, so a solution could be to have a threshold in the reception of the signal, can it be done?

Do you mean when physically moving the Arduino? Are you using a breadboard with jumper wires or is everything soldered?

@Wildman Yes, when I move the whole thing very fast it restart. It is soldered with cables.

You should add pull-down resistors generally of 10k on the interrupt pin, this will resist the unwanted signals on that pin.

Please explain how you conclude this?

Pull-up and Pull-down resistors are used to correctly bias the inputs of digital gates to stop them from floating about randomly when there is no input condition.


text:
How to increase pinout switching?
Consider this code:
void loop() {
    digitalWrite(pinTest, HIGH);
    digitalWrite(pinTest, LOW);
}

On an Arduino Mega 2560, running 16MHz (=0.06us), I would expect the width of the pulse to be somewhere around 0.1us.
However, when measuring with my oscilloscope, I get around 4us high and 5-6 us low. I understand it could take some cycles to run the digitalWrite code, but this seems quite a lot.
How is that difference explained?

digitalWrite is not optimized to translate the value of pinTest to the proper port/bit combination.  If you need that, do it once in advance. Your code will be hardware-specific for avr-gcc targets.

@DataFiddler any resources on how to do that in advance?

Watch this youtube Why I’m switching over from the awesome Arduino IDE to Atmel Studio

Thanks all. Too bad, I am on Linux, so Atmel Studio is not an option, but I found a wait to build assembly code using arduino-cli and Visual Studio Code.

You do not need to go all the way down to assembly in order to get that
speed. You can do direct port access from your .ino file:
void setup() {
    DDRA |= _BV(PA0);  // pin 22 = PA0 as output
    for (;;) {
        PINA |= _BV(PA0);  // toggle PA0
    }
}

void loop(){}

This compiles to something that is almost equivalent to your assembly
code. Actually, it is a bit faster, as it uses rjmp instead of the
slower jmp instruction.
Edit: A few notes

As pointed out by timemage in a comment, you can save another CPU
cycle by writing PINA = instead of PINA |=.

This code, as well as your two examples, will exhibit a glitch every
1,024 µs. This is caused by the periodic timer interrupt used
by the Arduino core for timekeeping (millis(), micros() and
delay()). You can avoid the glitch by disabling interrupts before
going into the tight loop. Alternatively, if you do not use the
Arduino core at all, you can define a function called main()
instead of setup() and loop(): this will completely remove the
Arduino core initialization for your compiled program.

arduino-cli is useful for sparing you the complexity of the Arduino
build system (automatic installation of the cores and libraries,
libraries in multiple places that depend on the core you use...). If
you do not use the Arduino core, arduino-cli is of little use: a
very simple Makefile that calls avr-gcc and avrdude is all you
need for basic AVR development.

PINA = rather than PINA |=.  I'm not 100% certain what will happen with the SBI that PINA |= expr appears to be generating; but it if actually behaves as PINA = PINA | expr it is trying to toggle port pins in part based on the current read value of the port. In any case, PINA =  is sufficient and winds up generating an OUT which is 1 cycle compared to SBI's two cycles. It's peanuts. But then they are going for speed.

@timemage: You are right, PINA = is faster here. sbi is safe, as it is a real bitwise access, not a bytewise read-modify-write. PINA |=, on the other hand, is only safe when you know PINA lives in the bit-addressable part of the I/O space.

I suspected that about sbi simply because it would be much less useful otherwise.  Re. I/O space: Yeah I didn't spell it out, but PINH/PINJ/PINK/PINL (curiously no PINI; perhaps it looks too much like a 1) all result lds,ori,sts

I fixed it by using assembly code to run the program. Because I am using Linux, I couldn't use Atmel Studio, but you can easily use AVR assembly with arduino-cli.
Make your .ino like this:
extern "C" void myAssemblyMain();

void setup() {
    myAssemblyMain();
}
void loop() {
}

then add a pulse.S file with the assembly code:
#define __SFR_OFFSET 0

#include "avr/io.h"

.global myAssemblyMain

myAssemblyMain:
  sbi   DDRA, 0     ; Set PA0 as output

blink:
  sbi   PINA, 0     ; Toggle PINB
  jmp   blink

Using this code, I get a ~400ns pulse. Which is more than enough for my needs.

you can do the same with the Arduino IDE. no need for CLI

please update your question, because this does not answer the question you asked

@jsotola agreed it didn't answer the exact question, but it does give another way of reaching the same goal.

@Juraj thanks, I'll check that out. But I work a lot with Visual Studio Code, so staying within the same tool is preferable.


text:
Delay coding not working as expected
Added second attempt at bottom of code, Please check it, works with out lag time but never turns Vacuum off?  This project is pretty well explained in the code description. My main problem is I need a delay for ditialWrite(vacPin,LOW);.  With this part included the stepper doesn't react a quickly as before 2/3 sec lag, & the ACS712 current sensor does not read at all in the console screen.
I have tried different operatives, statements, and relocating the code in different spots with no luck!
I think this has a simple fix, but it has alluded me!. Hope this is clear enough, any help would be appreciated.
/*This version works as is **EXCEPT** the Delay vac 4 sec has to be turned off. See ########### area for Problem.
/*Auto Blast gate project:  for dust collection in wood shop.
  Arduino Nano
  ACS712 current sensor
  DRV8825 stepper driver
  Nema 17 stepper
  Each tool will be monitor by a current sensor and when that analog port exceeds a given threshold
  1. Rotate the stepper to a predetermined position to align ports for that tool.
  2. After the gate is align a digital pin will drive relay to turn on Vacuum system.
      Vacuum will stay on as long as sensor exceed the threshold while tool is running.
      **When tool stops vacuum will continue for 4 seconds to clear remaining dust.**
  3. If the same tool is used next, the Stepper will remain in it's current position.
      But the vacuum system should still operate the same.
  4.  currently using buttons to simulate tools and also one ACS712 for testing  */

// defines pins numbers
const int stepPin = 3;
const int dirPin  = 2;
const int enPin  = 8;
const int vacPin = 4; //simulate Vacuum relay

int ca = 0;  //currentAngle
int na = 0;  //angle
int stepPerAngle = 5 / 9; // full step = 1.8 or could have used "*1.8"
int   numstep;
int analogValue = 0;

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

  // Sets the 3 pins as Outputs
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  pinMode(enPin, OUTPUT);
  pinMode(vacPin, OUTPUT); //Just added this for vac

  //set values for 2 outputs
  digitalWrite(enPin, LOW);
  digitalWrite(dirPin, HIGH);
  digitalWrite(vacPin, LOW); //just add this for vac

}

void loop() {
  int n;
 analogValue = 0;

  // Assign button degrees
  if      ( analogRead(A0) > 600) {
    analogValue = (analogRead(A0));
    Serial.print("AO = ");
    Serial.println(analogValue);
    na = 0;

  }
  else if ( analogRead(A1) > 600) {
    analogValue = (analogRead(A1));
    Serial.print("A1 = ");
    Serial.println(analogValue);
    na = 45;
  }

  else if ( analogRead(A2) > 600) {
    analogValue = (analogRead(A2));
    Serial.print("A2 = ");
    Serial.println(analogValue);
    na = 225;
  }

  else if ( analogRead(A3) > 600) {   //=tool on
  analogValue = (analogRead(A3));
    Serial.print("A3 = ");
    Serial.println(analogValue);
    na = 270;

  }

 /*###########################################################
 **this is where I need help.  The first if statement works as it should.
 when those 2 condition are met the vacPin goes high.** */

  if(analogValue > 600 && ca==na) {
    digitalWrite(vacPin, HIGH);
  }

/* **this part is not working correctly.  If the delay is remove it works as the "else if" statment reads.
  I need the delay so when a tool is stopped, the vacuum continues for a few secounds to clear remaining saw dust** */

else if (analogValue < 600) {
   delay (4000); **/*  with this on:
             the stepper does not start as quickly as before,
             the analog will not read the ACS712 sensor at all,  only the buttons*/**
    digitalWrite(vacPin, LOW);
  }

//################################################################################

  if ( ca != na ) {

  //2nd SCENARIO
  if (na - ca > 0 && na - ca <= 180)
    { digitalWrite(dirPin, HIGH);
      n = ((na - ca) * 5 / 9);
      numstep = n;
      ca = na;

    }

    //3rd SCENARIO
    else if (ca - na > 0 && ca - na > 180)
    { digitalWrite(dirPin, HIGH);
      n = ((na + 360 - ca) * 5 / 9);
      numstep = n;
      ca = na;
    }

    // 4th SCENARIO
    else if (na - ca < 0 && na - ca <= 180)
    { digitalWrite(dirPin, LOW);
      n = ((ca - na) * 5 / 9);
      numstep = n;
      ca = na;
    }

    //5th SCENARIO
    else if (na - ca > 0 && na - ca > 180)
    { digitalWrite(dirPin, LOW);
      n = ((ca + 360 - na) * 5 / 9);
      numstep = n;
      ca = na;
  }

    for (int x = 0; x < numstep; x++) {

      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);  //speed
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);

    }

    delay(200);
  }

}

#################################################
if(analogValue > 600 && ca==na) {
    digitalWrite(vacPin, HIGH);
  }

/* this part is not working correctly.  If the delay is remove it works as the "else if" statment reads.
  I need the delay so when a tool is stopped, the vacuum continues for a few secounds to clear remaining saw dust */

// another variation to the section in question
else if (analogValue < 600 && vacPin==HIGH) {
   delay (4000);
/*  written this way it works but never turn Vacuum off?*/
    digitalWrite(vacPin, LOW);
  }

Thanks for your reply,  I rewrote another way  if(analogValue > 600 && ca==na) {
digitalWrite(vacPin, HIGH);
}
/* this part is not working correctly.  If the delay is remove it works as the "else if" statment reads.
I need the delay so when a tool is stopped, the vacuum continues for a few secounds to clear remaining saw dust */
else if (analogValue < 600 && vacPin==HIGH) {
delay (4000); /*  written this way it works but never turn Vacuum off?*/
digitalWrite(vacPin, LOW);
}   This way works but never turns vacuum off after its on?

// another variation to the section in question
else if (analogValue < 600 && vacPin==HIGH) {
delay (4000); /*  written this way it works but never turn Vacuum off?*/
digitalWrite(vacPin, LOW);
}

Sorry again! I did read your comments and have no idea why part of my reply didn't show up and the rest doesn't show the way it looked when entered.  I'm interested in your input but afraid to try again in a reply.  What I learning is I need to go to a nonblocking delay.

then I'll say it again ... please, do not put code into comments ... add code, and any new info, to your post

I guess I'm a slow learner, I finally get what your telling me about the code (not in comments) I thought you were telling me not to put comments in the code! At this point I can't find your original question.  Learning this system is about as hard as the coding itself "for me".  Thanks for you patience.

It's not exactly clear what you're trying to do, but I think you want to start the vac and start the stepper, then 4 seconds later stop the vac. The 4 second delay forces the rest of your code to wait (doing nothing) during the 4 seconds.
Look at the Arduino IDE example program, BlinkWithoutDelay. The technique used there is what you need to use instead of delays, to allow your program to manage multiple things at once. This technique is called non-blocking; any time part of your program waits for something to happen blocks the code from doing anything else until that 'something' completes.
Search for non-blocking programming to read more. There are plenty of articles on the web, including in Arduino Stack Exchange that discuss that.
Update (following your 2021-05-05, 20:48Z update):
Here is an answer I wrote to similar question in which I wrote about non-blocking programming in more detail. The short answer is that you can't use delay() when you need to monitor or control several things simultaneously. Delays keep anything else from happening until they expire which is what is keeping your stepper from advancing as you intended. You need to do something like:
if the tool is running,
  ; // do nothing
else,
  save the time;    // this is the tool-stopped time
  move the stepper; // I assume the stepper completes in < 4s
end

if the tool is stopped and the vac is running,
  if (current_time - saved_time) >= 4000,
    stop the vac;
  end;
end;
// and let loop() keep running

Notice that this never waits for the tool or the fan. It just checks quickly and often, whether something needs to be done; if so, it does it; and in any case it continues on.
Because this is in your loop function, this code runs over and over again, so eventually, when 4 seconds has passed (in the case of the vac), the vac will get stopped, but meanwhile, the stepper has been able to run and any other small tasks needing doing will have an opportunity. The important point is, your code never hangs around waiting for anything to happen; it just very rapidly checks everything that could need to be {started, stopped, accelerated, ...}, if/when something is ready to be done, it does it, but it moves on immediately, in either case.

Thanks,  I will read up on that,    Your interpretation of what it does is close. When tool detected, move the stepper to position, turn on vacuum, when tool is turn off, vacuum remains on for 4 sec.   Thanks again I'll check it out.

https://www.instructables.com/Simple-Multi-tasking-in-Arduino-on-Any-Board/

That instructables presents the same ides, now structured in a nicer way. Note the important point: Each task gets many, frequent opportunities to execute. They decide whether or not they need to use any one of those opportunities, but they never wait. "Do or not do; there is no wait" to paraphrase Yoda.

I don’t know where to start but, this worked PERFECTLY! I need to work on stepper speed and ramp Length to smooth out, or jumpers on the DRV8825 expansion bd. Other than that, I want to understand the library! I went to the readme and it explained the thing it can do, but I don’t know how to utilize on my own. I noticed your name and written by are the same! Am I talking to a person or a company? Thanks again
Thanks for everyone else that help as well and I need to study some of those solutions as well!
MicroBahner
May 8
This would be my suggestion with MobaTools:
/*This version works as is EXCEPT the Delay vac 4 sec has to be turned off. See ########### area for Problem.
Auto Blast gate project:  for dust collection in wood shop.
Arduino Nano
ACS712 current sensor
DRV8825 stepper driver
Nema 17 stepper
Each tool will be monitor by a current sensor and when that analog port exceeds a given threshold

Rotate the stepper to a predetermined position to align ports for that tool.
After the gate is align a digital pin will drive relay to turn on Vacuum system.
Vacuum will stay on as long as sensor exceed the threshold while tool is running.
When tool stops vacuum will continue for 4 seconds to clear remaining dust.
If the same tool is used next, the Stepper will remain in it's current position.
But the vacuum system should still operate the same.
currently using buttons to simulate tools and also one ACS712 for testing
*/
// suggestion with MobaTools for driving the stepper and timer fuction
#include <MobaTools.h>

// defines pins numbers
const int stepPin = 3;
const int dirPin  = 2;
const int enPin  = 8;
const int vacPin = 4; //simulate Vacuum relay
const int stepPer360Degree = 200; // Number of steps for one revolution ( adjust to your needs )
MoToStepper stepper ( stepPer360Degree, STEPDIR );
MoToTimer vacTimer; // for delayed switch off
const long runOnTime = 4000;
int na = 0;  //angle
int analogValue = 0;
void setup() {
Serial.begin(9600);
// Setup the stepper
stepper.attach( stepPin, dirPin );
stepper.setSpeedSteps( 1000, 20 ); // sets Speed and ramplength
stepper.attachEnable( enPin, 100, LOW ); // Disable after 100ms. enabled is LOW
pinMode(vacPin, OUTPUT); //Just added this for vac
//set values for 2 outputs
digitalWrite(vacPin, LOW); //just add this for vac
}
void loop() {
analogValue = 0;
// Assign button degrees
if      ( analogRead(A0) > 600) {
analogValue = (analogRead(A0));
Serial.print("AO = ");
Serial.println(analogValue);
na = 0;
}
else if ( analogRead(A1) > 600) {
analogValue = (analogRead(A1));
Serial.print("A1 = ");
Serial.println(analogValue);
na = 45;
}
else if ( analogRead(A2) > 600) {
analogValue = (analogRead(A2));
Serial.print("A2 = ");
Serial.println(analogValue);
na = 225;
}
else if ( analogRead(A3) > 600) {   //=tool on
analogValue = (analogRead(A3));
Serial.print("A3 = ");
Serial.println(analogValue);
na = 270;
}
// position stepper if needed
if ( stepper.read() != na ) stepper.write( na );
// start vac if tool is on and stepper is in position
if (analogValue > 600 && !stepper.moving()) {
digitalWrite(vacPin, HIGH);
}
if ( vacTimer.expired() ) {
// switch off vac if timer expires
Serial.println( "Vac = off");
digitalWrite(vacPin, LOW);
}
if (analogValue < 600 && digitalRead( vacPin ) && !vacTimer.running()) {
// start timer to switch off vac after time
Serial.println( " start vac run-on-time" );
vacTimer.setTime( runOnTime );
}
}
If you want to give it a try, the library can be installed by means of the library manager ( enter mobatools in the search field )


text:
74HC595 chip with 7 segment display constantly displays either all 1's or all 0's
I made a simple circuit with an Arduino Nano ESP32, where I have connected a 74HC595 8-bit shift register chip, as well as a 7 segment display with a 100 ohm resistor on common (cathode) to show the shift register's state.
Expected Behavior
Seven segment display shows binary counting from 0-255.
Observed Behavior
The seven segment display continuously shows 8., which basically means the state of the shift register is 0b11111111.
When I use 5V (VBUS) instead of 3.3V for VCC of the IC, the shift register shows all zeros instead of all ones.
Attempts at Debugging
I have checked all input cables with my multimeter to check for any broken connections and everything seems to be fine. I also replaced the chip itself multiple times, same results. I tried replacing the resistor at the common of the seven segment display to something like 1,000 ohm, then back. Same results. I also used different sketches for testing, same results.
Resources
I made the current version of my circuit and code as a WOKWI (emulator) project: https://wokwi.com/projects/396140725340271617 [OUTDATED (also wont update for some reason)]
It features about the same exact connections I have on my breadboard.
Here is a screenshot of the circuit:

And the code, just in case wokwi might cease to exist in the future..
//**************************************************************//
//  Name    : shiftOutCode, Hello World
//  Author  : Carlyn Maw,Tom Igoe, David A. Mellis
//  Date    : 25 Oct, 2006
//  Modified: 23 Mar 2010
//  Version : 2.0
//  Notes   : Code for using a 74HC595 Shift Register           //
//          : to count from 0 to 255
//****************************************************************
//Pin connected to ST_CP of 74HC595
int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;
void setup() {
//set pins to output so you can control the shift register
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void loop() {
// count from 0 to 255 ankKomd display the number
// on the LEDs
for (int numberToDisplay = 0; numberToDisplay < 256; numberToDisplay++) {
// take the latchPin low so
// the LEDs don't change while you're sending in bits:
   digitalWrite(latchPin, LOW);
// shift out the bits:
shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);
//take the latch pin high so the LEDs will light up:
digitalWrite(latchPin, HIGH);
// pause before next value:
delay(500);
}
}

Consider copying that circuit image and code to your question above. People here don't like off site links as they can break over time. The idea is to keep these questions / answers for others to read even years from now.

If you need LED current limiting resistors, you will need one for each segment.  Not just one for the entire display. By the way, there are no resistors in the circuit diagram. Did you forget to place them?

Yes, sorry. I unfortunately dont have enough resistors to place one for each segment, so for now I've placed one for common. I'll edit my question to include the screenshot in the question, thanks.

You haven't made it very clear what you are attempting to do. If you are trying to use an 7 segment display to represent 8 bit binary numbers (between 0 and 255 dec.) then you have to show a mapping between each segment and the position of that segment between high order and low order binary bit. For example, it could be decimal point = high order bit (bit7), middle dash (segment G) = bit 6 etc.

The line setting latch to low is commented out. That alone breaks the code, as 74595 latches on the rising edge only.

BTW. This is why 595 datasheet call this pin "storage register clock", not "latch".

@Matt, oh right. sorry. I was doing that for debugging. I'll try again without it.

@Matt, same behavior.

This is because you have even more problems than that. Supplying 3v3 for the register is also totally wrong, as the mcu outputs 5v high signals. Even though the ground is common for both chips, the datasheet allows input voltages only upto vdd+0.5 AFAIR.

@Matt, I want to remind you that I'm using an Arduino Nano ESP32, which uses 3.3V as its operating voltage. What do you mean "the MCU outputs 5V high signals"?

Your picture still shows regular nano.

Apparently, the pinout is wrong. D12 is not 12 for esp32, etc.

@Matt, the reason why the picture shows a regular Nano is because the emulator does not have a Nano ESP32. I included in my introduction that it is an Arduino Nano ESP32. Anyways, in my code I tried using D12 instead of 12, D11 instead of 11 and so on.. There is no difference in the behavior.

I can't believe a one second delay is needed to clock data out. I have loops that clock out bits using SPI with no delays, which is even faster than shiftOut. See Using a 74HC595 output shift register as a port-expander.
You have some other issue.
Possibly what is happening is that it is working perfectly, but the number is changing so quickly that it appear that all segments are on.
Plus, you really shouldn't be testing without current-limiting resistors on every segment. A single common one will behave weirdly depending on how many segments are on at a time.

Hi, thanks for your answer. I did some more experimenting and turns out that you're right, I don't need a one second delay to clock data out, but I do need SOME kind of delay to see the segments light up. So yes, I guess the numbers were changing so quickly that I couldn't see them changing.

As for the resistors, I sadly don't have enough resistors to do that right now, and I've done some reading and concluded that the only side effect of having a single common one is a dimmer display when more segments are enabled. For now I should be fine but once I get some better resources I'll make sure to put resistors for each segment.

I would've never ever expected this, but turns out that my MCU was 'too fast'  (i suppose) and so nothing would show. This is the code before the fix:
    digitalWrite(latchPin, LOW); // Latch the data
    // no delay
    digitalWrite(latchPin, HIGH); // Unlatch for next data

and this is the code after:
    digitalWrite(latchPin, LOW); // Latch the data
    delay(1000);     // Short delay for visibility (adjust as needed)
    digitalWrite(latchPin, HIGH); // Unlatch for next data

I'm still experimenting with the shift register so I'll edit this answer if anything new pops up, or if my answer is entirely wrong.
EDIT: I did not need a one second delay between clock pulses, I appearantly just needed some delay to actually see the seven segment displays changing. (thanks @NickGammon)
EDIT: Here's the full code if anybody wants it, it displays a spiraling animation on the 7 segment display.
uint8_t latchPin = D8;
uint8_t clockPin = D12;
uint8_t dataPin = D11;

const byte segments[10] = { // Lookup table for digit patterns (common cathode)
  0b00111111,  // 0
  0b00000110,  // 1
  0b01011011,  // 2
  0b01001111,  // 3
  0b01100110,  // 4
  0b01101101,  // 5
  0b01111100,  // 6
  0b00000111,  // 7
  0b01111111,  // 8
  0b01101111   // 9
};

void setup() {
  // Set control pins as outputs
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

  Serial.begin(115200); // Start serial communication for debugging
  Serial.println("Starting...");

  displaySegments(0x00000000); // reset on startup, not needed just makes it look better ig
  delay(1000);
}

void spiralAnimation() {

  // Loop through each segment in the spiral order
  for (int i = 0; i < 7 - 1; i++) { // 7 being the number of segments, ignoring G so it looks better
    shiftOut(dataPin, clockPin, MSBFIRST, 0b00000001 << i);
    digitalWrite(latchPin, LOW);
    delayMicroseconds(1000);
    digitalWrite(latchPin, HIGH);
    delay(80); // Adjust delay for animation speed
  }
}

void loop() {
  // Loop through each digit pattern (modify for specific display)
    // for (int i = 0; i < 10; i++) {
    //   shiftOut(dataPin, clockPin, MSBFIRST, segments[i]);
    //   digitalWrite(latchPin, LOW); // Latch the data
    //   delay(100);     // Short delay for visibility (adjust as needed)
    //   digitalWrite(latchPin, HIGH); // Unlatch for next data

    //   Serial.print("Displaying: ");
    //   Serial.println(i);
    // }

    spiralAnimation();
}

void displaySegments(byte pattern) {
  shiftOut(dataPin, clockPin, MSBFIRST, pattern);
  digitalWrite(latchPin, LOW);
  delayMicroseconds(1000); // no need to edit this
  digitalWrite(latchPin, HIGH);
}

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val) // just in case
{
      uint8_t i;

      for (i = 0; i < 8; i++)  {
            if (bitOrder == LSBFIRST)
                  digitalWrite(dataPin, !!(val & (1 << i)));
            else
                  digitalWrite(dataPin, !!(val & (1 << (7 - i))));

            digitalWrite(clockPin, HIGH);
            digitalWrite(clockPin, LOW);
      }
}

So far with some quick testing everything's actually working as expected.

First of all, the code in the question does not match the code in "the supposed solution". ShiftOut function is pretty slow, so it could work as an extra delay when put between latch settings. So the code in question looks robust in this sense, imo.
Next, it is dubious to require a whole millisecond delay even in the second case. 74hc595 chip should be able to deal with signal faster than 10 MHz even when on 3v3 power supply. And digitalWrite function is also quite slow (as it is with the whole Arduino's extra compatibility layer), so I don't see any problem here.
More likely, this is due to parasitic capacitance. So the latch line (too long?) doesn't have enough time to discharge even at few megs speed. Then the shift register will never see low voltage level, except on startup. Proper connections (soldering wires, or at least using only short jumpers) should solve the issue.


text:
Arduino IDE Failing to Compile Any Sketches
OS: Windows 11
Arduino IDE Version: 2.3.2
I recently opened up my Arduino IDE to find that nothing--absolutely nothing--would compile. Whenever I tried, I got the following error message:
Using board 'uno' from platform in folder: C:\Users\abrah\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6
Using core 'arduino' from platform in folder: C:\Users\abrah\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6

Detecting libraries used...
C:\Users\abrah\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Users\abrah\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6\cores\arduino -IC:\Users\abrah\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6\variants\standard C:\Users\abrah\AppData\Local\Temp\arduino\sketches\5ECA4E3B637A45D6CBCAE2784E028875\sketch\sketch_aug10a.ino.cpp -o nul
Error while detecting libraries included by C:\Users\abrah\AppData\Local\Temp\arduino\sketches\5ECA4E3B637A45D6CBCAE2784E028875\sketch\sketch_aug10a.ino.cpp
Generating function prototypes...
C:\Users\abrah\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Users\abrah\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6\cores\arduino -IC:\Users\abrah\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6\variants\standard C:\Users\abrah\AppData\Local\Temp\arduino\sketches\5ECA4E3B637A45D6CBCAE2784E028875\sketch\sketch_aug10a.ino.cpp -o C:\Users\abrah\AppData\Local\Temp\1032671058\sketch_merged.cpp
avr-g++: error: device-specs/specs-atmega328p: No such file or directory
exit status 1

Compilation error: exit status 1

I have uninstalled and reinstalled the IDE from the website multiple times, I have attempted to compile multiple pre-coded examples on both a Uno board and a Nano board, and I have attempted to trace the file reported as missing. (It does not exist). I have also compiled and uploaded my code using the Arduino Cloud Editor, and that worked fine. However, the Cloud Editor is still a prototype and leaves a few things to be desired, so I would like to return to using the regular IDE as soon as possible.

try compiling an empty sketch

The specific error message is "device-specs/specs-atmega328p: No such file or directory", so please check your installation directory for this. What did you do with your PC (install other software, organizing your home directory, general clean up, ...) since the last time it worked? It does not need to be some action with the Arduino IDE.

@jsotola it gives the same error
@ the busybee my computer account was recently (accidentally) wiped. Since that event, I have re-installed the Arduino IDE, because the former auto-recovered version was not working.

Removing arduino ide and reinstall only updates that IDE, but all the boards, compilers and arduino cores are stored in C:\Users\abrah\AppData\Local\Arduino15 .. If you have issue, rename it into for example Arduino15_backup and start IDE (and install all the boards you need again).

@KIIV will go and try that now

YES! It worked! Thank you so much! @KIIV if you want to submit that comment as a full answer I'd be more than happy to accept and upvote it.

Error messages indicates there is an device spec missing somewhere in compiler directory structure. As all installed boards from Board Manager are stored outside Arduino IDE installation directories (C:\Users\abrah\AppData\Local\Arduino15) so it's not affected by reinstallations of IDE. You can even run different IDE's and all are using this directory.
You can either delete this directory (or rename) and download all the boards you are using again and they should be completely fresh.
I forgot to mention you could try to uninstall Arduino AVR boards in Boards Manager and reinstall it again or switch to the previous version and then back to to latest

OP writes in a comment "my computer account was recently (accidentally) wiped". Arduino15 folder is in users home folder so I guess OP only needed to install the packages

I have seen that happen when you don't select a target (a board to compile to) or don't change the target when trying to compile code for the next one


text:
Temperature sensor bugs
My project is based on a moving fan using DHT11 sensors. I have used 2 void loops and the IDE is showing an error

"exit status 1
  redefinition of 'void loop()'"

One doubt: Can we use 2 void loops in the code? Please see and identify the errors.
2nd doubt: dht DHT; shows error

"exit status 1
  'dht' does not name a type" for my version of Arduino 1.8.1

#include <DHT.h>
#include <DHT_U.h>
#include <Adafruit_Sensor.h>

 // Including library for dht
#include<LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
#define dht_dpin 12
dht DHT;
#define pwm 9

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

void loop() {
  // put your main code here, to run repeatedly:
  // put your setup code here, to run once:
  lcd.begin(16, 2);
  lcd.clear();
  lcd.print(" Fan Speed");
  lcd.setCursor(0,1);
  lcd.print(" Controlling");
  delay(2000);
  analogWrite(pwm, 255);
  lcd.clear();
  lcd.print("Circuit Digest ");
  delay(2000);
}

void loop() {
  DHT.read11(dht_dpin);
  int temp=DHT.temperature;
  lcd.setCursor(0,0);
  lcd.print("Temperature:");
  lcd.print(temp);   // Printing temperature on LCD
  lcd.print("oC");
  lcd.setCursor(0,1);
  if(temp <26 ) {
    analogWrite(9,0);
    lcd.print("Fan OFF");
    delay(100);
  } else if(temp==26) {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%");
    delay(100);
  } else if(temp==27) {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%");
    delay(100);
  } else if(temp==28) {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%");
    delay(100);
  } else if(temp==29) {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%");
    delay(100);
  } else if(temp>29) {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%");
    delay(100);
  }
  delay(3000);
}
}

There can be only one loop() function, and you have two.

Two void loops are not allowed, why do you need one??

After I remove the 2nd loop,then also there is an error.

send me the code after removing the loop, and also be specific  about what you are trying to do.

“dht DHT;”: You mean DHT dht;. The syntax is type_name variable_name; and the type name is DHT (upper case).

Here, below is updated version of your code.
Before running this code, you have to download DHT library. Just click on Click Here and you find good explanation & library of DHT11 Sensor. Becuase this library I usually preferred for my code. So, please download it and then run my code.
Click Here
And two void() loop never used. Put your all logic in one void() loop.
Note: This is not tested code. So if you face any problem then update me.
#include <dht.h>                // DHT library
#include<LiquidCrystal.h>       // LCD library

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

dht DHT;

#define DHT11_PIN 12

#define pwm 9

float temp;

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

  pinMode(pwm, OUTPUT); //Pin as OUTPUT
}

void loop()
{

 int chk = DHT.read11(DHT11_PIN);
 temp = DHT.temperature;
 Serial.print("Temperature = ");
 Serial.print("\t");
 Serial.print(temp);
 delay(1000);

 lcd.begin(16, 2);
 lcd.clear();
 lcd.setCursor(0, 0);
 lcd.print("Fan Speed");
 lcd.setCursor(0, 1);
 lcd.print("Controlling");
 delay(2000);
 lcd.clear();
 lcd.setCursor(0, 0);
 lcd.print("Circuit Digest");
 delay(2000);
 lcd.clear();
 lcd.setCursor(0, 0);
 lcd.print("Temperature:");
 lcd.setCursor(10, 0);
 lcd.print(temp);

 lcd.setCursor(0, 1);

 if(temp < 26 )
 {
    analogWrite(pwm, 0);
    lcd.print("Fan OFF");
    delay(100);
 }
 else if(temp == 26)
 {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%");
    delay(100);
 }
 else if(temp == 27)
 {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%");
    delay(100);
 }
 else if(temp == 28)
 {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%");
    delay(100);
 }
 else if(temp == 29)
 {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%");
    delay(100);
 }
 else if(temp > 29)
 {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%");
    delay(100);
  }
}


text:
Serial data is not sent on interrupt
I have a short program which should receive data, use this data to turn on/off an LED, and send data when a button is pressed. It is deployed on a Digispark board. The button is connected to INT0 port (PB2). The interrupt works, but data is not send. Receiving data works fine.
What am I missing here?
#include <SoftSerial.h>

#define RxD 1
#define TxD 0
#define out 3
#define btn 2
#define testled 4

SoftSerial blueToothSerial(RxD, TxD); //RX, TX
volatile int buttonState = 0;

void setup() {
  pinMode(out, OUTPUT);
  pinMode(btn, INPUT);
  pinMode(testled, OUTPUT);
  setupBlueToothConnection();
  digitalWrite(out, HIGH);
  digitalWrite(testled, HIGH);
  attachInterrupt(0, intrpt, CHANGE);
}

void loop() {
  char newVal;
  if(blueToothSerial.available()){
    newVal = blueToothSerial.read();
    if (newVal == '1') {
      digitalWrite(out, HIGH);
    } else {
      digitalWrite(out, LOW);
    }
  }
}

void intrpt() {
  buttonState = digitalRead(btn);
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(testled, HIGH);
  } else {
    // turn LED off:
    digitalWrite(testled, LOW);
    blueToothSerial.println("0");
  }
}

void setupBlueToothConnection() {
  blueToothSerial.begin(9600);
  blueToothSerial.print("\r\n+STWMOD=0\r\n");
  blueToothSerial.print("\r\n+STNA=HC-05\r\n");
  blueToothSerial.print("\r\n+STOAUT=1\r\n");
  blueToothSerial.print("\r\n+STAUTO=0\r\n");
  delay(2000);
  blueToothSerial.print("bluetooth connected!\n");
  delay(2000);
  blueToothSerial.flush();
}

EDIT
Serial data is sent fine. The above code works. On Windows I can see the data are coming, but not on OS X.

it appears your interrupt would trigger itself, it that intended?

Which board are you using here?

@Majenko Digispark with attiny85 http://i.imgur.com/LT4szAd.png

@Dandavis it triggers itself because of lack of debouncing, but shouldn't it send data even if it's unintentionally triggered?

no, i mean you println() on the TX pin, which changes its hi/low state, triggering the interrupt. TX==0

@dandavis, ohh I see... I thought 0 represents INT0... Now I've tried with attachInterrupt(digitalPinToInterrupt(btn), intrpt, CHANGE) but it cannot compile because digitalPinToInterrupt is not declared in the scope.

hmmm. https://forum.arduino.cc/index.php?topic=370167.0 ?

@dandavis seems 0 is INT0, which is on PB2 - https://digistump.com/board/index.php/topic,1060.msg12633.html#msg12633

Why would you use software serial on the hardware serial pins?  If you're going to use those pins, then just use Serial.  It works a lot better than any flavor of soft serial.

If you are handling interrupts then you need to keep the code as quick and simple as possible.  I suspect that in this case calling blueToothSerial.println is what's causing the problem. It may well be calling an operation that an ISR can't call and so it fails and your code doesn't write the data you expect it to.
All I ever do in ISRs is set flags and then get the 'normal' code to handle changes to the flags. Personally I wouldn't do the digitalWrites within the ISR. Have two volatile variables, one for the pin state and one when sending a message is required and handle those in your loop().


text:
Converting a message received in char buffer to integer
I am receiving a message from my mobile to my microcontroller via GSM. The message is in a char buffer, but I want to convert it to an integer as I want to perform some mathematical operations on it. I tried many functions such as atoi, toint but it's not working. Please let me know if there is any way in which I could do this conversion.

int x = String( chars ).toInt() works if nothing else...

You'd better post your char buffer content here. There is a chance it might contain something can't be converted into integer.

i am only sending integer data such as 242,etc

"not working" is not an useful description of a problem.

atoi should have worked.  If it didn't then you have some other mistake.  If you'll post the code that you were using then that would make it possible for someone to try to spot the problem and help you.

atoi() is the simplest way:
int val = atoi(buf);

If that doesn't work then your buffer doesn't start with the number you are after. If that is the case you will have to work out where in the buffer the number is and convert just that portion. How you do that depends on what the format of the data is in your buffer.


text:
HC-06 RX pin usefulness
I have a HC-06 bluetooth module. The module has an RX and TX pin (the RX pin receives data and TX transmits data) which connect to the TX and RX pin of an Arduino respectively (in my case an Arduino pro mini).
My question is in what scenario would someone use the RX pin of the module(basically for what purpose would the bluetooth module receive a signal from the Arduino)?
For example let's say i have a simple LED that i turn off and on. I just sent the signal from my phone to the module and the module sends the signal to the Arduino. So basically i've connected the TX pin of the module (which transmits the data) with the RX pin of the Arduino (which receives the data).
In order to connect the RX pin of the module with the TX pin of the Arduino i have to use a voltage divider as the module only accepts 3.3 volts of signal while the Arduino transmits 5 volts of signal. I want to avoid that because in my project i need the PCB to be quite small.
So if someone only wants to transmit data from the module to the Arduino, is there a reason on why would he connect the other two pins?

If you never want to change the configuration of the module either, then no, you don't need to connect the module's RX pin.
However many people want bi-directional communication. Not only the ability to send a signal to turn the LED on or off, but also the ability to get the current state of the LED - is it on or off?
Or maybe to send an analog reading. Or the data from some sensor.
The HC-06 is a bi-directional module. If you choose to use only one direction then you only need to wire in one direction. However, tie the RX pin to 3.3V with a 10KΩ resistor to stop it floating and consuming extra power or causing random noise to be transmitted to your phone.
In fact, it's just like a phone. You can call someone up and just speak to them without listening to what they are saying. That's fine if all you want to do is call Mom and say "Pick me up in 5 minutes" and hang up. But if you want to ask your Mom "Can you pick me up in 5 minutes?" you have to actually listen for her answer "No, walk home you lazy oik!".


text:
Arduino relay. risks?
I just started working with arduinos recently. I'm really interested in working with relays. I would like to turn a desk lamp on and off using an ios app or a web browser button. I have no experience working with relays but I would love to experiment with relays in order to turn a desk lamp on or off based on an external switch in like an IOS app or a browser.
I am wondering what are the risks in relays with arduino ? I would like to switch a desk lamp on or off using a relay but I don't really understand the risks with creating a desk lamp powered using a wall socket and turned on or off using a arduino relay module . What is the worst case scenario if I screw up ? What are the risks and precautions I should take while working with relays and trying to build a relay controlled desk lamp?
I live in an apartment and I am trying to make sure that my entire building does not lose electricity or I don't screw up the electricity in my unit. What are protective measures that I can take to minimize damages while working on this project?

What is the worst case scenario if I screw up ? -- You are dead. Your apartment block has burned down. Your family are all dead. The neighbours are all dead.  MAINS ELECTRICITY IS DEADLY - YOU NEED TO KNOW WHAT YOU ARE DOING WITH IT

What are protective measures that I can take to minimize damages while working on this project? - Get some qualifications in working with mains electricity.

I'm sorry but your response is not helpful at all. I've been going over tutorials and it does not seem that difficult. I kind of wanted some tips and advice on common errors people make and maybe some good precautionary measures from people who have been working with relays for a long time. Please be more specific as to what constitutes as "qualifications with working in mains electricity". I am currently in upper year  for an undergrad program for electrical engineering and I am sure I will be able to follow through or search the web a little more to understand your tips or advice

I am currently in upper year for an undergrad program for electrical engineering - You're way more advanced than 99% of the people that visit here then. Most would succumb to "Darwinism In Action", hence the big warnings I post whenever mains is involved.

@vp1234 you could achieve almost the same results by working with safer power levels, as first attempt. For example by using LEDs.
And you could check if your installation has a residual current circuit breaker. It's not sufficient to mitigate any risk, but it does provide some protection. https://en.wikipedia.org/wiki/Residual-current_device
Depending on its presence or not,you could choose your course of actions.

I prefer to use wireless remote control outlet switches, and connect a 433mHz transmitter to the Arduino. That way I can switch AC appliances on and off, without ever having to touch any of the mains electricity stuff.

Thank you very much for your help everyone :) Really appreciate it

Get a 24VDC desklight :)

Basic safety precautions:

Always fully unplug the lamp before working on any wiring, even when working with the low-voltage side of things.
Invest in a proper enclosure and follow the rules of insulation and earthing: if the enclosure is metal or has exposed metal they have to be earthed. If it is plastic it is insulated and there is nothing to earth (plastic is best).
Use nylon bolts etc when situated near mains voltages.
A proper relay module with good screw terminals is recommended.
Do not tin your mains wires when screwing them into a terminal block
Do your mains wiring with your left hand in your pocket (an old electrician's trick: if you should get a shock the path to earth is down the side of your body and through your foot. If you have your left hand touching something the path to earth could well be straight across your chest, through your heart, and down your other arm, killing you. It has saved my life a few times...)
Keep mains voltages and low-voltage areas separate. Cable ties and self-adhesive nylon cable tie pads are great for keeping cables where they should be.
Shield any exposed mains connections from touch. Things like the underside of the relay module where the terminal blocks are soldered, that sort of thing.
Don't let the relay module wave around loosely. Keep it well secured in the enclosure.

I'm sure I could find more tips if I tried :)
The main thing to remember is that mains electricity is deadly and should be treated with the utmost respect.
For the ultimate in safety though you could get an isolating transformer. This separates your work from the main supply and means that the only way of getting a shock is by actively touching both outputs of the transformer at once - something you're not really likely to do - and even then it's usually a very localised path for the electricity (through a finger or two).
Adding an ELCB to the lamp's plug (if it is earthed) can be a good precaution while you are working too - and making sure the socket is connected to a ring main that is protected by an RCD is pretty much essential (in the UK it is the law that all ring mains are protected by an RCD - I would hope the same is the case where you live).

Thank you very much for your help :) Really appreciate it

Read through the Sparkfun Beefcake Relay Hookup Guide.  It points out many things to keep in mind.
The kit is quite good, I just finished putting one together to control a humidifier off an Arduino with a DHT-11 to keep ambient humidity within a range.
As people have posted, don't ever do any work while the mains are plugged in!
In your project, you'll be able to test the relay without the mains being plugged in, the relay will make a nice "clicking" sound and if you use the "Beefcake" kit, an LED will light up when the relay is "on".
Be sure to have everything in a "housing" and not flopping around. They sell blue plastic junction boxes for about $1 which is what I used.  A GFI or GFCI socket is safer to use, though more expensive.
Good luck!

Thank you very much for your help :) Really appreciate it

this is andrew.
I saw your Question.
Relay's are not even risky Electronic device , it can be controlled by 5v or 12 v.
On behalf, you can just run your simple led blink program to Start up your relay.
Just use the Default (13th) pin for relay input. Run your Code. If your code runs successfully, the relay activates, led in the relay will light up and as well as Your default Led also light up in your arduino Board. After that you can give the output 220v power to control electronic Devices.
if any doubt just ping me.

Working with mains is not risky? Really?

Really, its not Risky. But Be Carefull On Dealing with Current.

But, screw it up well the power (110v-220v) to the relay On Common and Normally Open or Normally Closed Pin.

Be, Sure there is no short Circuit.