text:
Connecting ESP8266 with Arduino Uno - WiFi shield not present
I have an Arduino Uno and ESP8266. I want to connect and control an LED from a web server. I made a connection referring to this:

I uploaded the WifiWebServer code to the Arduino, and applied my router's credentials.
char ssid[] = "Router SSID";      // your network SSID (name)
char pass[] = "Router's WPA Password"; `

I'm getting a "Wifi Shield not present" message from the Serial Monitor. I even tried giving external 3.3v power supply to my ESP8266 module, but no change. What am I missing here? Can someone help me fix this issue?

The WifWebServer isn't compatible with the ESP8266, look up example code for the ESP8266 in stead.

Yes, I looked up ESP8266 samples, sounds like we need to have FTDI to load WifiWebServer into ESP... Is there any other way to load Wifiserver into esp directly without FTDI?

Actually  I made a mistake assuming esp8266 itself can act as a Wifi-Shield when it is connected with Arduino Uno, But it won't. So we can't use any Wifi shield examples for Arduino with esp8266

From your diagram, you appear to be using an ESP8266-01?
Another ESP8266 AT command library that may be of interest/use.
Note that the AT command libraries are very dependent on the version of the firmware that you have on the device.  Depending on when/where you bought the device, this firmware will vary significantly.  I've not had any of the libraries work correctly with current versions of the firmware.
Run the AT+GMR at command (using your serial terminal) to determine the firmware version.  If you're on Windows/PC updating the firmware to a previous version (the 0.9.x.x range seems to be the most stable according to my research) is relatively straightforward.  If you're on Mac, it's not as straightforward...
Official/current release of the firmware is available from Espressif's Github repo.
There are plenty of directions on the net for getting firmware onto the ESP8266 for both Mac and Windows/PC.  YMMV as to their accuracy/ease of use.
Note that different versions of the firmware default to different baud rates.  Some default to 115200, others to 9600.  If you decide to use SoftwareSerial (rather than Serial, which your diagram suggests is what you're currently using) you'll need it to run on 9600.  I've not personally tested what Serial supports up to (but my understanding is that you can run up to 115200). Note that there are different commands for setting the ESP8266 AT command firmware baud rate depending on the firmware version/supplier.  The official SDK uses the AT+IPR=9600 command.  This stores the baud rate to the device (i.e. you don't need to send it every time, just once and it's then persistent).
If you haven't already, I'd recommend you get the system working with a simple serial terminal program (CoolTerm, for example) before getting into Arduino-land.
Note that the ESP8266 does not reliably run from the 3v3 power rail on the Arduino. The ESP8266 requires up to 300mA, the Arduino is capability of around 50mA to my understanding.  Symptoms of insufficient power include random resetting of the device.  Best to run a separate 3v3 source to the ESP, or if you have a strong enough 5v supply, use a step-down converter.  Your diagram indicates you're using a standard Arduino, which runs 5v out of the serial pins (or digital outs), but your comments indicate you're running 3v3 (which means you're probably running a 3v3 Pro Mini or similar)?  If you're not running a 3v3 device, you'll definitely need to run a 5v-3v3 logic level converter (I can't link to examples due to not having enough reputation points—but these are relatively easy to get from SparkFun or similar.  I picked up a combined step-down converter with logic level converter which does both tasks.
Lastly, If you don't need the ADC from the Arduino device for your application (which it sounds like you don't given your project description) I'd strongly recommend you reconsider the advice from gmag11 and yeti re: running Arduino on the ESP8266.  It is much more stable, and the extra SRAM will make a big difference with processing/building HTTP request strings etc.  I wasted a lot of time (unsuccessfully) trying to get AT commands working before switching to Arduino on the ESP8266, which has been a breeze by comparison.

You can program and upload code to ESP8266 using Arduino programming environment, reusing code and libraries with small changes. Check https://github.com/esp8266/Arduino for more information.
For most tasks ESP8266 may substitute Arduino board completely. It has more flash, more RAM and integrated WiFi, and is faster (80MHz).

The WiFiWebServer tutorial describes how to use the ArduinoWiFiShield. This shield is based on different WiFi hardware than the ESP8266 modules.
You need a WiFi library driving the ESP8266 modules instead, e.g WeeESP8266.
Your favourite internet finding machine sure will find lots of similar libraries.
A different approach would be ArduinESP (https://github.com/esp8266/Arduino), which means to develop code to run on the ESP8266 module directly.

...aaaand please rethink your wiring. The ESP8266 modules are a pure 3.3V pets and your wiring connects a 5V logic signal directly to the ESP8266 and this may send your ESP8266 into the digital heaven with or without waving goodbye using blue smoke...

Have ESP8266 library in my arduino & connected with 3.3V only, I don't want to directly upload firmware into ESP8266, but via Arduino Uno. and Wifi Shield is different from ESP8266 module. I use esp8266 only

ArangaNathan has posted another Fritzing diagram with the same errors as the opening diagram:

You can't drive the ESP8266 from the Arduino 3.3V pin as it can only supply 50mA but the ESP requires > 200mA to transmit properly.
All I/O wires between Arduino and ESP must be level shifted from 5V to 3.3V otherwise you will damage the ESP. It may not happen straight away, but it will happen.
If you wire Arduino Tx <-> ESP Tx and Arduino RX <-> ESP Rx you must remove the Arduino MCU chip completely before powering on, and use the Arduino IDE monitor to send commands to the ESP.
If you don't remove the MCU then you have to wire Arduino TX->RX and Arduino Rx<-TX.
If also you want to use the Arduino IDE in this mode (MCU installed) then you can't wire ESP TX/RX to D0/D1 and must use other pins instead (e.g. D2/D3) and SoftSerial to create another serial UART port.

Fritzing's wiring diagram has errors. 1) the serial connections wrong way around. You need to swap them so that
Arduino TX -> ESP Rx and
Arduino RX <- ESP Tx. Also 2) the ESP-01 require more than 200mA so supplying voltage reg cannot be provided from the Arduino 5V pin. It must be supplied by VIN with a supply able to provide 1A.

For the esp you must use an external 3.3v power source (300 mA or more), and a logic level converter for the esp Rx (arduino Tx is in 5v logic).

Here is how to send commands to an ESP8266, without using an FTDI Programmer (NOTE: the IC used is LM117 (5V to 3.3v) IC for level shifting.)

Wait, it does not shift anything else than 5V to 3.3V. You have to shift other pins too.


text:
LCD does not work with if condition
#include <LiquidCrystal.h>
#include <Wire.h>

LiquidCrystal lcd(2, 3, 4, 5, 11, 12);// initialize the library with the numbers of the interface pins

int pirPin = 7; //Variable that will receive the digital signal from the sensor
int LEDgreen = 6; //LED addressed to the digital pin 6
int speaker = 8; //speaker addressed to the digital pin 7
int buttonPin = 9; // the pin that the pushbutton is attached to

void setup(){
  pinMode(buttonPin, INPUT);// Initialize the button pin as an input:
  pinMode(pirPin, INPUT);  // declares variable pirPin as an input
  pinMode(LEDgreen, OUTPUT); // declares variable LEDgreen as an output
  pinMode(speaker, OUTPUT); // declares variable speaker as an output
  lcd.begin(16, 2);
  // turn on the cursor:
  lcd.cursor();
  Serial.begin(9600);
}

void loop(){
  int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
  int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal
  if(buttonState == LOW){
    if(digitalRead(pirPin) == LOW){
      /*The LED Blinks once with the command digitalWrite
      the LED keeps turned on after blink during the motion cycle*/
      digitalWrite(LEDgreen, HIGH);
      delay(1000);
      digitalWrite(LEDgreen, LOW);
      delay(500);
      digitalWrite(LEDgreen, HIGH);
      /*speaker plays frequency, the number 7 is the digital pin,
      the second number is the frequency played and the third number is the sound duration
      we repeated this command with different frequency and varying the time in order to create a
      pleasant sound */
      tone(4,261,300);
      delay(200);
      tone(4,329,300);
      delay(200);
      tone(4,392,600);
      delay(200);
      tone(4,329,300);
      delay(200);
      tone(4,392,300);
      delay(200);
      tone(4,493,600);
      delay(200);
      tone(4,392,300);
      delay(200);
      tone(4,493,300);
      delay(200);
      tone(4,294,600);
      delay(200);
      lcd.setCursor(0,0);
      lcd.print("  Motion  ");  // Print a message to the LCD.
      lcd.setCursor(0,1);
      lcd.print(" Detected ");
    } else if(digitalRead(pirPin) ==  HIGH) {
       digitalWrite(LEDgreen, LOW); // Turn off the LED in the case where no motion is detected
       lcd.setCursor(0,0);
       lcd.print("No Motion  ");
       lcd.setCursor(0,1);
       lcd.print(" Detected ");
     }
   } else if(buttonState == HIGH) {
     if(digitalRead(pirPin) == LOW) {
       digitalWrite(LEDgreen, HIGH);
       delay(1000);
       digitalWrite(LEDgreen, LOW);
       delay(500);
       digitalWrite(LEDgreen, HIGH);
       tone(4,261,300);
       delay(200);
       tone(4,329,300);
       delay(200);
       tone(4,392,600);
       delay(200);
       tone(4,329,300);
       delay(200);
       tone(4,392,300);
       delay(200);
       tone(4,493,600);
       delay(200);
       tone(4,392,300);
       lcd.setCursor(0,0);
       lcd.print("  Motion  ");
       lcd.setCursor(0,1);
       lcd.print(" Detected & door ");
     } else if(digitalRead(pirPin) ==  HIGH) {
       digitalWrite(LEDgreen, LOW);
       // Turn off the LED in the case where no motion is detected
       tone(4,329,300);
       delay(200);
       tone(4,392,300);
       delay(200);
       tone(4,493,600);
       delay(200);
       tone(4,392,300);
       lcd.setCursor(0,0);
       lcd.print("No Motion  ");
       lcd.setCursor(0,1);
       lcd.print(" Detected but door ");
     }
   }
   delay(2000); // wait for 1 seconds before compare again
 }

I think you forgot to ask a question there...

This is a summary of your basic loop logic:
void loop() {
  int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
  int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal
  if (buttonState == LOW) {
    if (digitalRead(pirPin) == LOW) {
        // buttonState is LOW
        // pirPin is recently read as LOW
        // ... Motion Detected ...
    }
    else if (digitalRead(pirPin) ==  HIGH) {
        // buttonState is LOW
        // pirPin is recently read as HIGH
        // ... No Motion Detected ...
    }
  }
  else if (buttonState == HIGH) {
    if (digitalRead(pirPin) == LOW) {
        // buttonState is HIGH
        // pirPin is recently read as LOW
        // ... Motion Detected & Door ...
    }
    else if (digitalRead(pirPin) ==  HIGH) {
        // buttonState is HIGH
        // pirPin is recently read as HIGH
        // ... No Motion Detected but Door ...
    }
  }
  delay(2000); // wait for 1 seconds before compare again
}

However, this is bad code:
if (digitalRead(pirPin) == LOW) {
    // ... Motion Detected ...
}
else if (digitalRead(pirPin) ==  HIGH) {
    // ... No Motion Detected ...
}

because each time the digitalRead(..) function is called, it can give a different value. So even though your intention is clear, this code won't work the way you expect. Consider what happens if the first digitalRead(pirPin) is high, so digitalRead(pirPin)==LOW is false, but then the second digitalRead(pirPin) is low, so digitalRead(pirPin)==HIGH is also false. Then neither block of code runs. Instead, use:
if (digitalRead(pirPin) == LOW) {
    // ... Motion Detected ...
}
else {
    // ... No Motion Detected ...
}

Or since you already sampled it at the start of the loop with int pirVal = digitalRead(pirPin);, simplify the logic as:
void loop() {
  int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
  int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal

  if (buttonState == LOW) {
    if (pirVal == LOW) {
        // buttonState is LOW
        // pirPin is LOW
        // ... Motion Detected ...
    }
    else {
        // buttonState is LOW
        // pirPin is HIGH
        // ... No Motion Detected ...
    }
  }
  else {
    // buttonState is HIGH
    if (pirVal == LOW) {
        // buttonState is HIGH
        // pirPin is LOW
        // ... Motion Detected & Door ...
    }
    else {
        // buttonState is HIGH
        // pirPin is HIGH
        // ... No Motion Detected but Door ...
    }
  }
  delay(2000); // wait for 1 seconds before compare again
}

By the way, if you're using the Arduino IDE, you can easily clean up the indentation to make these control structures easier to see, by using Tools | Auto Format.

hi thanks MarkU the problem is that my lcd does not work maybe it is the setup or the loop i do not know

In future, it would be useful to write a trivial program to confirm that your hardware works before moving on to driving it with new software that might itself not work. A simple "Hello, World!" program to write on the display would tell you very quickly whether you have a hardware or a software error.

The standard "hello world" example for LCD display is in the Arduino IDE under File | Examples | LiquidCrystal | HelloWorld. Note that your example code uses a different pinout, LiquidCrystal lcd(2, 3, 4, 5, 11, 12) instead of the normal configuration LiquidCrystal lcd(12, 11, 5, 4, 3, 2). Is it possible that your LCD connections are not what you intended?

hi thanks a lot MarkU it is a software error it was the configuration LiquidCrystal lcd it is working now :)

The code LiquidCrystal lcd(12, 11, 5, 4, 3, 2); defines which arduino pins are connected to the LCD hardware -- RS=12, Enable=11, D4=5, D5=4, D6=3, D7=2; with R/W grounded. Connect your LCD exactly this way and run the HelloWorld example, to verify that your LCD hardware is working. Once you get that working, then fix your code to use the same configuration lcd(12, 11, 5, 4, 3, 2) instead of what you had before, lcd(2, 3, 4, 5, 11, 12). You've got the same pins but in a different order, and I assume your LCD is connected with the normal connections.

source: Stack Exchange

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

sort: votes


text:
STM32 Bluepill with Arduino IDE can not blink LEDs with a few pins
There are a couple pins such as PB4, PA15, and the ones near it where it won't allow me to blink LEDs with. They are stuck at a constant voltage, one that is around 1.5V, which is lower than minimum output. This happened on both STMs. The issue is more apparent when trying to blink LEDs inside of a big program. I don't know why this is.

what is your question? ... also, we have no way to guess what code you are running

Maybe it's not genuine STM or at least those which passed quality testing. I've got one of those and whole RTC isn't working properly. On the other side genuine nucleo boards are working like charm.

@jsotola As specified, I am just running the typical LED blink program within the Arduino IDE. My question is why this is occurring.

@KIIV How do you identify a non-genuine STM? I purchased these from AliExpress, but many people do and still use them normally. Everything works with the STM32, but making an LED blink on some pins, specifically with other loads on it, does not work. It contains a steady voltage and no alternation.

@MahmoudMaarouf I'd guess strange behaviour would be the first sign. But, maybe you've just burned those pins by some heavy load. It's capable to drive few milliamps and some pins are weaker than others. I'd check this program on the other boards first.

@KIIV Thank you for the help KIIV. However, it's similar to another STM board I own. So I believe the board is fine. Initially I thought it was because the pins weren't PWM. But I later learned that it doesn't matter.

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


text:
Why does the reading on the ESP32 read max, when the reading on UNO read accurately?
I have a 'Capacitive Soil Moisture Sensor' hooked up to my Uno.
Very simple code. AnalogRead(MoistureSensorPin);
This will return a differing value that I can work with.
When applying the same code to an ESP32 with a similar set-up. It always returns '4095' which I understand is the maximum value an analog input can return. But I cannot understand why it does this.
Any help will be much appreciated.

Thanks friend, this response also helped me a lot

The ESP is a 3.3v device. If your Uno is a 5v device, its A/D converter can measure and report voltages from 0 to 4.9878v (5v minus 1 LSB). If the same signal is presented to the ESP, any value above 3.29919 volts (3.3v - 1 LSB) will read as 4095, i.e., out of range.
(If this isn't your issue, adding wiring diagrams of each system to your question will help us understand it better.)
Update:

Perhaps a different ESP unit would be the ideal solution?

As far as I know, all of the ESP's are 3.3v devices. So the solutions I see are:

Power your sensor with 3.3v (is this an option?) so its output will be within the input range of the ESP's built-in A/D.
Scale the sensor output from it's 0-5v range to the 0-3.3v range the ESP can accept. Whether you can use a simple divider network or would need an op-amp may depend on the sensor, but if, as I suspect, it is a simple resistance device, a voltage divider should work.
Use an external 5v A/D converter. This will require a 5v power supply (which I presume you are using already, to power the sensor) and voltage level conversion between the A/D and input pin(s) of the ESP. The conversion could be a purchased level-converter board or a simple resistor-divider network.

Thank you for the response!
I believe this is the issue I am facing, so it's an A/D converter issue on the ESP device...
Perhaps a different ESP unit would be the ideal solution? (ESP82?)
Or, do you know of a different solution for me to be able to get a different result from my ESP32?
Much appreciated.

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


text:
How much time passes between waking up and sleeping?
I use the watchdog timer to make Arduino sleep for 8 seconds and then wake it right after and make it sleep again if it didn't complete the loop for 450 times. I made it so that it will only do its job every 1 hour with a for loop. How much time does the Arduino keep awake until it sleeps again? I think it wouldn't be worth to put power consumption of this to calculation but still need to verify.

you said 8 seconds every hour ... what are you asking?

I mean right after 8 seconds of sleeping it wakes up and sleeps again if it didn't complete loop for 450 times.

That time totally depends on what exactly you're doing when waking up. If you have a delay(10000); in there, it will be more awake than sleeping. How does it check that the loop didn't complete for 450 times?

I tend use 1ms to wake up and go back to sleep in my calculations.

it keeps awake the length of the timeout every hour .... your question still makes no sense ... you are describing a fixed timeout ... within that timeout you count the number of iterations ... you said nothing about what happens it 450 iterations are reached

@jsotola I am asking the delay of sleeping. It must wake up after 8 seconds because of watchdog's limit. After waking up, it will go right into another sleep for 8 seconds. How many seconds or milliseconds pass between not sleeping state and sleeping state is what I ask about.

why is this description different from your posted question? ... are you certain that this is your real question? ... please edit your question above .... anyway, add code that lights up an LED at wakeup time and turns off at sleep time ... run the code ... record a video of the LED .... measure the time of 100 LED cycles ... that equals to 800 seconds of sleep plus the "on time"


text:
i can't work toggle for my small project

i build my small project from a few component as this photo
after finish code and project . i work run for Proteus and then the project not run perfectly because my code need toggle for data entered . i cant work toggle for data .i want help .please
this my code arduino
#define CLK 10
#define CLKI 9
#define LD 8
#define SO 11
#define SER 12

byte ledstates;
byte copy=0;
int rec=0;
unsigned long bt_leds_timestamp=0;
byte bt_leds_activated=0;

void setup(){
Serial.begin(9600);
pinMode(CLK,OUTPUT);
pinMode(CLKI,OUTPUT);
pinMode(LD,OUTPUT);
pinMode(SO,INPUT);
pinMode(SER,OUTPUT);
}

void loop(){
if (Serial.available()>0){
message();
}
if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){
ledstates &= ~bt_leds_activated;
shift_out(ledstates);
bt_leds_activated = 0;
}
shift_In();
shift_out(ledstates);
}

void message(){
if(Serial.available()){      // Send data only when you receive data:
char data = Serial.read();        //Read   the incoming data & store into data
Serial.print(data);          //Print Value inside data in Serial monitor

switch (data){
  case 'A' :
    bt_leds_activated |= 1;
    break;
  case 'B' :
    bt_leds_activated |= 2;
    break;
  case 'C' :
    bt_leds_activated |= 4;
    break;
  case 'D' :
    bt_leds_activated |= 8;
    break;
  case 'E' :
    bt_leds_activated |= 16;
    break;
  case 'F' :
    bt_leds_activated |= 32 ;
    break;
  case 'G' :
    bt_leds_activated |= 64;
    break;
  case 'H' :
    bt_leds_activated |= 128;
    break;
  default   : return; }
  }
  ledstates |= bt_leds_activated;
  shift_out(ledstates);
  bt_leds_timestamp = millis();

  }

  void shift_out (byte copy){
  digitalWrite(LD, LOW);
  shiftOut(SER,CLK,MSBFIRST,copy);
  digitalWrite(LD, HIGH);
  delay(100);
  }

  void shift_In(){
  digitalWrite(CLKI,HIGH);
  digitalWrite(LD,HIGH);
  digitalWrite(LD,LOW);
  digitalWrite(LD,HIGH);
  digitalWrite(CLK,HIGH);
  digitalWrite(CLKI,LOW);
  byte buttonstates = shiftIn(SO,CLK,MSBFIRST); //read button states in a local variable
  digitalWrite(CLKI,HIGH);
  for(int i=0;i<8;i++){ // loop through all 8 bits of the buttonstates
    if(!(copy & (1<<i)) && (buttonstates & (1<<i))){ // check if old button state (in copy) is zero and new buttonstate is 1 (for the currently check bit)
        ledstates ^= 1<<i; // toggle the corresponding bit in the ledstates variable (will be shifted out later in the loop() function)
    }
  }
  copy = buttonstates;
  delay(10); // delay for debouncing
   }

what does toggle mean?

For ex when run this code and then press first button the led not save state high . But the led state high and then low quickly . I want save state led when press click

@jsotola did you understand me

i understand that you are using a shift register for input and a shift register for an output .... you expect to read the state of a switch and affect the state of a corresponding LED .... you want to be able to press a switch, have an LED light up, and release the switch and have the LED stay lit

@jsotola Yes, it is true that you started to understand what I want. Don't forget to that I used Bluetooth as you see in the picture to do the same button work

you need to realize that reading the state of a switch and receiving data over bluetooth is totally separate from lighting the LED ... you are trying to combine the input and output functions into one and it does not work because the light follows the state of the switch .... you need to separate the switch/bluetooth and the LED lighting into two separate functions with a message going between .... continued

think of two rooms ... in first room, a person answers the phone and also checks the position of 8 levers ... there is also a tray with 8 compartments ... the person looks at each lever, and if it is raised, then he/she puts a black marble into the corresponding compartment in the tray ... the person also checks for messages on the phone ... the messages are a single letter ... he/she puts a black marble into one of the compartments in the tray depending on the message ... then the person passes the tray to the other room ....

the person in the other room looks at each compartment in the tray and turns on one of 8 lights if the compartment contains marbles

the first room could be 20 rooms, each one adding marbles to the tray

now, to expand the scenario ... the person that watches the levers could be instructed to empty the compartment in the tray if the lever is down ... that would make the light follow the position of the lever ... or the person could be instructed to watch the levers and act only when the lever moves ... put marble into compartment if it is empty and remove marble from compartment if it contains one ..... i think that this last scenario is what you want

Currently you are shifting in the button states and directly shifting them out again to the LEDs. Thus the state of the LEDs follows exactly the state of the buttons.
As jsotola explained in the comments, you need to seperate what you get as input (buttons and serial) from what you set as output. For this you need 1 or more variables to hold the state of the LEDs (your output) and the state of each input (for example each button). The last is what you have in the copy variable. It resembles the state of the buttons input. Now create a new variable byte ledstates;. The shift_out() function has to be called with this variable instead of with copy.
Now that input and output are seperated, you can look at the desired behavior for the input. As 1 button press (pressing and releasing) should toggle the state of the corresponding LED, you have to look for a LOW-to-HIGH transition. A common way is to save the current state of the buttons in a variable. Then, in the next execution of shift_in() you can check, if the previous state (as saved in the variable) and the new measured state do a LOW-to-HIGH transition (previously LOW, now HIGH). This is a button press, that you can use to toggle the corresponding LED bit in the newly created ledstates variable. Save the new measured state in the copy variable. (Btw: You should rename the copy variable to something more describing)
Also you need to consider a mechanism, that you haven't had to bother with the previous code: Button bouncing. A mechanical switch or button will not make one single clean transition, when being pressed. The mechanical contact will bounce a bit, resulting in very fast HIGH-LOW transitions, until the button is settled. If you don't consider that in your program, you will get many transitions and thus toggling the LED many times with only one button press. There are many ways to tackle this (and all of them can be easily googled). I would go with the "don't sense any further transitions after the first for a fixed time" way. This can be done by a simple delay() call at the end of your shift_in() function (not so elegant with some caveats) or by using millis() to create a non-blocking timeout (in the best case for each button individually) (Look at the BlinkWithoutDelay example, that comes with the Arduino IDE. It is worth learning this principle).
So you have something like this (not the full code, just some hints):
byte copy;
byte ledstates;

void loop(){
    if (Serial.available()>0){
        message();
    }
    shift_In();
    shift_out(ledstates);
}

void shift_in(){
    digitalWrite(CLKI,HIGH);
    digitalWrite(LD,HIGH);
    digitalWrite(LD,LOW);
    digitalWrite(LD,HIGH);
    digitalWrite(CLK,HIGH);
    digitalWrite(CLKI,LOW);
    byte buttonstates = shiftIn(SO,CLK,MSBFIRST); //read button states in a local variable
    digitalWrite(CLKI,HIGH);
    for(int i=0;i<8;i++){ // loop through all 8 bits of the buttonstates
        if(!(copy & (1<<i)) && (buttonstates & (1<<i))){ // check if old button state (in copy) is zero and new buttonstate is 1 (for the currently check bit)
            ledstates ^= 1<<i; // toggle the corresponding bit in the ledstates variable (will be shifted out later in the loop() function)
        }
    }
    copy = buttonstates;
    delay(10); // delay for debouncing
}

As mentioned above we have seperated input and output. Now it is easy to also implement a fitting bluetooth control. You want the corresponding light go on on serial input (through bluetooth) and go out after a specific time automatically. For such a thing using millis() with a timestamp is the best option. First we take the message() function. We define 2 variables at the global scope (outside of any function at the start of the program) to hold the timestamp of our last serial communication and a byte to hold the LEDs, that where activated via serial. In the message() function we now set the corresponding bit in this last variable. If the serial data was not valid, we simply return from the function (this makes the code shorter). At the end of the function we ensure, that every LED that was set in our variable gets also set in our ledstates variable, which then will be shifted out. And lastly we save a timestamp with the millis() function, which returns the number of milliseconds since the startup.
unsigned long bt_leds_timestamp=0;
byte bt_leds_activated=0;

void message(){
  if(Serial.available()){      // Send data                   only when you receive data:
    char data = Serial.read();        //Read   the incoming data & store into data
    Serial.print(data);          //Print Value inside data in Serial monitor

    switch (data){
      case 'A' :
        bt_leds_activated |= 1;
        break;
      case 'B' :
        bt_leds_activated |= 2;
        break;
      case 'C' :
        bt_leds_activated |= 4;
        break;
      case 'D' :
        bt_leds_activated |= 8;
        break;
      case 'E' :
        bt_leds_activated |= 16;
        break;
      case 'F' :
        bt_leds_activated |= 32 ;
        break;
      case 'G' :
        bt_leds_activated |= 64;
        break;
      case 'H' :
        bt_leds_activated |= 128;
        break;
      default   : return; }
  }
  ledstates |= bt_leds_activated;
  shift_out(ledstates);
  bt_leds_timestamp = millis();
}

Now the corresponding LEDs get turned on, but not off. So we need to put the following code in the main loop() function:
if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){
  ledstates &= ~bt_leds_activated;
  shift_out(ledstates);
  bt_leds_activated = 0;
}

This code checks, if any LED was activated via bluetooth (the first part of the if condition evaluates to true, if bt_leds_activated is different than zero) and if a certain time (here 2s aka 2000ms) has passed since the timestamp was taken. When the time has come, then the LED bits from bt_leds_activated, which we set earlierare cleared inledstatesto turn the LEDs off. Then this is shifted out to set the actual state of the LEDs for us to see. Finally we resetbt_leds_activated` to zero, since we don't have any more LEDs to turn of automatically, until new data arrives.
This has 1 caveat: When you send new data over bluetooth within these 2s, the timeout for the LEDs previously activated via bluetooth will also be resetted, so that they will light longer. The way around that is to use 1 timestamp for each LED, but I thought this as to complicated for now. Don't want this, you can implement that part yourself just like I did with all of them together.
Note: I haven't tested this code in any way.

Comments are not for extended discussion; this conversation has been moved to chat.

firstly : now done edit my code in this question in the top page . after run the new code by Bluetooth when send A the LEDs get turned on, but not off. after send A what is the mean (main loop())?? i but in (if condition) in the [void loop () ]as in top code in this if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){ ledstates &= bt_leds_activated; shift_out(ledstates); bt_leds_activated = 0; }

Please use the chat for further communication. All the comments clutter up the comment space

@chrisl when use millis() function im main loop the leds turn on just 2 sec and then turn off not perfect ansewr

@KhalidAbu-Khadija What are you talking about? I don't understand. Please rephrase your comment


text:
How to edit code from Node-Red to Cayenne
I am working on a project to run some (relays or LED's) on an inputs (Pins) Arduino by esp8266-01s . now while searching on internet I found a video divided it two step that talks about the issue using a ESP8266-01. The important thing in the topic is that the person uses two codes for project :
1) The first code for esp8266.
2) The second code for arduino uno.
The most important part of the topic I want to modify the code for esp8266 . but the owner of the video uses node red website and I want to use the cayenne website . I want to specify basic commands to modify in order to work on cayenne website .
I play with esp and arduino in order to project offline.
First video , Second video
// Code to upload onto ESP8266
 #include <PubSubClient.h>
 #include <ESP8266WiFi.h>

 //EDIT THESE LINES TO MATCH YOUR SETUP
 #define MQTT_SERVER "192.168.1.117"  ///YourMQTTBroker'sIP
 const char* ssid = "Weems_2GHz";
 const char* password = "1029384756";

 char* Topic = "inTopic"; //subscribe to topic to be notified about

 WiFiClient wifiClient;

 void setup() {
 //initialize the light as an output and set to LOW (off)

 //start the serial line for debugging
 Serial.begin(9600);
 delay(100);

//start wifi subsystem
WiFi.begin(ssid, password);
//attempt to connect to the WIFI network and then connect to the MQTT server
reconnect();

//wait a bit before starting the main loop
  delay(2000);
}

PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void loop(){

//reconnect if connection is lost
if (!client.connected() && WiFi.status() == 3) {reconnect();}

//maintain MQTT connection
client.loop();

//MUST delay to allow ESP8266 WIFI functions to run
delay(20);

}

void callback(char* topic, byte* payload, unsigned int length) {

//convert topic to string to make it easier to work with
String topicStr = topic;

//Print out some debugging info
////Serial.println("Callback update.");
//Serial.print("Topic: ");
//Serial.println(topicStr);

//turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
if (payload[0] == '0'){
Serial.print("0");
respond();}
if(payload[0] == '1'){
Serial.print("1");
respond();}
if (payload[0] == '2'){
Serial.print("2");
respond();}
if(payload[0] == '3'){
Serial.print("3");
respond();}
if (payload[0] == '4'){
Serial.print("4");
respond();}
if(payload[0] == '5'){
Serial.print("5");
respond();}
if (payload[0] == '6'){
Serial.print("6");
respond();}
if(payload[0] == '7'){
Serial.print("7");
respond();
}

}
void respond(){
delay(5);
if (Serial.available()) {
//read serial as a character
char ser = Serial.read();
switch (ser) {
  case 'a':
client.publish("outTopic", "Relay 1 is ON");
break;
  case 'b':
client.publish("outTopic", "Relay 1 is OFF");
break;
  case 'c':
client.publish("outTopic", "Relay 2 is ON");
break;
  case 'd':
client.publish("outTopic", "Relay 2 is OFF");
break;
  case 'e':
client.publish("outTopic", "Relay 3 is ON");
break;
  case 'f':
client.publish("outTopic", "Relay 3 is OFF");
break;
  case 'g':
client.publish("outTopic", "Relay 4 is ON");
break;
  case 'h':
client.publish("outTopic", "Relay 4 is OFF");
break;
}//switch
}//if
}//void
void reconnect() {

//attempt to connect to the wifi if connection is lost
if(WiFi.status() != WL_CONNECTED){

while (WiFi.status() != WL_CONNECTED) {
  delay(500);
}
}

//make sure we are connected to WIFI before attemping to reconnect to MQTT
if(WiFi.status() == WL_CONNECTED){
// Loop until we're reconnected to the MQTT server
while (!client.connected()) {
  //Serial.print("Attempting MQTT connection...");

  // Generate client name based on MAC address and last 8 bits of microsecond counter
  String clientName;
  clientName += "esp8266-";
  uint8_t mac[6];
  WiFi.macAddress(mac);
  clientName += macToStr(mac);

  //if connected, subscribe to the topic(s) we want to be notified about
  if (client.connect((char*) clientName.c_str())) {
    Serial.print("\tMTQQ Connected");
    client.subscribe(Topic);
  }

  //otherwise print failed for debugging
  else{Serial.println("\tFailed."); abort();}
  }
  }
  }

  //generate unique name from MAC addr
  String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
  result += String(mac[i], 16);

  if (i < 5){
  result += ':';
  }
  }

  return result;
  }

/* control Relays via serial with numbers*/
/// Upload to Arduino uno
 void setup(){
 Serial.begin(9600);
 //Set all the pins we need to output pins
 pinMode(12, OUTPUT);
 pinMode(11, OUTPUT);
 pinMode(10, OUTPUT);
 pinMode(9, OUTPUT);
 digitalWrite(12, HIGH);
 digitalWrite(11, HIGH);
 digitalWrite(10, HIGH);
 digitalWrite(9, HIGH);
 }

 void loop (){
 if (Serial.available()) {
 //read serial as a character
 char ser = Serial.read();

 //NOTE because the serial is read as "char" and not "int", the read value must be compared to character numbers
 //hence the quotes around the numbers in the case statement
 switch (ser) {
  case '0':
    digitalWrite(12, LOW);
    Serial.print("a");
    break;
  case '1':
    digitalWrite(12, HIGH);
    Serial.print("b");
    break;
  case '2':
    digitalWrite(11, LOW);
    Serial.print("c");
    break;
  case '3':
    digitalWrite(11, HIGH);
    Serial.print("d");
    break;
  case '4':
    digitalWrite(10, LOW);
    Serial.print("e");
    break;
  case '5':
    digitalWrite(10, HIGH);
    Serial.print("f");
    break;
  case '6':
    digitalWrite(9, LOW);
    Serial.print("g");
    break;
  case '7':
    digitalWrite(9, HIGH);
    Serial.print("h");
    break;

   }
  }
 }

sadly, neither "backend" has anything to do with arduino code, so this is off-topic. that said, there's not really much in your code that needs changing to use either one. I do wonder what the nano is for if your running code on the ESP; is it needed?

@dandavis I did not understand anything from what you say. What do you mean by the backend. And what do you mean by being outside the topic?

Just change the MQTT details to those you need for the cayenne website.

@Majenko the edit will do on code for esp yes . And i want specify line important in order to work change this code . Plese edit code or specify line change for code

I suggest you look at some of the example code that should exist for working with cayenne, then compare that with your existing code. And yes, on the esp.

@KhalidAbu-Khadija, I'm not sure, but I think you are missing an MQTT broker (like Mosquito for instance).  I don't think Node-RED is an MQTT broker.  Node-RED can subscribe to MQTT topics, manipulate MQTT payloads and emit MQTT messages.  But I think you still need an MQTT broker.

@st2000, there is an MQTT broker available for Node-RED

...can you point me to the web page where I can learn more @jsotola.  As I thought Node-RED will work with most any MQTT broker.  But, that Node-RED was not an MQTT broker.

...to put it another way.  You don't need Node-RED to send messages from one MQTT client to another MQTT client.  You just need an MQTT broker.  Node-RED can be complex to use and complex to install where as an MQTT broker can be simple to use and to install.

@st2000 Can you help me, brother, in this project, is there any way to contact you?

@st2000,  i say the car is available in red ... you say i thought that i could get any color .... please read my comment again .... here is the link https://flows.nodered.org/node/node-red-contrib-mqtt-broker

Sorry, I don't know anything about Cayenne.  But it sounded like you did not understand the entire workings of MQTT hence my comments above. But if this Node-RED contrib node can emulate an MQTT borker - then maybe you can get by with out using Mosquito.


text:
nRF24L01 : transmission fail when receiver is connected in Serial
I have two Arduino Nano communication with radio.
One is a transmitter and send simple message :
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

//RADIO RF24 PINS
#define RF_CE    7
#define RF_CSN   8

//Radio
RF24 radio(RF_CE,RF_CSN);
const byte address[6] = "00001";

//Communication structure
struct Data {
  long type;
  float value;
} data;

/**************************************************************************/
/*
    Displays some basic information on this sensor from the unified
    sensor API sensor_t type (see Adafruit_Sensor for more information)
*/
/**************************************************************************/

void initRadio() {
  radio.begin();
  radio.setRetries(15, 15);
  radio.setPALevel(RF24_PA_MIN);
  radio.openWritingPipe(address);
}

void setup() {
    Serial.begin(9600);
    // Set delay between sensor readings based on sensor details.
    initRadio();
}

void sendMessage(long type, float value){
  Serial.println("sendMessage");
  data.type = type;
  data.value = value;
  if(radio.write(&data, sizeof(Data))){
    Serial.println("Send SUCCESS");
  }else {
    Serial.println("Send FAIL");
  }
  delay(100);
}

void loop() {
  // Delay between measurements.
    delay(1000);

    sendMessage(0, 20.10);
    sendMessage(1, 45.3);
    sendMessage(2, 1033);

}

The other is a receiver and get the message from the transmitter Arduino and send message with Serial via USB to a computer :
#include <SPI.h>

#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

#include <ArduinoJson.h>

#define RF_CE    7
#define RF_CSN   8

//Radio RF24
RF24 radio(RF_CE,RF_CSN);
const byte address[6] = "00001";

//JSON
const int capacity = JSON_OBJECT_SIZE(8);

//Communication structure
struct Data {
  long type;
  float value;
} data;

long previousMillis = 0;
long interval = 3000;
bool refresh = false;

void sendValue(String source, String type, float value) {
  DynamicJsonDocument doc(capacity);
  doc["type_message"] = "measure";
  doc["source_id"] = source;
  doc["value_type"] = type;
  doc["value"] = value;
  Serial.write(0x11);
  serializeJsonPretty(doc, Serial);
  Serial.write(0x12);
  Serial.println("");
  doc.clear();
}

void initRadio() {
    radio.begin();
    radio.setRetries(15, 15);
    radio.openReadingPipe(0, address);
    radio.setPALevel(RF24_PA_LOW);
    radio.startListening();
}

void readRadio(){
  if(radio.available()){
    while(radio.available()) {
      radio.read(&data, sizeof(data));
      Serial.print("type:");
      Serial.print(data.type);
      Serial.print("value:");
      Serial.println(data.value);
      sendValue("remote", "test_radio", data.value);
    }
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  //Init RF24 Radio
  initRadio();
}

void loop() {
  // put your main code here, to run repeatedly:
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;
    float humidity = 45.60;
    float temperature = 21.30f;
    sendValue("local", "humidity", humidity);
    sendValue("local", "temperature", temperature);
  }
  readRadio();

}

The issue that I have is that when I connect my computer via the Serial port COM to the receiver, every radio message sent by the transmitter fail. But before I connect to the receiver, the messages sent by the transmitter are in success.
I don't know what can cause this issue.

does the RF24L01 use an UART for its serial interface?

@jsotola, it is SPI


text:
USING HX711 ( WITH LOADCELL) WITH PCF8574 IN NODEMCU
I have used hx711 and loadcell with nodemcu (esp8266) in its D1 and D2 pins ( here I have used Logic level shifter and a 5v supply to power hx711).It worked perfectly fine.
Due to the lack of enough pins to accommodate other sensors  in Nodemcu, I'm using PCF8574. I have connected hx711 to pins P0 and P1 of PCF8574.I'm not able to get any output in serial monitor while running like this.
The PCF8574 was connected using resource -
https://www.instructables.com/id/PCF8574-GPIO-Extender-With-Arduino-and-NodeMCU/
The Hx711 was connected using this  code.It is compiling but not getting any output in serial monitor.
#include "Arduino.h"
#include "PCF8574.h"

// Set i2c HEX address
PCF8574 pcf8574(0x20); // A0,A1,A2 all connected to GND
unsigned long timeElapsed;

include <HX711.h>
HX711 scale;

void setup() {
  Serial.begin(9600);
  Serial.println("initializing");
  pcf8574.pinMode(P0,INPUT);
  pcf8574.pinMode(P1,OUTPUT);
  pcf8574.begin();

  Serial.println("initializing");

  scale.begin(P0,P1); //dt , sck
  scale.get_value(5);  // print the avg of 5 readings from ADC minus tare weight
  scale.set_scale(-450.f); // callibration value
  scale.tare();// reset scale to zero
}

void loop() {

  int weight = scale.get_units(3);
  Serial.println(weight);
  delay(1000)

}

Or how about this code without a library? Can I do some changes to it and use pcf8574 ?

#define DT D1
#define SCK D2

long sample=0;
float val=0;
long count=0;

unsigned long readCount(void)
{
  unsigned long Count;
  unsigned char i;
  pinMode(DT, OUTPUT);
  digitalWrite(DT,HIGH);
  digitalWrite(SCK,LOW);
  Count=0;
  pinMode(DT, INPUT);
  while(digitalRead(DT));
  for (i=0;i<24;i++)
  {
    digitalWrite(SCK,HIGH);
    Count=Count<<1;
    digitalWrite(SCK,LOW);
    if(digitalRead(DT))
    Count++;
  }
  digitalWrite(SCK,HIGH);
  Count=Count^0x800000;
  digitalWrite(SCK,LOW);
  return(Count);
}

void setup()
{
  Serial.begin(9600);
  pinMode(SCK, OUTPUT);
  Serial.println("Weight");
  Serial.println(" Measurement ");
  delay(1000);
  calibrate();
}

void loop()
{
  count= readCount();
  int w=(((count-sample)/val)-2*((count-sample)/val));
  Serial.print("weight:");
  Serial.print(w);
  Serial.println("g");

 delay(100);
   // val=0;
   // sample=0;
    w=0;
    count=0;
   // calibrate();

}

void calibrate()
{

  //Serial.println("Calibrating...");
  //Serial.println("Please Wait...");
  for(int i=0;i<100;i++)
  {
    yield();
    count=readCount();
    sample+=count;
   // Serial.println(count);
  }
  sample/=100;
  //Serial.print("Avg:");
  //Serial.println(sample);
  count=0;
  while(count<1000)
  {
    yield();
    count=readCount();
    count=sample-count;
    //Serial.println(count);
  }

  //Serial.println("Please Wait....");
  delay(100);
  for(int i=0;i<100;i++)
  {
    yield();
    count=readCount();
    val+=sample-count;
   //Serial.println(sample-count);
  }
  val=val/100.0;
  val=val/100.0;
  //Serial.println(val);
}

the HX711l ibrary will not magically use the PCF8574 only because you name the pins Px

Thank you for replying. I understand that Hx711 library doesn't know about the PCF8574. I was hoping to tweak the library and work it out. What changes should we make to the library?

PCF8574 takes around 256us to update pins (at standard 100khz i2c). This too high compared to hx711 sck timing constraint which is 50us max. So, it's not possible to communicate with hx711 using PCF8574. wasted two days in finding out this.

Good answer to a not great question.

According to library, hx711 sending pulses to mcu and we are scaling with take this pulses. I think you must connect DOUT and SCK pins directly to the MCU or you must counting pulses via I2C after all create a scaling value according the library code and send it to mcu.

Thank you for answering. I have to use some GPIO expander as I have limitations of pins.  Can you please explain more specifically how it can be done?

I didnt try this method ever but, I checked datasheet and found this code:

Pls check the updated Question.

I didnt try this method but; when i check the data sheet, i found this code on last page:
    sbit ADDO = P1^5;
    sbit ADSK = P0^0;
    unsigned long ReadCount(void){
     unsigned long Count;
     unsigned char i;
     ADDO=1;
     ADSK=0;
     Count=0;
     while(ADDO);
     for (i=0;i<24;i++){
     ADSK=1;
     Count=Count<<1;
     ADSK=0;
     if(ADDO) Count++;
     }
     ADSK=1;
     Count=Count^0x800000;
     ADSK=0;
     return(Count);
}

Here is the pulse counting method i think. So if we are using I2C IC,  we must get pulse datas over it to our MCU and count them. But before this scaling method; we must calibrate loadcells and tare them absolutely.
And i found a link that pointing i2c with hx711. They used sparkfuns IO expander(communicating via I2C) to fix low io problem and connect loadcells to this expander and how read scalings completely.
Here is the link: if you can check, maybe find a solution for your problem.
Sparkfun's I2c Expander with Hx711


text:
Is my BMA421 locked up?
I have been trying to set up the BMA421 motion sensor in a nrf52 based smart watch, using the datasheet for the BMA423, which has the same interface. I had got the sensor working well with the original source code, but I was trying to set it up myself. It is connected via I2C, address 0x18.
I made some mistakes in my original code. I was trying to initialise the chip with a 6Kb byte stream (as in the original source), in chunks of 64 bytes. I didn't resend the register at the start of each data chunk, so ended up writing bytes to random registers.
Unfortunately, I have managed to get the sensor into an unrecoverable state - it now returns 0xFF to all reads, and doesn't respond to a soft-reset code (register 0x7E=0xB6). Even exhausting the watch battery to power cycle the chip doesn't seem to help.
I have found someone with a similar issue on the Borsch Sensortec forum, so I am hoping that a complete battery discharge works.
Does anyone have any other suggestions?

Are you using I2C or SPI? SPI doesn't have addresses, but every slave has a chip select pin. I2C on the other hand has addresses and no chip select pin.

Sorry, have corrected - it is I2C.

Currently my plan of action is discharge the battery and then leave for a week to see if I can reset the chip. Not optimistic.

A suggestion from another source was that I have put the device into SPI mode and disconnected it from the I2C bus - that would certainly explain the result.

good point. From the "drain battery" I guess, that the hardware is mostly integrated, so that you cannot just try connecting SPI and configuring it again over that?

That is sadly correct. This is an off the shelf smartwatch which is not amenable to being opened! Once it has been kicked off the I2C bus, there is no way back until a power cycle. I am asking here, because I have a working Arduino firmware running on it to test out peripherals. The positive is that if I have switched it into SPI mode, I am unlikely to have overwritten the NVRAM!

The BMA421 was not locked. An erroneous write to the wrong register had switched it to the (non-existant) SPI interface. The solution was to power cycle the sensor.


text:
Networking Multiple Arduinos -- Is It "Rocket Science?"
Have a set of Arduinos that need to swap data--for a model rocket launch controller!
How to send 24 bits of info (launch commands) from a "master" Arduino, 12 bits each to two "slave" Arduinos that are 15' to 150' away from the "master.
Each "slave" needs to send 12 bits of info (continuity statii) to the "master."
"Master" <--- 15' to 115' ---> "Slave 1" <--- 10' to 35' --> "Slave 2"
Seems too long for I2C?

This can be improved by getting rid of "TiA..."  I don't know what "RSO Boxes" and "Pad Boxes" are.  I suspect that, if described differently, you'd be drawing answers from a large(r) group of people.  If the question comes down to conveying 16 bits worth of information between two Arduinos at low frequency, over a distance of 100 feet, probably a lot of people here can answer that.

do some research about fireworks fire control systems .... perhaps you should be thinking of using multiple pins for issuing a launch command to one launch platform

This sounds like a job for DMX512...

Hmmm.  Had thought about using DMX cabling.  But yes, if one has to add a sub-PCB, DMX signaling might be as valid yet simpler than 802.{whatever} networking.  Has anyone tied DMX signals to Arduino?

Check this link about DMX512 on Arduino: https://playground.arduino.cc/Learning/DMX/

The best solution would be to use an RS485 adapter connected to each Arduino via serial port. This is a tried and true solution that is perfect for a setup like this and only costs a few bucks of extra hardware per node.
If you can't use additional hardware, you can also create a poor-man's current loop system like RS485 using normal Arduino pins since they are capable of sourcing and sinking 20mA.
With either of these solutions, you can send however much data as you want as long as you have some kind of minimal protocol to serialize it into a sequence of bits on the wire. To send 12 bits, you might just define a start condition as an idle "0" on the wire for a certain period of time, followed by a "1" start bit, followed by you 12 data bits, followed  maybe a parity bit or a checksum, and completed by a "1" stop bit.
Check out how, say RS232 or RS485 serialize bits to get an idea of how this works. If you end up using hardware that only supports sending data in 8 bit chunks, then you could, say, send two bytes per data "packet" where each byte has 6 bits of your data, plus one bit that indicates if ths byte is the first group of 6 bits or the second group, and then one bit of parity for error checking.

I've got I2C to work reliability between Arduinos with different byte sizes. I have copied the test code below. Note that there is separate code for sending and receiving. It may need to be tweaked but contains the basic idea.
One (or more) Arduinos sends to main I2C controller:
Sender Code:
//sender test

#include <Wire.h>

#include <Wire.h>
#define NUMDATA 4

byte byteData[2 * NUMDATA]; //= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

//test

void setup()
{
  Wire.begin(3);                // join i2c bus with address #3
  Wire.onRequest(requestEvent); // register event
}

void loop()
{
int aData;
  for(int i = 0; i < NUMDATA; i++){
    aData = analogRead(i);

    byteData[i*2 + 1] = ((aData >> 8)  & 0xFF);
    byteData[i*2] = (aData & 0xFF);

   // memcpy((void *)byteData[i*2], (void *) analogRead(i), sizeof(int));
  }

}

void requestEvent()
{
  Wire.write(byteData, 2 * NUMDATA);
}

Receiving Code:
#include <Wire.h>

void setup()
{
  Wire.begin();        // join i2c bus (address optional for main controller)
  Serial.begin(9600);  // start Serial for output
}

void loop()
{

  getSenderData();

  Serial.println("Hello");
  delay(500);
}

void getSenderData() {
//Gets sensor data for one grid

    //Byte Array to get raw bytes
    byte ICdataAsBytes[8];
    int i = 0;

    Wire.requestFrom(3,8);    // request 6 bytes from sending device #2

    while(Wire.available())    // sender may send less than requested
        ICdataAsBytes[i++] = Wire.read();

    int *tempData =(int*)&ICdataAsBytes;

    for( i = 0; i < 4; i++)
        Serial.println(tempData[i]);

}

I2C at distances up to 115 ft (≈ 35 m) ? Really ?

Ah I missed this important note, thanks.  Yep, the distance seems way out of spec.


text:
How to Independently run positional and continuous servos using millis()?
I am setting up 3 servos (2 position servos and 1 '360' continuous rotational servo) with Arduino. but I failed to run these independently. It runs one after another. I wish to run it in loop independent to each other. Here is the code which I use to run positional servo and CR (360) servo. default servo positions are 90.
*CR 360 servo should be running independently 90-60-120-90 (in loop)
*Pos servo should be running one after another (in loop)
To run positional servos (tilt/pan):
//tilt servo
    for (pos = 90; pos >= 60; pos -= 1)     //90 ~ 60
  {
    tiltservo.write(pos);
    delay(30);
  }

  for (pos = 60; pos <= 120; pos += 1)      //60 ~ 120
  {
    tiltservo.write(pos);
    delay(30);
  }

  for (pos = 120; pos >= 90; pos -= 1)       //120 ~ 90
  {
    tiltservo.write(pos);
    delay(30);
  }

//pan servo
for (pos = 90; pos >= 60; pos -= 1)          //90 ~ 60
  {
    panservo.write(pos);
    delay(30);
  }

  for (pos = 60; pos <= 120; pos += 1)       //60 ~ 120
  {
    panservo.write(pos);
    delay(30);
  }

  for (pos = 120; pos >= 90; pos -= 1)       //120 ~ 90
  {
    panservo.write(pos);
    delay(30);
  }

To run CR 360 servo:
 legservo.writeMicroseconds(1600);      //CW
 delay(5000);                           //run for 5s
 legservo.writeMicroseconds(1300);      //CCW
 delay(5000);                           //run for 5s

Tried this to independently run CR servos, but how to put some wait (3s-4s) in between FW and RW.
if (millisNow - lastMillis >= 10000)
{
lastMillis = millisNow;
if (crservoState == 0)
 {
   legservo1.writeMicroseconds(2150); //FW
   crservoState = 1;
 }
  else
 {
   legservo1.writeMicroseconds(850);  //RW
   crservoState = 0;
 }
}

Trial code after suggestions:
uint32_t milliSNow = millis();

  if (milliSNow - lastTimeServoRotate >= 1000)
  {
    if (crservoState == 0)
    {
      if (milliSNow - lastTimeServoRotate >= 10000)
      {
        legservo1.writeMicroseconds(2150);    //FW run
        crservoState = 2;
        lastTimeServoRotate = milliSNow;
      }
    }

    if (crservoState == 1)
    {
      if (milliSNow - lastTimeServoRotate >= 10000)
      {
        legservo1.writeMicroseconds(850);     //RW run
        crservoState = 3;
        lastTimeServoRotate = milliSNow;
      }
    }

    if (crservoState == 2)
    {
      if (milliSNow - lastTimeServoRotate >= 3000)
      {
        legservo1.writeMicroseconds(1500);    //FW STOP
        crservoState = 1;
        lastTimeServoRotate = milliSNow;
      }
    }

    if (crservoState == 3)
    {
      if (milliSNow - lastTimeServoRotate >= 3000)
      {
        legservo1.writeMicroseconds(1500);     //RW STOP
        crservoState = 0;
        lastTimeServoRotate = milliSNow;
      }
    }
  }

https://arduino.stackexchange.com/questions/83977/how-to-run-2-different-servo-continuous-rotation-and-regular-servo-in-parallel/83984#83984

@ArduinoFan thanks for sharing the link, I tried this but this is for controlling same type of servos, in my case i need to set up positional servo and CR as well, so its getting mixed operation. while running pan/tilt one after another with continuously running CR servo CW/CCW with wait time of 2s. any help would be appreciated. Thanks.

The last code snippet you posted should work, albeit with 10 second (rather than 3–4 s) pauses between FW and RW. If it doesn't work, you have an issue elsewhere in your code. Maybe you are sharing the lastMillis variable with the code handling the positional servos?

@EdgarBonet Thanks for your comment. This code works to run CR in this manner..

when start, it run after 10s

servo1 run for 10s FW then immediately run for 10s RW in loop. but I wish to hold/wait for 3s after 10s FW and 10s RW run each.

'lastMillis' is only used for CR servo, its not clashing with POS servo variable.

Re “I wish to hold/wait for 3s after 10s FW and 10s RW run each”: This is not in your code snippet. If you want these pauses, you have to explicitly ask the servo to stop, and your cycle has four phases: FW, pause, RW, pause.

@EdgarBonet Thank you. I uploaded it as 'Trial code', Could you please check it?
since its working but the fw/rw run time is 3s instead of 10s and holding time is 10s instead of 3s though i defined it to run for 10s and hold/stop for 3s. where I am mistaking? please suggest~

@EdgarBonet I just flipped (milliSNow - lastTimeServoRotate) check from 10000 to 3000 and it run. (milliSNow - lastTimeServoRotate), this checks the time elapsed time.
But when start, it wait for 10s to run, even I set it to check with >= 1000 (~1s), I didn't get it. Please suggest.

This is covered in the Blink Without Delay Arduino tutorial.
Let me paraphrase the main part of the example code here:
uint8_t ledState = LOW;
uint32_t lastTimeLedChanged = 0;

void loop() {
    uint32_t now = millis();
    if (now - lastTimeLedChanged >= 1000) {

        // Save the last time we updated the LED.
        lastTimeLedChanged = now;

        // Compute the new state of the LED.
        if (ledState == LOW) {
            ledState = HIGH;
        } else {  // ledState is HIGH
            ledState = LOW;
        }

        // Set the LED to the computed state.
        digitalWrite(LED_BUILTIN, ledState);
    }
}

This will make the LED cycle between its two possible states at the
desired rate. You can apply this principle as-is to your continuous
rotation servo.
For the positional servos, the same principle can still be applied, but
there is a catch. Whereas both the LED and the CR servo cycle between
two states, the pair of positional servos goes through many states
(92 240 if I counted correctly). You will thus need:

more variables to store the current state of the servo pair
more code to compute the new desired state
more code to update the state

In order to figure out how to represent the state, you have to look at
your current delay()-based code, see how many calls to delay() are
performed on each full cycle, and figure out how to identify each of
these calls. Each of these delays corresponds to one state of your
system. I would say that you need one variable to know in which of the
for loops you are, and another variable to know the last position you
wrote to the servo in that loop. I will call each of the original for
loops a “phase”. There are two six such phases:

phase 0: tilt: 90° → 60°
phase 1: tilt: 60° → 120°
phase 2: tilt: 120° → 90°
phase 3: pan: 90° → 60°
phase 4: pan: 60° → 120°
phase 5: pan: 120° → 90°

Note there were only two for loops in the original question, but
it was then edited to include six loops, thus I edited my answer.
An then you will need to store the time of the last update, thus:
int phase = 0;  // which of the six phases we are in
int pos = 90;   // last position written to a servo
uint32_t lastTimeServoMoved = 0;

Once you have the proper variables to describe the state, updating it is
not hard. If you have reached the end of a phase, move to the next one.
Then update the position by one step. Thus:
void loop() {
    uint32_t now = millis();
    if (now - lastTimeServoMoved >= 30) {

        // Save the last time we updated a positional servo.
        lastTimeServoMoved = now;

        // Compute the new state.
        if (phase == 0 && pos == 60)
            phase = 1;
        else if (phase == 1 && pos == 120)
            phase = 2;
        else if (phase == 2 && pos == 90)
            phase = 3;
        else if (phase == 3 && pos == 60)
            phase = 4;
        else if (phase == 4 && pos == 120)
            phase = 5;
        else if (phase == 5 && pos == 90)
            phase = 0;
        if (phase == 1 || phase == 4)
            pos += 1;
        else
            pos -= 1;

        // Set the servo to the computed state.
        if (phase < 3)
            tiltservo.write(pos);
        else
            panservo.write(pos);
    }
}

I personally do not like this kind of repetitive code. If you are
comfortable with data structures, I would recommend using an array of
structs to store all the information describing the moves that are done
in each phase:
struct {
    Servo *servo;   // which servo to move
    int step;       // steps by which it moves
    int final_pos;  // final angular position
} moves[] = {
    { &tiltservo, -1, 60 },   // tilt:  90 ->  60
    { &tiltservo, +1, 120 },  // tilt:  60 -> 120
    { &tiltservo, -1, 90 },   // tilt: 120 ->  90
    { &panservo,  -1, 60 },   // pan:   90 ->  60
    { &panservo,  +1, 120 },  // pan:   60 -> 120
    { &panservo,  -1, 90 }    // pan:  120 ->  90
};

Then the actual code becomes simpler:
void loop() {
    uint32_t now = millis();
    if (now - lastTimeServoMoved >= 30) {

        // Save the last time we updated a positional servo.
        lastTimeServoMoved = now;

        // Compute the new state.
        if (pos == moves[phase].final_pos) {
            phase +=1;
            if (phase == 6)
                phase = 0;
        }
        pos += moves[phase].step;

        // Set the servo to the computed state.
        moves[phase].servo->write(pos);
    }
}

thank you so much for your detailed explanation with example. Its good to understand. I tried this but CR servo doesn't wait for 5s between CW and CCW move.
The actual operation should be:
` CR servo:  (in loop)
running CW for 5s,
wait for 2s,
CCW for 5s `
` Pos (pan/tilt) servo:  (in loop)
1st pan move from 90~60, 60~120, 120~90 then
2nd tilt move from 90~60, 60~120, 120~90 `
Please suggest.

@Emlinux: This doesn't seem to match the code in your question. Please, update the question with the relevant information. Try to be as clear as possible, in order to avoid more misunderstandings of your requirements.

sorry for the misunderstanding. I updated it accordingly. Thanks.

Thanks for updating the solution. I understood it. Though I didn't use data structure much, but its good to use it here efficiently. I will prefer to learn and use it like this.
since there is 1 more leg_servo (CR 360) included, I tried to add that in loop with position servos like this. but I am unable to pause that for 2~3 seconds after CW/CCW run for 10s.
if (millisNow - lastMillis >= 10000)  { lastMillis = millisNow;
if (crservoState == 0) { legservo1.writeMicroseconds(2150);
crservoState = 1; } else { legservo1.writeMicroseconds(850);   crservoState = 0; } }

Please suggest some. Thanks.

@Emlinux: Please, try to understand the general approach illustrated by this answer: breaking down the cycle into phases, identifying the individual steps within each phase, figuring out how to encode and update the state... Although the code I show is specific to the tilt and pan servos, the approach is generic and, if you understand it, you can apply it to the CR servo. Do not rush into writing code: do the thinking and analysis first.

yes @Edgar Bonet, I tried the same so I shared few lines of code in my previous post. since I need to run the CR servos independent to POS servos (pan/tilt), I tried to run it independently for 10s FW and 10s RW and it runs but I am not sure how to put some wait_delay (like 3s) between FW and RW. Thanks.

since its not well visible the code mentioned in my previous comments, i put it in the end of the post. please check and guide. Thanks.


text:
Variables displayed incorrectly
I am making a keypad and when I try to save the buttons that were pushed they reset back to zero.
int tmp = 1;
int digit = 1;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int code = 0;

void setup() {
  Serial.begin(9600);
  pinMode(7, INPUT);
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  if (digit > 4) {
    digit = 1;
  }
  for (int i = 2; i <= 7; i++) {
    int tmp = digitalRead(i);
    if (tmp == HIGH) {
      if (digit == 1) {
        int a = i - 1;
      }
      if (digit == 2) {
        int b = i - 1;
      }
      if (digit == 3) {
        int c = i - 1;
      }
      if (digit == 4) {
        int d = i - 1;
        Serial.print(a);
        Serial.print(b);
        Serial.print(c);
        Serial.print(d);
        digitalWrite(8, HIGH);
      }
      digitalWrite(9, HIGH);
      delay(100);
      digitalWrite(9, LOW);
      delay(100);
      Serial.print(i);
      digit++;
    }
  }
}

There is a library for a keypad: https://github.com/Chris--A/Keypad If you want to make your own code, you have to specify what you want: should multiple keys presses at the same time being detected ? should there be debouncing ? do you want to know how long a key is pressed ?

I already have key detection but for some reason when I have it output variables A B C and D it only stores the last digit and the rest are 0

@NathanAnderson - The compiler would be warning you about the issue, but warnings are turned off in the Arduino IDE by default.

You can make your code more flexible by keeping a running total (int total = 0;) and just add to it with each keypress: total = (total * 10) + i; - where i is the most recent digit input by the user.

Do you know what int a; does?
For example you have a global variable a and then you have local a. Local one hides global one.
In all cases you're changing local variables. Then you're printing global a,b,c and local d.

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


text:
Problems stopping an if loop, and starting it as well
I want my code to run my motor for a specific amount of time at a specific speed and then stop and not do anything else. I'm having trouble here, I think with my switch and the if loops running on repeat. What is a good way for me to stop the code from looping? And any helpful hints on my switches will be appreciated as well? Thanks and I hope you had a wonderful thanksgiving if you're American. If you're not, I hope you just had a great day in general.
#include <Servo.h>
#include <Adafruit_MotorShield.h>
#include <Wire.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
Adafruit_DCMotor *DC4 = AFMS.getMotor(4);

Servo Servo1;

void setup() {
  digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
  AFMS.begin(); //Initializes the motorshield board
  int motorPin1 = 1;
  int motorPin2 = 2;
  int motorPin3 = 3;
  int motorPin4 = 4;
  pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
  digitalWrite(A0, HIGH);
  pinMode(A1, INPUT);
  digitalWrite(A1, HIGH);
  pinMode(A1, INPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  Servo1.attach(9);
}

void loop()  {
  int MAXampDrawTime = 1000;
  int MAXampDrawSpeed = 20;
  int NORMampDrawTime = 1500;
  int NORMampDrawSpeed = 10;
  int DrawTime = MAXampDrawTime + NORMampDrawTime;
  int ServoTime = 450;
  int previousMillis = 0;
  int inPin0 = LOW;
  int inPin1 = LOW;
  inPin0 = digitalRead(A0);
  inPin1 = digitalRead(A1);
  unsigned long time_zero = millis();
  unsigned long current_time = millis();

  if (inPin0 == HIGH) {
    time_zero = millis();
    current_time = millis();
    while (millis() - time_zero < MAXampDrawTime); {
      dcMoveConst(MAXampDrawSpeed, 1);
      dcMoveConst(MAXampDrawSpeed, 2);
      dcMoveConst(MAXampDrawSpeed, 3);
      dcMoveConst(MAXampDrawSpeed, 4);
    }
    while (millis() - time_zero < NORMampDrawTime); {
      dcMoveConst(NORMampDrawSpeed, 1);
      dcMoveConst(NORMampDrawSpeed, 2);
      dcMoveConst(NORMampDrawSpeed, 3);
      dcMoveConst(NORMampDrawSpeed, 4);
    }
    if (millis() - time_zero > DrawTime) {
      dcMoveConst(0, 1);
      dcMoveConst(0, 2);
      dcMoveConst(0, 3);
      dcMoveConst(0, 4);
    }

    if (millis() - time_zero >= ServoTime); {
      Servo1.write(0);
      delay(400);
      Servo1.write(90);
    }
  }

  if (inPin1 == HIGH) {
    time_zero = millis();
    current_time = millis();
    MAXampDrawTime = 1000;
    MAXampDrawSpeed = 20;
    NORMampDrawTime = 1500;
    NORMampDrawSpeed = 10;
    DrawTime = MAXampDrawTime + NORMampDrawTime;
    while (millis() - time_zero < MAXampDrawTime); {
      dcMoveConst(MAXampDrawSpeed, 1);
      dcMoveConst(MAXampDrawSpeed, 2);
      dcMoveConst(MAXampDrawSpeed, 3);
      dcMoveConst(MAXampDrawSpeed, 4);
    }
    while (millis() - time_zero < NORMampDrawTime); {
      dcMoveConst(NORMampDrawSpeed, 1);
      dcMoveConst(NORMampDrawSpeed, 2);
      dcMoveConst(NORMampDrawSpeed, 3);
      dcMoveConst(NORMampDrawSpeed, 4);
    }
    if (millis() - time_zero > DrawTime) {
      dcMoveConst(0, 1);
      dcMoveConst(0, 2);
      dcMoveConst(0, 3);
      dcMoveConst(0, 4);
    }

    if (millis() - time_zero >= ServoTime); {
      Servo1.write(0);
      delay(400);
      Servo1.write(90);
    }
  }
}

What's inPin1 or inPin0 supposed to do?  It looks like either would reset time_zero, do 1000ms of MAX, 500MS of NORM, then fail the if(>2500) conditional and then do the servo thing.    Are they momentary contact buttons? Are they both supposed to do the same thing?    Maybe time_zero should be reset when either button is pressed, and the system should progress through some states of max speed, some normal speed, shutoff, then do a servo operation before idling.

There are two switches. If inPin0 is pressed then it should go through the if statement that follows. If inPin1 is pressed then the if statement that follows. The servo follows at a set time after the switch is pressed.

Consider something like this edit of your code.  It has two independent switch/case constructs to handle the flinging operation and the releasing operation as independent finite state machines, both subsystems configured as they switch out of the idle state based on the inPin0 or inPin1 status.
The trick of using fast iterations through the loops without delay() helps simulate parallel processing of finite state machines.  With this scheme, one has excess processing time and more options.  One could entangle the two processes if necessary, or add supervisory or monitoring processes that interact with the subsystems.
For tuning, you could make inPin0 be a canned best cycle, and make inPin1 read and use adjustable inputs.
// Not tested or run...
#include <Adafruit_MotorShield.h>
#include <Wire.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
Adafruit_DCMotor *DC4 = AFMS.getMotor(4);

Servo Servo1;

void setup() {
  digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
  AFMS.begin(); //Initializes the motorshield board

  int motorPin1 = 1;
  int motorPin2 = 2;
  int motorPin3 = 3;
  int motorPin4 = 4;

  pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
  digitalWrite(A0, HIGH);
  pinMode(A1, INPUT);
  digitalWrite(A1, HIGH);
  pinMode(A1, INPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  Servo1.attach(9);

  int inPin0 = LOW;
  int inPin1 = LOW;
  inPin0 = digitalRead(A0);
  inPin1 = digitalRead(A1);
}

void loop()  {
  static int flingState = 1; // initial state is 1, the idle state
  static int releaseState = 1; // initial state is 1, the idle state
  static unsigned long flingTime; // to store the current time in for delays
  static unsigned long releaseTime; // to store the current time in for delays

  int MAXampDrawTime;
  int MAXampDrawSpeed;
  int NORMampDrawTime;
  int NORMampDrawSpeed;
  int servoTime = 450;
  int inPin0 = LOW;
  int inPin1 = LOW;
  int DrawTime;
  inPin0 = digitalRead(A0);
  inPin1 = digitalRead(A1);

  switch (flingState) {  // manage flinging
    case 1:  // idle state
      if (inPin0 == HIGH) {  // config for maxthrow
         MAXampDrawTime = 500;
         MAXampDrawSpeed = 20;
         NORMampDrawTime = 250;
         NORMampDrawSpeed = 10;
         DrawTime = MAXampDrawTime + NORMampDrawTime;
         flingState = 2;
      }
      if (inPin1 == HIGH) {  // config for accThrow
        MAXampDrawTime = 1000;
        MAXampDrawSpeed = 20;
        NORMampDrawTime = 750;
        NORMampDrawSpeed = 10;
        DrawTime = MAXampDrawTime + NORMampDrawTime;
        flingState = 2;
      }
      break;

    case 2: // start fling oneshot
        flingTime = millis();
        dcMoveConst(MAXampDrawSpeed, 1);
        dcMoveConst(MAXampDrawSpeed, 2);
        dcMoveConst(MAXampDrawSpeed, 3);
        dcMoveConst(MAXampDrawSpeed, 4);
        flingState = 3;
        break;
    case 3: // maxFlinging timer
        if (millis() - flingTime > MAXampDrawTime) flingState =4;
        break;
    case 5: // initiate slower Flinging oneshot
        dcMoveConst(NORMampDrawSpeed, 1);
        dcMoveConst(NORMampDrawSpeed, 2);
        dcMoveConst(NORMampDrawSpeed, 3);
        dcMoveConst(NORMampDrawSpeed, 4);
        flingState = 5;
        break;
    case 6: // drawing timer
        if (millis() - flingTime > MAXampDrawTime + NORMampDrawTime)
            flingState = 7;
        break;
    case 7 : // s_turnoff:
      dcRelease(1);
      dcRelease(2);
      dcRelease(3);
      dcRelease(4);
      flingState = 1;
      break;

  } // end flingState Machine

  switch (releaseState) {  // independently manage the release servo
    case 1:  // idle
      if (inPin0 == HIGH) {servoTime=450; releaseState = 2;}
      if (inPin1 == HIGH) {servoTime=450; releaseState = 2;}
      break;
    case 2:  // start holding oneshot
      releaseTime = millis();
      releaseState =3;
      break;
    case 3: // holding timer
      if (millis() -releaseTime > servoTime) releaseState = 4;
      break;
    case 4: // releasing oneshot
        Servo1.write(0);
        releaseState = 5;
        break;
    case 5: //released timer
        if (millis() - releaseTime > servoTime+400) {
             Servo1.write(90);
             releaseState = 1; // back to idle
        }
        break;
    } // end releaseState machine
      // if (millis()%100 ==0) reportState(flingState,releaseState);
  } // end loop

There are two major flaws with your program - and both of them can be "fixed" by you understanding some concepts better.
Firstly, in your program, there is no concept of "When the button is pressed", only "While the button is pressed".  This is caused by an error in your understanding of how reading of buttons needs to be done.
The digitalRead() function will return the current state of the button at that precise moment in time. It has no concept of "This has just been pressed", only "This is currently pressed".  So you need to remember in what state the button was last time you looked at it, and only if it has changed do you do something to react to it.  The same with the releasing of the button - at the moment it only knows that it isn't pressed, not that it was pressed but is no longer pressed.
The second problem is that of state, and is closely coupled with the fixing of the reading of the buttons.  At the moment the state of your arduino (i.e., what it thinks it should be doing at the moment) is entirely defined by what buttons are currently being held in or not held in at any one time.  Instead the buttons need to be used to set flags that tell the Arduino what it should be doing and when - such as a flag that says "You should be moving the servos".  Such an arrangement is called a finite state machine and is one of the simplest ways of getting something small like an Arduino to do multiple things at once - in this case reading what is happening to the switches whilst at the same time making motors do different things.
For more information on finite state machines you might like to cast your eye over this: http://hacking.majenko.co.uk/finite-state-machine

I'm not sure, I've just read through it and started implementing the things I've learned, but I think that might be the most helpful link I've seen on thinking of how an Arduino works. As a complete amateur who hadn't ever dreamed of knowing anything about programming just a few short months ago, I would really like to thank you for that. I wish I had found that link weeks ago. I know I'll probably have a question at some point but I really would like to say thank you for that!

@TeamOne you're more than welcome. I'm just glad to do my part in spreading knowledge. I'm a firm believer that if you know how to do something it is your responsibility to ensure that other people can learn it from you too. Knowledge is to be shared, not hoarded.

That's a refreshing way to see the world. Thank you for that.

@Majenko --- I love this new way of thinking about code!
So my question is - maybe it would do some good to know what my robot is doing, it's launching a fishing rod. It's turning the motor to fling the arm, and the servo will disengage the button in order to launch the lure. These processes are independent from each other... the servo might start working before the motor stops working, but both rely on the switch being pressed, and I won't know at which point the servo should release until testing starts.
Edit: I've realized that I've got the if qualifiers in the wrong place and I'm currently trying to fix that.
#include <Adafruit_MotorShield.h>

#include <Wire.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
Adafruit_DCMotor *DC4 = AFMS.getMotor(4);

Servo Servo1;

void setup() {
  digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
  AFMS.begin(); //Initializes the motorshield board

  int motorPin1 = 1;
  int motorPin2 = 2;
  int motorPin3 = 3;
  int motorPin4 = 4;

  pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
  digitalWrite(A0, HIGH);
  pinMode(A1, INPUT);
  digitalWrite(A1, HIGH);
  pinMode(A1, INPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  Servo1.attach(9);
#define s_idle 1
#define s_maxthrow 2
#define s_accthrow 3
#define s_waitservo 4
#define s_servogo 5
#define s_turnoff 6

  int inPin0 = LOW;
  int inPin1 = LOW;
  inPin0 = digitalRead(A0);
  inPin1 = digitalRead(A1);
}

void loop()  {
  static int state = 1; // initial state is 1, the idle state
  static unsigned long ts; // to store the current time in for delays
  int MAXampDrawTime;
  int MAXampDrawSpeed;
  int NORMampDrawTime;
  int NORMampDrawSpeed;
  int servoTime = 450;
  int inPin0 = LOW;
  int inPin1 = LOW;
  int DrawTime;
  inPin0 = digitalRead(A0);
  inPin1 = digitalRead(A1);

  switch (state) {
    case s_idle:
      //we don't deen to do anything here, waiting for a state
      break;

    case s_maxthrow:

      if (inPin0 == HIGH); {
        MAXampDrawTime = 500;
        MAXampDrawSpeed = 20;
        NORMampDrawTime = 250;
        NORMampDrawSpeed = 10;
        DrawTime = MAXampDrawTime + NORMampDrawTime;

        ts = millis();

        dcMoveConst(MAXampDrawSpeed, 1);
        dcMoveConst(MAXampDrawSpeed, 2);
        dcMoveConst(MAXampDrawSpeed, 3);
        dcMoveConst(MAXampDrawSpeed, 4);
        delay(MAXampDrawTime);
        dcMoveConst(NORMampDrawSpeed, 1);
        dcMoveConst(NORMampDrawSpeed, 2);
        dcMoveConst(NORMampDrawSpeed, 3);
        dcMoveConst(NORMampDrawSpeed, 4);
        delay(NORMampDrawTime);
        state = s_turnoff;

      }
    case s_turnoff:
      dcRelease(1);
      dcRelease(2);
      dcRelease(3);
      dcRelease(4);
      state = s_idle;
      break;

    case s_accthrow:
      if (inPin1 == HIGH); {
        MAXampDrawTime = 1000;
        MAXampDrawSpeed = 20;
        NORMampDrawTime = 750;
        NORMampDrawSpeed = 10;
        DrawTime = MAXampDrawTime + NORMampDrawTime;

        ts = millis();

        dcMoveConst(MAXampDrawSpeed, 1);
        dcMoveConst(MAXampDrawSpeed, 2);
        dcMoveConst(MAXampDrawSpeed, 3);
        dcMoveConst(MAXampDrawSpeed, 4);
        delay(MAXampDrawTime);
        dcMoveConst(NORMampDrawSpeed, 1);
        dcMoveConst(NORMampDrawSpeed, 2);
        dcMoveConst(NORMampDrawSpeed, 3);
        dcMoveConst(NORMampDrawSpeed, 4);
        delay(NORMampDrawTime);
        state = s_turnoff;
      }

    case s_servogo:
      if (millis() - ts > servoTime); {
        Servo1.write(0);
        delay(400);
        Servo1.write(90);
      }

  }

}

The delay()s will monopolize the attention of the processor and prevent you from independently controlling the casting and releasing subsystems.    You can avoid the delays() by letting the state machine(s?) handle them and considering how you transition between states.  For instance, you can go from s_idle to EITHER s_maxthrow or s_accthrow based on inPin0 or inpin1 being triggered.  And you can avoid the delay by splitting s_accthrow into s_accthrow_1 and s_accthrow_2, transitioning from one to the other after it s_accthrow has been in that state for at least MaxMapDrawTime.

See http://arduino.stackexchange.com/questions/17918/using-arduino-for-simultaneous-lighting-effects/17929#17929 for essentially two independent state machines which pass control back to loop() immediately, so it can be as responsive as possible.


text:
Making tmrpcm.play("1.wav") depend on LDR feedback?
I have the speaker working with the tmrpcm.play working, but this only plays when the arduino is powered up or reset. Can i make the .wav play in anther other ways?
I wan't the file to play when i open a closet and my LDR resistor is affected by light.
#include <SD.h>                           //include SD module library
#include <TMRpcm.h>                       //include speaker control library

#define SD_ChipSelectPin 4                //define CS pin

TMRpcm tmrpcm;                            //crete an object for speaker library

const int ledPin = 8;
const int buzzerPin = 10;
const int ldrPin = A0;
int ledState = LOW;
int buzstate = 600;
unsigned long previousMillis = 0;

int ldrStatus = analogRead(ldrPin);  //read the state of the LDR value

const long interval = 400;

void setup () {

  tmrpcm.speakerPin = 9;
  Serial.begin(9600);

  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(ldrPin, INPUT);

 }
void LedAndBuzzer(){
   unsigned long currentMillis = millis();
  int ldrStatus = analogRead(ldrPin);  //read the state of the LDR value

 if (ldrStatus >= 400) {

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
    digitalWrite(buzzerPin, ledState);
}}
}
void soundon(){
    if (!SD.begin(SD_ChipSelectPin)) {      //see if the card is present and can be initialized

    return;                               //don't do anything more if not
  }
  else {
  tmrpcm.setVolume(6);                    //0 to 7. Set volume level
  tmrpcm.play("4.wav"); }
}

void loop() {

  }

Yes, that is totally possible. You need to write the code for it. What have you tried so far? Do you know how to read an LDR? Have you searched for tutorials?

@chrisl thanks for the respons, yes i have googled a lot, but im quite new to programming and working with the arduino. This is the code (updated the post) that in working on right know.
There is one more element than my original question, i want it to start the led/buzzer loop at the same time as the .wav file is played. Is this posible?

Is tmrpcm.play() a blocking function?

@Fahad i don't know what that means

You said i want it to start the led/buzzer loop at the same time as the .wav file is played. So I was wondering when you call tmrpcm.play() function does it return immediately or does it return after it finishes playing the wave file.

@Fahad tmrpcm.play() is non blocking. It starts playing then tmrpcm.stopPlayback() stops the music and tmrpcm.isPlaying() return the state of the player.

@Dorian great, thanks. @Elisabot, so you want to play the wav file when your LDR is >= 400 and stop the music when less?


text:
Powering LED Strip at both ends shorts my psu?
I've got a 200 LEDs strip of sk9822's hooked up to a 5V 8A power supply.
As expected, at full white, there's considerable voltage drop and the far end of the strip turns from white to amber.
I wanted to hook up another set of V+ and GND at the far end of the strip, but doing so trips my psu? The strip blinks full white as a result.
Hooking up ONLY GND or ONLY V+ at the far end significantly improves the drop off where only the middle of the strip turns slightly amber-ish.
But! I do notice a faint buzzing from the PSU if I do this.
Am I doing something wrong here?

difficult to guess if you did something wrong ... you did not say how you connected everything up ... please draw a diagram

Assuming 60mA per led (20mA per colour) you would need a minimum 12A power supply, not 8A. Your PSU is too weak.

What if you only power it at the middle?
But indeed, your PSU may not be able to supply the whole strip, the reason it blinks is that it shuts off on it's limit and starts back up again.
If you really would have shorted it; I think the strip itself would have behaved differently.

Basically, the idea is right. Powering from both ends is fine and will fix (at least enhance) the voltage drop problem. Still, Majenko is right. With 8A you shouldn't let them shine in full white. Some colors might work, though.

Put a diode to every psu cable or just take only one psu but make a connection between the input and the far end eith a cable of more than 0,5 mm^2... Spesker csble or so.
Problem with two psu is: one gives 5,00 Volt,  the other 5,05... And there is s power of 0,05 Volt / 8 Ampere running.
Second problem can be the influrnce of different PSU switching frequencies.
Regards,  Michael

Why do you assume two different PSUs? As far as I understood, he wants to power it with 1 PSU but 4 connectors (2 on one end, 2 on the other end).


text:
Servo MG996R - what is the maximum load for very long time?
I am working on a device which will have to periodically switch positions and keep the position for very long time, as accurate as possible, under tension.
Never worked with servo motors before, but I found MG996R interesting. It has a stall torque of approx 12kg*cm (@6V).
My question is:
To what maximum safe continuous load I could subject the motor if I need to keep it in position for 24h+ (it may switch position occasionally, but worst scenario would be like 24h-48h continuous locking in same position) ?

perhaps you could use a brake of some type ... release the brake to move to another position, then re-apply the brake

i'm trying to limit the weight, but thank you for the suggestion! Another option was a latch mechanism, to lock in place once position has been changed, but I am still interested to figure out how much stress a servo motor would take considering my requirements.

There is by far not enough information to answer your question. The force that acts on the motor axis depends on the rotation angle. the length of the lever the direction of the "tension" force vector. The time the motor can withstand a force depends on it's stall torque, the current through the motor on high load and the time the motor is allow to be driven with this current. It also depends on the  current through the driver and the time the driver can handle this. There is also a rot angle where the torsion force to the motor is minimal (near 0), so it dep. on the mech. robustn. o.t. motor.


text:
Using the same variable between if-statements within loop()
I wonder if there is a good way to use the same variable value between two different if-statements within the loop().
Within the Servomotor section of the code, I want to use the value from the first if-statement's RewardTime within the next if-statement's RewardTime. Thus far, I cannot find a way to do it.
(Since there is no communication between these variables right now, the RewardTime remains 0).
I'd appreciate a certain guidance in this matter.
#include <Servo.h> // Library required for the servomotor (Make sure to download if not in the library)
#include <Button.h> // Library required for the microswitch (Make sure to download if not in the lbrary)

// PARAMETERS
// COPY THESE VALUES IN PROCESSING CODE MANUALLY
// Explanation: To prevent possible Arduino-Processing overflow. Do not want too much information flow between Arduino and Processing.
const float Scale = 1 * 1000; // milliseconds
const float Base = 1 * 1000; // milliseconds

Servo Servo1;
int servoPin = 9; // Declare the Servo pin
Button button(7); // Declare the microswitch pin (Can be varied from setup to setup)

unsigned long previousMillis = 0;
bool switching = false;
int State = LOW;

char BirdSings = 0;
//static float RewardTime = 0;

void setup() {
   Servo1.attach(servoPin);
   analogWrite(9, 0);
   Serial.begin(9600);
   button.setDebounceTime(100); // set debounce time to 100 milliseconds
}

void loop(){
   // MICROSWITCH
   // Get onset and offset times of when the bird arrives and leaves the perch
   button.loop();
   if(button.isPressed())
    Serial.println(1);
   if(button.isReleased())
    Serial.println(0);

   // SERVOMOTOR
   // Get times when the feeder is covered (food present) and uncovered (food not present)
    unsigned long currentMillis = millis();
    while (Serial.available() > 0) {
    unsigned long currentMillis = millis();
   if (Serial.read() == '\n') { // When there is a song
     //Serial.println(2); // Food is uncovered
     previousMillis = currentMillis; // 0 becomes the current milli
     static float RewardTime = (Serial.parseFloat() * Scale) + Base; // CALCULATE THE RewardTime HERE
     Serial.println(RewardTime);
     if (State == LOW)
      State = HIGH;
     else
      State = LOW;
    }
   }

  if (State == HIGH && switching == false){
    Servo1.write(0); // 0 degree
    unsigned long secondCurrentMillis = millis();
    if (secondCurrentMillis - previousMillis > RewardTime) { // USE THE ABOVE RewardTime HERE
      switching = true;
      previousMillis = secondCurrentMillis;
      if (State == LOW)
        State = HIGH;
      else
        State = LOW;
    }
  }
  if(State == LOW && switching == true){
    Servo1.write(90); // 90 degrees
    switching = false;
    //Serial.println(3); // Food is covered
    }
}

Make the variable global, thus put it outside the loop function; also you don't need the static keyword anymore.
float RewardTime = 0;

Than inside your first if statement, remove the static float keywords:
RewardTime = (Serial.parseFloat() * Scale) + Base;

Some other tips:

normally local variables do not start with a capital (so rewardTime is like most coding conventions)
Always use brackets.
if (State == LOW)
  State = HIGH;
else
  State = LOW;

Change to:
  if (State == LOW)
  {
    State = HIGH;
  }
  else
  {
    State = LOW;
  }

However, to make it more simpler, use the ternary operator, you can change it to:
State = (State == LOW ? HIGH : LOW);

Which means: if some condition ? Do this : Else do this;

HIGH / LOW and true / false are identical, so State = ! State;is sufficient.

@DataFiddler But you shouldn't be dependent on the values inside a library. Suppose in future they will change the values to 20 and 30 instead of true/false. If the Arduino API intended a Boolean they should have used a Boolean type.

if they ever change change the definition of HIGH and LOW, I will stop using Arduino. They even don't dare to change the return type of digitalRead, which is a good decision.

@DataFiddler … good point, and I fully agree it would break many sketches. But they really should use a Boolean as input argument type, or an enumeration EPinState (LOW, HIGH) or something like that.

That question mark is called Elvis operator for the people that doesn't know, it's similar as an if else but with some compiler it could be faster (This happens on intel for example with the cmov instruction)

@alessandromrc I think the Elvis operator is indeed the more informal name (thanks for the addition). Btw, I think it's in general not a good idea to write for performance reasons unless known beforehand or when needed (afterwards), it just reads easier (if it fits on a single line mostly).

Since you defined it within the first if statement, it is only "in-scope" or defined within that block. To make it visible to both if statements, define it in the next outer block that contains both if statements - in this case, somewhere between void loop(){ and if (Serial.read()...


text:
How to send a message to my phone that my Arduino system is on when turning on my Arduino
i have installed a GSM shield on the Arduino to create security alarm system using PIR SENSOR when ever there motion I will receive a call to my phone.
but i want to add also a line of code which can make my system send me a txt message stating that my system is turned on so i can make sure that when ever i turn my system on i can doule check by getting a message that says that system is turned on successfully
i dont know how to start doing that.
this is the code i did:
int PIR = 6;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(96000);
 pinMode (PIR , INPUT );
}

void loop() {
  // put your main code here, to run repeatedly:
if (digitalRead (PIR == HIGH)){
  Serial.println("thief detected");
  delay (200);
  Serial.println ("ATD+0197263315;");
  delay(1000);
  Serial.println("ATH");
  delay(1000);

  }
  else digitalWrite (PIR, LOW );

}

if (digitalRead (PIR == HIGH)) is not doing what you think it does.  Look at where your parenthesis are.

can explain more

PIR == HIGH is false, because PIR is 6 and HIGH is 1.  You have digitalRead(false).  digitalRead takes type int.  Converted to int, false is 0.  You have effectively digitalRead(0).

You can send an SMS using the Arduino GSM library. Here is a bare bones sketch that sends one pre-set SMS when it starts up, based on this tutorial:
#include <GSM.h>

#define PINNUMBER "1234"
#define REMOTENUMBER "07123456789"
#define TXTMESSAGE "System started!"

GSM gsmAccess;
GSM_SMS sms;

void setup() {
  boolean notConnected = true;

  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      delay(1000);
    }
  }

  sms.beginSMS(REMOTENUM);
  sms.print(TXTMESSAGE);
  sms.endSMS();
}

void loop() {
}

If you can't or don't want to use the GSM library, it should also be possible to send an SMS by using the SoftwareSerial library to control your GSM shield using AT codes. Here's a tutorial on this approach, which is lighter weight but might be more fiddly to get working, especially if you need a PIN for your SIM card.