message:
Connect Arduino Uno to video camera's web Server via Ethernet (not working)

I work with cameras in the film and TV industry. A project I have just started tinkering around with is building an Arduino Uno-based box that would automatically collect the metadata (settings, etc.) via the camera's built-in web server (over Ethernet, at least at the moment). Specifically the Arri Alexa camera.

Like I said, this camera already has a web server and the functionality built in for somebody to hook their computer directly up to the camera with an Ethernet cord (it actually uses an RJ45 - Lemo proprietary cable system in order to support some accessories that draw more power than RJ45 is capable of). Then when you navigate to the camera's IP address in a web browser it serves up a web page to you with all the camera settings and other things displayed.

I found that my test computer connected perfectly to the camera without fiddling with any network settings as the manufacturer's documentation seemed to indicate. Here are the basic network settings my computer had when connected directly to the camera over ethernet (no Arduino yet):

[![IPConfig Settings][2]][2]

Notice the IP Address and subnet mask: 169.254.106.46 and 255.255.0.0 respectively.

Just to note, these are the manufacturer recommended settings I found in some literature:

[![enter image description here][3]][3]

Since that was working I tested the Arduino using the same settings. I am using an Arduino Uno combined with a Seeed Ethernet Shield (v2.0) which utilizes a Wiznet 5200 processor (not the 5100 normally used). Because of this you have to use the Ethernetv2_0 library that Seeed provides rather than the normal Ethernet library.

Here is my code, basically an adapted version of the WebClientRepeating example. I got this code working when I was just connecting to say arduino.cc and was going through the hub of my router (auto-assigned IP address). However when I attempt to connect to the camera with the Arduino sans Hub / Switch with a manually assigned IP address and subnet mask and all that I can never make the client (object) to connect. Basically this code is printing out "connection failed" to the serial monitor indicating and connection was never established.

    #include <SPI.h>
    #include <EthernetV2_0.h>

    // assign a MAC address for the ethernet controller.
    // fill in your address here:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };

    // fill in an available IP address on your network here,
    // for manual configuration:
    //IPAddress ip(169, 254, 106, 46); //Address that worked on my computer
    IPAddress ip(169, 254, 1, 2); //Manufacturer recommended address

    // fill in your Domain Name Server address here:
    IPAddress myDns(1, 1, 1, 1); //Random, not sure if I need to do anything specific here

    // subnet mask that manufacturer recommends and what worked on my computer
    IPAddress subnet(255, 255, 0, 0);

    // initialize the library instance:
    EthernetClient client;

    //IPAddress server(64,131,82,241); //arduino.cc IPAddress
    IPAddress server(169, 254, 184, 143); //Arri Alexa (Camera) IPAddress

    unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
    const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
    // the "L" is needed to use long type numbers

    #define W5200_CS  10
    #define SDCARD_CS 4

    void setup() {
      // start serial port:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      pinMode(SDCARD_CS,OUTPUT);
      digitalWrite(SDCARD_CS,HIGH);//Deselect the SD card
      // give the ethernet module time to boot up:
      delay(1000);
      // start the Ethernet connection using a fixed IP address and DNS server:
      Ethernet.begin(mac, ip, myDns, subnet);
      // print the Ethernet board/shield's IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      // if there's incoming data from the net connection.
      // send it out the serial port.  This is for debugging
      // purposes only:
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
      }
      // if ten seconds have passed since your last connection,
      // then connect again and send data:
      if (millis() - lastConnectionTime > postingInterval) {
        httpRequest();
      }
    }

    // this method makes a HTTP connection to the server:
    void httpRequest() {
      // close any connection before send a new request.
      // This will free the socket on the WiFi shield
      client.stop();
      // if there's a successful connection:
      if (client.connect(server, 80)) {
        Serial.println("connecting...");
        // send the HTTP GET request:
        client.println("GET /webremote/index.html HTTP/1.1");
        client.println("Host: 169.254.184.143");
        client.println("User-Agent: arduino-ethernet");
        client.println("Connection: close");
        client.println();
        // note the time that the connection was made:
        lastConnectionTime = millis();
      } else {
        // if you couldn't make a connection:
        Serial.println("connection failed");
      }
    }

I guess my question is, if I'm using the exact same network settings that worked for my computer connecting to the camera, why aren't they working for the Arduino? I know this is somewhat of an obscure situation but I'll appreciate any ideas you can give me. Thanks!

  [2]: https://i.stack.imgur.com/kT4cr.png
  [3]: https://i.stack.imgur.com/bODPX.jpg

body:
I agree with Mark that your code all looks sensible, apart from the line defining myDNS. I have no experience of the board/library you are using, but recently I saw an industrial board suffer from a similar problem that turned out to be it was trying to resolve an IP address to a name using reverse DNS and because the DNS server wasn't set properly it failed to connect. So it might be that by setting the address in the myDNS line to a valid DNS server (the one your test PC uses?) then the problem will go away.

If that doesn't work then can you read the manual and see if the Client object can be persuaded to give you an error code or message that would give you a hint as to why it isn't working?

I understand that 169.254.1.2 is the manufacturer recommended address, but why did you use 169.254.106.49 for the test PC? It's very unlikely to be anything, but...

Also (I'm sure this was your first check), is the connection between the Arduino and the camera a straight connection, there are no firewall, routers, switches or bridges in the way doing NAT or PAT or blocking certain connections etc?

(DNS = Domain Name Service, converts names like google.com into meaningful addresses like 1.2.3.4)


sender: user

sender: assistant

body:
In the spirit of "Use the Source, Luke," I've had a look at the [code on GitHub](https://github.com/Seeed-Studio/Ethernet_Shield_W5200/blob/master/EthernetV2_0.cpp#L54), which is I hope the same code that you're using or very similar to it.

There the four-parameter version of `Ethernet.begin()` takes the gateway, not the subnet mask, as the fourth parameter. The subnet mask, when passed in explicitly, is the fifth parameter of the five-parameter version.

This shouldn't actually make any difference since the gateway ought not be used for anything on the same subnet, and the default subnet for [class B addresses](https://en.wikipedia.org/wiki/Classful_network#Classful_addressing_definition)  (from `128.0.0.0` through `191.255.255.255`), in which range your address falls, is 16 bits, `255.255.0.0`.

The problem is, the code linked has what I would [argue is a bug](https://github.com/Seeed-Studio/Ethernet_Shield_W5200/issues/9):

    void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway)
    {
      IPAddress subnet(255, 255, 255, 0);
      begin(mac_address, local_ip, dns_server, gateway, subnet);
    }

The subnet mask is _always_ set to 24 bits (`255.255.255.0`), in this call that you're using.

`169.254.1.2` and `16.254.184.143` don't have the same 24-bit prefix, so the software (I assume, I've not followed it through) will try to contact the gateway you inadvertently supplied, which isn't even on the same network (not to mention nonexistent), and so fail.

Try calling the 5-argument `Ethernet.begin()` (passing in `0.0.0.0` for the gateway should be fine) and see if that fixes your problem.

I checked the [WebClientRepeating example](https://github.com/Seeed-Studio/Ethernet_Shield_W5200/blob/master/examples/WebClientRepeating/WebClientRepeating.ino#L55) in that repo and they use the three-parameter version. Perhaps you switched to the four-parameter version, or perhaps you got your example from another library. (This example hasn't been modified since the start of the repo in April 2014.)


message:
DS18B20 - Temperature a bit off?

I'm trying to measure the temperature using a DS18B20 sensor. I'm using the DallasTemperature and OneWire Libraries. The sensor is connect in Pin 10 with a 4k7 resistor between VDD and DQ (actually I'm using 4x 1k and 2x 330 ohms) as so:

[![layout][1]][1]

Here's the code I'm using:

    #include <OneWire.h>
    #include <DallasTemperature.h>

    #define ONE_WIRE_BUS 10

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

    float celsius;

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

      sensors.setResolution(12);

      sensors.begin();
    }

    void loop(void) {
      sensors.requestTemperatures();
      celsius = sensors.getTempCByIndex(0);

      Serial.println(celsius);
    }

The sensor is outputing values close to the actual temperature (measure with a mercury thermometer), but a bit off.

Example:

    Sensor Temperaute: 34.44°C
    Thermometer Temperature: ~32°C

Why is that? And how can I fix it?

  [1]: https://i.stack.imgur.com/UhHft.jpg

body:
When the wires to the DS18B20 are short, you can use a 10k resistor as well.

The DS18B20 is accurate. If you have connected it wrong and it became very hot, then it might be damaged. But normally it is always accurate.

Many report that the DS18B20 returns a high temperature, and the cause is often something nearby that makes the DS18B20 warmer. For example an Arduino board (with a hot voltage regulator) or a computer screen or a certain air flow of warm air or even very dim sunlight. A normal thermometer does not do that, but the DS18B20 is highly influenced by warm things nearby.

Some temperature sensors have a problem with self-heating. You could add a delay of 5 seconds in the loop function, to see if that makes a difference.

To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water).

The picture uses pin 2 and the sketch uses pin 10. I assume that is a mistake.


message:
Serial LCD has like a "rolling shutter"

I've attached my LCD Display (AV1624YRB-SJ) to my Arduino Nano on the following pins:

    #define LCD_RS 7
    #define LCD_ENABLE 8
    #define LCD_D4 9
    #define LCD_D5 10
    #define LCD_D6 11
    #define LCD_D7 12
    #define LCD_CONTRAST 6 //PWM Wave with capacitor for contrast

and im initializing it this way:

    LiquidCrystal lcd(LCD_RS, LCD_ENABLE, LCD_D4, LCD_D5, LCD_D6, LCD_D7);

    byte arrow[8] = {
        B00000, B00100, B00010, B11111, B00010, B00100, B00000,
    };

    void setup() {
      pinMode(LCD_CONTRAST, OUTPUT);
      pinMode(LCD_D4, OUTPUT);
      pinMode(LCD_D5, OUTPUT);
      pinMode(LCD_D6, OUTPUT);
      pinMode(LCD_D7, OUTPUT);
      analogWrite(LCD_CONTRAST, STARTCONTRAST); // Set LCD Contrast

      lcd.begin(16, 2);
      lcd.createChar(CHAR_ARROW, arrow);
      lcd.setCursor(3, 0);
      lcd.print("Welcome To");
      lcd.setCursor(1, 1);
      lcd.print("My Test");
      delay(2000);
    }

The Problem is, that there is nothing to see on the display.
If i crank up the contrast slightly you can see something like a rolling shutter effect.

http://i.imgur.com/FOIEwVj.gif

The display worked just fine 3 days ago.
Where could be a mistake. I don't remember changing something, but i tried rewiring.

body:
As I noted in a comment to the question  [Arduino LCD is displaying gibberish, sometimes](https://arduino.stackexchange.com/q/33578),  a PWM's sharp-cornered waveform might introduce a lot of noise into the LCD.  If you have to use PWM, you probably should put a good low-pass filter between PWM and LCD pin 3.

Check whether using a fixed voltage (from a voltage divider or pot) fixes the problem.  That fixed the problem in the case of the linked question.

If you need programmable control of contrast, and can't get PWM to work without heroic measures involving op-amp based filters, you could use a digital pot or a DAC.


message:
Photoresistor value drops when board stacked on Arduino Uno

I have a simple photoresistor displaying values on a serial monitor every second so I can establish a value that I want to use to have it activate a relay.

It has worked fine for a few weeks, with bright sunlight values about 1000, total dark is 0. I soldered only the headers on a protoshield, and stacked it on the Arduino. I have nothing else on the protoshield and I am still using jumper wires to a breadboard, which I have not changed.

Why would the photoresistor values drop to approximately 40 (from 900's) when I stack the second board on the Arduino?

body:
It should not happen.

I have changed this answer, because at first I read that the resulting value was changed by -40, but I think it drops from 900 to 40.

The shield is doing something, so it is not empty. Perhaps it shortcuts the AREF to GND. Perhaps you are reading an open input, and the sensor is at another analog pin. Perhaps the shield does something to the voltage pins.

A breadboard can have bad contacts. The shield can have bad contacts.

Be sure that the sensor is connected to the channel that you are reading. Measure the voltage at that analog input with a multimeter with and without the shield. Check the 5V, 3.3V and AREF pins with and without the shield.


body:
Does the proto-shield have any LEDs on it?

You were probably connected to a pin unknowingly.

How is resistance being measured? A voltage divider with an `analogRead()`?
Using a cheapo multimeter can cause problems.

Possibly, his proto-shield has some trace "wires" etched into it that were unseen, and he was connected to a floating pin or ground.

Or maybe the shield was shifted over one pin, and he wasn't connected to the pins he thought.


message:
unexpected change of ADC value with multiple voltage dividers (thermistors and pot)

So this is my basic circuit. Three voltage dividers: one 10k pot, 2 thermistors. Fan driver circuit using TIP120 (currently just driving an LED from the 3.3v source). Board is a Leonardo clone, circuits.io only had the Uno in their library. Edit: circuit is now more simplified.

Schematic:

[![bbw temp controller][1]][1]

reality:

[![enter image description here][2]][2]

When I adjust the pot, the ADC value of `airPinValue` changes, regardless of which analog input it is connected to. `meatPinValue` does not change. Swapping the inputs that `airTempPin` and `meatTempPin` are assigned to has no effect, `airTempPin` changes the same. Physically swapping the thermistors has no effect, nor does switching which input they connect to.

Code:

    #define potPin A0
    #define airTempPin A5

    int potValue = 0;
    int airPinValue = 0;
    int i = 0;

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

    void loop() {
      i++;
      potValue = analogRead(potPin);
      airPinValue = analogRead(airTempPin);
      if (i == 2000) {
        Serial.print(potValue);
        Serial.print(",");
        Serial.println(airPinValue);
        i = 0;
      }
    }

EDIT: much simplified code

EDIT v2.0 : I have now swapped out the board for an official Uno, as well as swapped everything to a different breadboard and a different Leonardo, with no change in behavior.

EDIT v3 : Corrected code sample. I have also dropped my DMM onto this, reading from the 5v rail to the voltage going to A2. With the pot set to 0 I see 2.401v from the divider, pot to max, same voltage, 2.401v.

EDIT v4: with only the pot and airTemp hooked up, still happens. Further DMM probing actually shows that this only happens when the pot and thermistor are both hooked up to the arduino. If either one is disconnected, the voltage being read by `airTempPin` is stable/correct. Once both are hooked up to the analog pins on the arduino, that's when the voltage at `airTempPin` goes off...

Also update diagram, pic, and code to match what I'm currently testing with.

EDIT v5 : This is some sort of analog bleed between the analog input ports. Not really sure how I can combat this :\

  [1]: https://i.stack.imgur.com/5hCqO.png
  [2]: https://i.stack.imgur.com/9HUqs.jpg

body:
https://www.arduino.cc/en/main/arduinoBoardUno
> Vin. The input voltage to the Arduino/Genuino board when it's using an
> external power source (as opposed to 5 volts from the USB connection
> or other regulated power source). You can supply voltage through this
> pin, or, if supplying voltage via the power jack, access it through
> this pin.

Thisi not to be used as powersource for motor/LED whatever, this is input.

Use 5V instead, maybe this would solve the problem.


body:
    #define meatTempPin A0
    #define airTempPin A1

Your code says A0,A1 but the circuit and picture of the wires say A0,A2.

Since A1 doesn't appear to be connected, as you scan things, the ADC could be sampling and holding some voltage from the prior conversion of potPin.

Try this instead:

    #define meatTempPin A0
    #define airTempPin A2


body:
Moral of the story, the multiplexer was not switching between inputs quickly enough causing the odd reading, looking very much like bleed between the pins. By simply reading each analog input twice and only storing the value of the second reading, I was able to get a valid, stable, reading as expected.

    #define potPin A4
    #define airTempPin A0

    int potValue = 0;
    int airPinValue = 0;
    int i = 0;

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

    void loop() {
      i++;
      analogRead(potPin);
      potValue = analogRead(potPin);
      analogRead(airTempPin);
      airPinValue = analogRead(airTempPin);
      delay(10);
      if (i == 50) {
        Serial.print(potValue);
        Serial.print(",");
        Serial.println(airPinValue);
        i = 0;
      }
    }


body: You need to have a reference voltage for ADC the problem is that you are not setting the reference voltage for ADC.Change the code in setup where you add a analog reference voltage as internal or default according to your requirement.


message:
Calculate the time since arduino started working for a year

I want Calculate the time since arduino started working for a period of one year using arduino uno and when the period is over flip a light on

body:
The function millis counts up to about 50 days. However, you can make a software timer with millis of, for example, 1Hz. With a unsigned long that counts the seconds, it is easy to count a year.

It will not be reliable. When the power is off, it starts again. A RTC (Real Time Clock) with its own battery is better.

Are you a good software engineer ? How can you be sure that it will work ?


body:
Simplest solution would be to use `millis()`, but you will need to
somehow take care of the periodic rollover. Creating a lower frequency
software timer, as explained by Jot, is one solution. Another option is
to extend `millis()` to 64 bits:

    uint64_t millis64()
    {
        static uint32_t low32, high32;
        uint32_t new_low32 = millis();
        if (new_low32 < low32) high32++;
        low32 = new_low32;
        return (uint64_t) high32 << 32 | low32;
    }

You must call this function at least once every 49.7 days, otherwise it
will loose time. I would just call it on every loop iteration, like
this:

    const uint64_t ONE_YEAR = 365.25 * 86.4e6;  // Julian year

    void loop()
    {
        if (millis64() >= ONE_YEAR) {
            // do some stuff...
        }
    }

Besides the issue of a possible power failure, there is another caveat:
the Arduino Uno is clocked off a ceramic resonator. These are not very
accurate, and are typically specified to be within 0.5% of their nominal
frequency. This means that your “year” can be off by as much as
1.8 days. RTCs are clocked off a quartz crystal and are then far
more accurate. Ultimate accuracy could be achieved with a GPS receiver.


body: I would use a network card to talk to an NTP server. In setup(), fetch the time and save it to EEPROM if there's not one already saved. You can then ping the NTP server every day or every boot, comparing the saved date and responding as appropriate. This strategy avoids MCU timer slew, power-out milis() resets, and extra hardware (other than networking, which more and more projects have already anyway).


message:
Motor running during Motor Shield R3 reset

I have a problem with the [Arduino Motor Shield R3][1] on an Arduino Uno. I Have a DC Motor on the A Channel and the Shield is connected to an external power source. When I reset the Arduino card the motor starts running by default until the pins are initialized.

This is really problematic for me because the motor is on a rail delimited by 2 switches, when a switch is reached the motor stops. When the motor moves during reset the value of the switches are not read yet, which causes the motor to go beyond the switch and be blocked afterwards.

When I reset the card I read the value of the 3 digital pins used to drive the motor :

 - pin 12 : Direction (DirA), HIGH motor foward, LOW motor running backward
 - pin 3 : Power (PwmA), HIGH motor running, LOW motor not running
 - pin 9 : Brake (BrakeA), HIGH brake is on, motor can't run, LOW brake is off, motor can run

Before reseting I put the 3 pins at HIGH, At reset, pin 12 == HIGH, pin 9 == LOW, pin 3 == HIGH
which means that the brake is disengaged but the Power is still here, so the motor starts running again until the pinMode function is reached. During that reset time of approximately 2 seconds, the motor has the time to go beyond the switches which causes the system to break.

**Is this normal ? Is there a way to force the pin 3 to be at LOW when the Arduino resets ?** I put my code at the bottom.

**Naïve solution** : is to put PwmA at LOW when a switch is reached, so I'm sure it will stay that way until the next reset. But if the arduino is reseted while the motor is running I still have the problem.

    int closeSwitch = A3;
    int openSwitch = A2;
    int DirA = 12;
    int PwmA = 3;
    int BrakeA = 9;

    int OpeningDirection = LOW;
    int ClosingDirection = HIGH;

    bool motorRunning = false;
    bool motorOpening = false;
    bool openSwitchReached = false;
    bool closeSwitchReached = false;

    void setup() {

      Serial.begin(9600);

      sendToPC("Init\n"); //This is just to read the init state of the pins
      Serial.print(digitalRead(DirA));
      Serial.print(digitalRead(BrakeA));
      Serial.print(digitalRead(PwmA));

      pinMode(openSwitch, INPUT);//is High when Hublot opened
      pinMode(closeSwitch, INPUT); //is HIGH when hublot closed
      pinMode(DirA, OUTPUT); //Initiates Motor Channel A pin
      pinMode(BrakeA, OUTPUT); //Initiates Brake Channel A pin
      pinMode(PwmA, OUTPUT); //Initiates Brake Channel A pin

      sendToPC("\nAfter\nA:"); //After init all is LOW
      Serial.print(digitalRead(DirA));
      Serial.print(digitalRead(BrakeA));
      Serial.print(digitalRead(PwmA));

      //Stopping the motor
      setMotorSpeed(0);
      if (digitalRead(BrakeA) == LOW) {
        brakeMotor();
      }

      //Is the first switch on
      openSwitchReached = (digitalRead(openSwitch) == HIGH);
      //Second switch state
      closeSwitchReached = (digitalRead(closeSwitch) == HIGH);

      handleSerialInput(-3); //Send ping return
      handleSerialInput(-2); //Send status
    }

    void sendToPC(const char * str) {
      Serial.write(str);
      delay(215); //Delay to avoid answers being read as one
    }

    void setMotorSpeed(int speed) {
      if (speed > 0)
        digitalWrite(BrakeA, LOW);   //Disengage the Brake for Channel A
      digitalWrite(PwmA, HIGH);   //Spins the motor on Channel A at full speed
    }

    void setMotorDirection(int direction) {
      digitalWrite(DirA, direction); //Establishes direction of Channel A
    }

    void brakeMotor() {
      digitalWrite(BrakeA, HIGH);
      //digitalWrite(PwmA, LOW); -> this is my naïve solution
    }

    void handleSerialInput(int input) {
      Serial.print(input);
      if (input == 1 && !openSwitchReached) { //open
        brakeMotor(); // stop motor
        delay(100);
        setMotorDirection(OpeningDirection);
        setMotorSpeed(255); // set motor max speed
        motorRunning = true;
        motorOpening = true;
        sendToPC("HublotOpening");
      }
      else if (input == 2 && !closeSwitchReached) { //close
        brakeMotor(); // stop motor
        delay(100);
        setMotorDirection(ClosingDirection);
        setMotorSpeed(255); // set motor max speed
        motorRunning = true;
        motorOpening = false;
        sendToPC("HublotClosing");
      }
      else if (input == -2) { //get status
        if (openSwitchReached)
          sendToPC("HublotOpened");
        else if (closeSwitchReached)
          sendToPC("HublotClosed");
        else if (motorRunning && motorOpening)
          sendToPC("HublotOpening");
        else if (motorRunning && !motorOpening)
          sendToPC("HublotClosing");
        else if (!motorRunning)
          sendToPC("HublotNotMoving");
      }
      else if (input == -3) //Ping
        sendToPC("ArduinoHublot");
      else if (input == 0) { //Stop
        brakeMotor(); // set motor max speed
        motorRunning = false;
      }
      else {
        sendToPC("WTF");
        Serial.print(input);
      }
    }

    void loop() {

      openSwitchReached = (digitalRead(openSwitch) == HIGH);
      closeSwitchReached = (digitalRead(closeSwitch) == HIGH);

      if (openSwitchReached && motorRunning && motorOpening) {
        sendToPC("HublotOpened");
        brakeMotor();
        motorRunning = false;
        delay(200);
      }
      else if (closeSwitchReached && motorRunning && !motorOpening) {
        sendToPC("HublotClosed");
        brakeMotor();
        motorRunning = false;
      }

      if (Serial.available()) {
        int read = (Serial.readStringUntil(':')).toInt();
        handleSerialInput(read);
      }

    }

  [1]: https://www.arduino.cc/en/Main/ArduinoMotorShieldR3

body:
Add pulldown resistors (10KΩ) to any pins you want to force to be low at reset.

(Quite frankly I'm amazed they don't exist on all inputs to the board by default - it seems a bit of a fatal omission).


message:
How do I make specific tones with a piezo buzzer?

I am using a piezo buzzer and fiddling around with it a little bit. I currently have different tones with delays in between and I have to do a lot of trial and error for the piezo buzzer to play sounds like I want it to. Is there a better way to do this? because at this rate I will be stuck for a while.

I am trying to get the piezo buzzer to make the sound of an alarm. Any suggestion on how I can get it to sound exactly like an alarm or is trial and error the only way?

body:
It's very hard to know from your question what you are having trouble with.  I have a piano and I can hit the keys, but it takes me a long time to hit them in the right order and with the right timings to create a new symphony.

Anyway, if creating the sounds is the problem, have you looked at the [Tone library][1]?

Different alarms have different sounds.  I once heard an alarm which sounded like the start of [Fuer Elise][2], so probably the [notes][3] were `E` and `D#`.  That would make their [frequencies][4] about 330Hz and 311Hz:

    void loop()
    {
        tone(pin, 330, 250);
        delay(300);
        tone(pin, 311, 250);
        delay(300);
    }

The sound you [linked to][5] sounds to me like it starts on a C, and slides up gradually one octave.  One octave higher is double the frequency, so this code should do that:

    void loop()
    {
        const int startFreq = 523;  // C5 is 523Hz

        // Start at the given freqency, and increase gradually by
        // one octave (double the frequency)
        for (int freq=startFreq ; freq<= (startFreq*2) ; ++freq)
        {
            tone(pin, freq, 10);
            delay(3);
        }
    }

  [1]: https://www.arduino.cc/en/Reference/Tone
  [2]: https://www.youtube.com/watch?v=_mVW8tgGY_w
  [3]: http://makingmusicfun.net/images/thumbs/fur-elise.jpg
  [4]: http://www.phy.mtu.edu/~suits/notefreqs.html
  [5]: https://www.youtube.com/watch?v=lo4yJbjkMWA


message:
How to use a 4-pin ultrasonic sensor as a 3-pin ping sensor?

const int pingPin = A0;

    void loop() {
      long duration, inches, cm;
      pinMode(pingpin, OUTPUT);
      digitalWrite(pingPin, LOW);
      delayMicroseconds(2);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(5);
      digitalWrite(pingPin, LOW);
      pinMode(pingPin, INPUT);
      duration = pulseIn(pingPin, HIGH);
      inches = microsecondsToInches(duration);
      cm = microsecondsToCentimeters(duration);
      Serial.print(inches);
      Serial.print("in, ");
      Serial.print(cm);
      Serial.print("cm");
      Serial.println();
    }

How to change this code for a 4-pin ultrasonic sensor?

body:
The four pin `Echo)))` module is basically the same as three pin ones, except for triggering is done by another pin. So you don't have to care about setting pin to the output mode and switching it back to the input mode after the trigger pulse. You can read about it for example [here][1].

<!-- language: c++ -->

    const int8_t pingPin = A0;
    const int8_t trigPin = A1;

    void setup()
    {
      pinMode(pingPin, INPUT);
      pinMode(trigPin, OUTPUT);
    }

    void loop()
    {
      // pulse on trigger pin:
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10); // 10us is minimum trigger pulse duration
      digitalWrite(trigPin, LOW);

      // measure HIGH pulse duration:
      long duration = pulseIn(pingPin, HIGH);

      // and rest of the code:
      long   inches = microsecondsToInches(duration);
      long       cm = microsecondsToCentimeters(duration);

      Serial.print(inches);
      Serial.print("in, ");
      Serial.print(cm);
      Serial.print("cm");
      Serial.println();
    }

  [1]: https://alselectro.wordpress.com/tag/ultrasonic-sensors/


message:
Arduino Mega external interrupts fire randomly

I'm trying to solve a nagging issue with external interrupts - this is for a slot car track lap count controller. It uses the Mega's 6 external interrupt lines connected to photo diodes. The HW itself works fine - yes, trust me, it's fantastic.

I have observed the following. The code in the loop() is surrounded with:

    detachAllInterrupts();
    delay(10);
    ...
    ... process any interrupts and/or button presses
    ...
    delay(10);
    attachAllInterrupts();

If I omit or reduce the delay amount the random firing gets worse.

The ISR is lean and mean:

    void lapDetected1() {
      lane1.lapDetected();
    }

calling the method of class Lane:

        void lapDetected() { // called by ISR, short and sweet
          now = millis();
          if ((now - finish) < laneProtectionTime) {
            return;
          }
          start = finish;
          finish = now;
          count++;
          reported = false;
        }

all the variables used are declared *volatile*.

I don't *like* to use delay and I'm seeking advice on how to correctly implement ISRs and their handling.

here's the link to the entire code on GitHub: https://github.com/gabe2001/PCLapCounterWithArduino/

Thanks for any advice I can get here!
-gabe

body:
Now, you write the following:

    detachAllInterrupts();
    delay(10);
    ...
    ... process any interrupts and/or button presses
    ...
    delay(10);
    attachAllInterrupts();

I understand that you put this stuff into the loop, such that the loop in effect looks like this:

    void loop() {
        detachAllInterrupts();
        delay(10);
        ...
        ... process any interrupts and/or button presses
        ...
        delay(10);
        attachAllInterrupts();
    }

Assuming that the above is correct, then you will be enabling and disabling your interrupts in one long stream. You would often NOT disable your interrupts, because you don't know when the are available or not, then.

You should typically ENABLE the interrupts in the startup code, and then in the `loop()` you can have any Other processing you want, but not any processing referring to the interrupt processing.

The interrupt processing would take care of the button pressed etc. So - in the `lane.lapdetected1()` algorithm, you would take care of reading buttons pressed etc., and, you would have to attach the interrupt itself directly to your algorithm. I cannot see that you have told that when an interrupt has been happening, then the code execution goes to the ISR `lane.lapdetected1()` algorithm?

What you would want to do, is to setup an interrupt in the `setup()`, which is run once upon start of the program in the arduino, and then, providing that you want the interrupt on pin 2 (external pin), and the algorithm to run while you receive falling signals on the pin 2 is lapdetected1, then you could use the following:

    void setup() {
      attachInterrupt(digitalPinToInterrupt(2), lapdetected1, FALLING);
    }

Thereby you would remove the `detachAllInterrupts()`, and all the way down to `attachAllInterrupts()` from the loop construction and thereby you would be able now to process interrupts within the lapdetected1-algorithm and run what ever you would want to run, normally, from within the loop-construction.


body:
> The code in the loop() is surrounded with:

it doesn't make much sense for you to "process the interrupts" in the loop(). Use ISR instead.


message:
I have a diagram of my Arduino circuit. How do get it ready for PCB manufacture?

For my engineering class, I am building a digital scale. My team has assembled the prototype out of:

 - Arduino Uno
 - Hx711 amplifier module
 - 1 kg load cell
 - 2 push buttons
 - A 4 digit 7-segment display module we found online, but we don't know its specific name
 - HC-05 Bluetooth module, no specific manufacturer
 - Lilypad switch CR2032 battery module
 - DC-DC step up to 5V boost converter module

Our prototype works. Well, sort of (we're still trying to work out the boost converter and c2032 to work). We have diagrammed how each module connects to each other on a piece of paper. However, we want to properly diagram this in a way so we can create a PCB for it.

I have tried the Eagle and Fritzing programs. I am very inexperienced with them. I am not able to find the HC-05 and LED display .sch or .fzz files online for this, so I have came to a halt. I am not sure how each of these modules are actually wired together either.

What can I do next?

body:
You can find the parts on [fritzing.org][1]. Anyway. You can get rid of some parts and save money if you pick the right ones. Instead of an Arduino Uno take an [Arduino Pro Mini][2] with 3.3V and [HC-05][3] without a breakout for 5V Arduinos.

Doing that everything will smaller and running on 3.3V thus getting rid of the DC-DC converter.

  [1]: http://forum.fritzing.org/c/parts-submit
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardProMini
  [3]: http://forum.fritzing.org/t/hc-05-custom-board/2443


body:
You can try to implement the circuit without an Arduino board [on a breadboard][1]. So you can get more information about what works and what not. From there after making necessary changes (if there is any), you can draw the schematics and create a PCB layout using Orcad, Eagle etc.There are a lot of tutorials out there about PCB designing.

  [1]: https://www.arduino.cc/en/Main/Standalone


message:
Using rotary encoders with pin change interrupts

I'm using an Arduino Uno and two (3-pin) rotary encoders for a project. Since the loop takes a bit long and accuracy is important, I'd like to use interrupts to read the values from the rotary encoders. Also, pins 2 and 3 are occupied so I can't use hardware interrupts.

I'm using the Rotary library ([github link][1]) for the rotary encoders and the EnableInterrupt library ([github link][2]) for external interrupts. The Rotary library includes an interrupt example, but I couldn't manage to modify it to work with pin change interrupts. This is my current state (test code):

    #include <EnableInterrupt.h>
    #include <Rotary.h>

    Rotary r = Rotary(2, 3);

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

      /* Original interrupt setup:
      PCICR |= (1 << PCIE2);
      PCMSK2 |= (1 << PCINT18) | (1 << PCINT19);
      sei();
      */

      enableInterrupt(2, interruptFunction, CHANGE);
      enableInterrupt(3, interruptFunction, CHANGE);
    }

    void loop() {

    }

    void interruptFunction() {

      Serial.println("Int. called");

      unsigned char result = r.process();
      if (result == DIR_NONE) {
        // do nothing
      }
      else if (result == DIR_CW) {
        Serial.println("ClockWise");
      }
      else if (result == DIR_CCW) {
        Serial.println("CounterClockWise");
      }
    }

Everytime I turn the encoder for one step, the interruptFunction gets called a bunch of times (about 2~4) but the r.process() call never returns a value.

My current guess is that this has something to do with the rotary encoder outputting gray code, but I'm not quite sure how my approach differs from the Rotary interrupt example using hardware interrupts.

Hope you can help!

  [1]: https://github.com/brianlow/Rotary
  [2]: https://github.com/GreyGnome/EnableInterrupt

body:
I too had this problem. I chased my tail in SW for hours. I was making the ISRs non-reentrant (assumed they accidentally were), I was doing SW debouncing etc. I even looked at the signal on a scope but did not see any significant bounces.
I eventually added 0.1uF capacitors to the inputs and that solved all my problems with the ISR.
So don't trust the encoder manufacturers, there WILL be signal bounce and your Arduino WILL detect it and throw multiple interrupts.
Good luck with your project!
LDP


body:
> Everytime I turn the encoder for one step, the interruptFunction gets
> called a bunch of times (about 2~4)

This is due to contact bounces. You should either implement a hardware debouncing circuit (a simple R-C filter could be enough. Do not connect instead large capacitors directly in parallel to your contacts, as when the contact closes, the energy stored on the capacitor will damage over time the contacts. Using large capacitances on an input can also lead to problems when power is removed), or better a good software debouncing strategy.

For instance, when the interrupt is called the first time, disable the pin-change interrupts. Then set up a timer, which will trigger an interrupt when it expires (the time should be larger than the bounce time, usually several ms or more). Then in the timer interrupt, first put your code:

      unsigned char result = r.process();
      if (result == DIR_NONE) {
        // do nothing
      }
      else if (result == DIR_CW) {
        Serial.println("ClockWise");
      }
      else if (result == DIR_CCW) {
        Serial.println("CounterClockWise");
      }

end re-enable the pin-change interrupts.

      enableInterrupt(2, interruptFunction, CHANGE);
      enableInterrupt(3, interruptFunction, CHANGE);

> but the r.process() call never returns a value.

r.process() will ALWAYS returns a value. Maybe you did mean that it returns DIR_NONE ?


body:
check the library to see if it debounces the input.

if not, write your own code. usually state machine-based approaches are very resistant to switch bounces.


body:
Code Correction 7th October - Tidy code as per comments
Code Correction 7th October - proper reading of rotary encoder

 Uses the Pin Change interrupts to allow increment and decrement of the 2 rotary encoders within an interrupt service routine using arduino (in my case nano) with ATMEGA328P chip. Need to add 2 x 104 (0.1uF caps) at the rotary encoder between each pin and the centre ground pin to stop the debounce, doesnt work without the capacitors added. Does not need any library. Watched the Tutorial: Pin Change Interrupts on the Arduino by makecourse which helped understand the Pin change interrupts, will help to watch this if have a different version of arduino so know what digital pins relate to what interrupts.

              //*******************************************  rotary encoder ************************************************************
              #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))    //shortcut way to clear a bit in a register
              #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))     //shortcut way to set a bit in a register

              #define Encoder1pin 3 //corresponds to PCINT19
              #define Encoder2pin 4 //corresponds to PCINT20
              #define Encoder3pin 5 //corresponds to PCINT21
              #define Encoder4pin 6 //corresponds to PCINT22
              #define Encoder5pin 7 //corresponds to PCINT23

              unsigned long encoderPos1 = 100;
              unsigned long oldEncPos1 = 0;
              unsigned long encoderPos2 = 100; //this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
              unsigned long oldEncPos2 = 0; //stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)

              volatile byte portDstatus;

              volatile bool readingEncoder1pin = 0;
              volatile bool readingEncoder2pin = 0;
              volatile bool readingEncoder3pin = 0;
              volatile bool readingEncoder4pin = 0;
              volatile bool lastreadingEncoder1pin = 0;
              volatile bool lastreadingEncoder2pin = 0;
              volatile bool lastreadingEncoder3pin = 0;
              volatile bool lastreadingEncoder4pin = 0;

              void setup() {

                Serial.begin(9600);

              //*************************************************** rotary encoder ******************************************************************************
                pinMode(Encoder1pin, INPUT);//define pin as INPUT
                digitalWrite(Encoder1pin, HIGH);//connect the internal pull-up resistor - this will yield a HIGH readout if the switch is open.
                pinMode(Encoder2pin, INPUT);
                digitalWrite(Encoder2pin, HIGH);
                pinMode(Encoder3pin, INPUT);
                digitalWrite(Encoder3pin, HIGH);
                pinMode(Encoder4pin, INPUT);
                digitalWrite(Encoder4pin, HIGH);
                pinMode(Encoder5pin, INPUT);
                digitalWrite(Encoder5pin, HIGH);

                //setting up the interrupt pins:   //I needed to set all of these otherwise the serial monitor does not read the byte correctly -
                                                   // and it doesnt work.

                sbi (PCICR, PCIE2); // enable interrupt PCI2);
                sbi (PCMSK2,PCINT23); // set the interrupt control bits for pins 7-3. These bits control whether the pins can trigger the interrupt or not.
                sbi (PCMSK2, PCINT22);
                sbi (PCMSK2, PCINT21);
                sbi (PCMSK2, PCINT20);
                sbi (PCMSK2, PCINT19); // we do not want to set interrupt control for pins 0 or 1 since this is serial reading .

              //******************************************************************* LED *********************************************************************
              }

              void loop()

                  {
                   }

              ISR(PCINT2_vect) // Interrupt Service Routine. This code is executed when a state change occurs on a pin
              {

                    portDstatus=PIND;
                   readingEncoder1pin = bitRead(portDstatus,3);
                   readingEncoder2pin = bitRead(portDstatus,4);
                 if(lastreadingEncoder1pin == 1 && lastreadingEncoder2pin == 0 && readingEncoder1pin == 1 && readingEncoder2pin == 1)
                  {
                      encoderPos1 ++;
                       lastreadingEncoder1pin = readingEncoder1pin;
                       lastreadingEncoder2pin = readingEncoder2pin;
                  }

                  else if(lastreadingEncoder1pin == 0 && lastreadingEncoder2pin == 1 && readingEncoder1pin == 1 && readingEncoder2pin == 1)
                  {
                    encoderPos1 --;
                      lastreadingEncoder1pin = readingEncoder1pin;
                      lastreadingEncoder2pin = readingEncoder2pin;;
                  }
                  else
                    {
                       lastreadingEncoder1pin = readingEncoder1pin;
                       lastreadingEncoder2pin = readingEncoder2pin;
                    }

        //  reading the second encoder:

                   readingEncoder3pin = bitRead(portDstatus,5);
                   readingEncoder4pin = bitRead(portDstatus,6);

                 if(lastreadingEncoder3pin == 1 && lastreadingEncoder4pin == 0 && readingEncoder3pin == 1 && readingEncoder4pin == 1)
                  {

                      encoderPos2 ++;
                       lastreadingEncoder3pin = readingEncoder3pin;
                       lastreadingEncoder4pin = readingEncoder4pin;
                  }

                  else if(lastreadingEncoder3pin == 0 && lastreadingEncoder4pin == 1  && readingEncoder3pin == 1 && readingEncoder4pin == 1)
                  {
                    encoderPos2 --;
                      lastreadingEncoder3pin = readingEncoder3pin;
                      lastreadingEncoder4pin = readingEncoder4pin;;
                  }
                  else
                    {

                       lastreadingEncoder3pin = readingEncoder3pin;
                       lastreadingEncoder4pin = readingEncoder4pin;
                    }
                 // serial print for testing only then remove from ISR
              Serial.print(encoderPos1);
              Serial.println(encoderPos2);

                 }


message:
Trying to understand interaction of interrupts, noInterrupts and delays

I'm having trouble understanding how to activate interrupts so that they operate only when they should. With this code, I seem to get erratic performance when I either attach or unattached interrupts, or when I try using noInterrupts.
What I am trying to accomplish is to deactivate the alarm function from running until a slight delay is initiated upon hitting an incorrect key. That would allow leaving the premises without triggering the interrupt. Does noInterrupt only affect the function in which it is placed??

    ///////////////////////// initialize & includes //////////////////////////
    #include "SIM900.h"
    #include "sms.h"
    #include "Keypad.h"
    #include <GSM.h>
    SMSGSM sms;
    //To change pins for Software Serial, use the two lines in GSM.cpp.
    int PIR_SensorPin = 2;
    int LED_OutPin = 11; //green
    int Alarm_OutPin = 12; //red
    int alarm_count = 0;
    volatile boolean trigsensor = false;
    boolean away = false;
    const byte interruptPin = 2;
    int z = 0;
    int i = 0;
    int timeout = 10000;

    //////////////////////////// setup keyPad //////////////////////////
    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    char keys[ROWS][COLS] =
    {
      {
        '1', '2', '3', 'A'
      }
      ,
      {
        '4', '5', '6', 'B'
      }
      ,
      {
        '7', '8', '9', 'C'
      }
      ,
      {
        '*', '0', '#', 'D'
      }
    };
    byte rowPins[ROWS] = {
      6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
    }; // connect to the row pinouts of the keypad
    byte colPins[COLS] = {
      3, A0, A1, A4
    }; // connect to the column pinouts of the keypad
    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    const char PIN[5] = {
      '9', '6', '7', '9', '#'
    }; // PIN number
    char key_input[5] = {
      0, 0, 0, 0, 0
    }; // used for comparison

    //////////////////////////////// setup ///////////////////////////////////
    void setup() {
      Serial.begin (9600);  // Establish Serial connection;
      pinMode (LED_OutPin, OUTPUT);   // Set pinMode.
      pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
      pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
      digitalWrite (LED_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (PIR_SensorPin, LOW);
      Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
      if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
        Serial.println ("Status = Network READY");
        digitalWrite (LED_OutPin, HIGH);
      }
      attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // PIR as interrupt
      Serial.println ("System Ready");
    }

    //////////////////////////////// void loop ///////////////////////////////////
    void loop()
    {
      readKeypad(); // Serial.println ("at keypad");
      if (trigsensor == true) {
        alarm ();
      }
    }

    ///////////////////////////// void trigger ///////////////////////////////////
    void trigger() {
      trigsensor = true;
      alarm();
    }

    //////////////////////////////// void alarm ///////////////////////////////////
    void alarm() {
      Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("trigsensor="); Serial.println (trigsensor);
      Serial.println ("at Alarm");
      if (away == true && trigsensor == true) {
        noInterrupts();////////////////////////////////
        // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
        Serial.println ("MOTION detected: SMS Sent");
        for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
          digitalWrite (Alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
          digitalWrite (Alarm_OutPin, LOW); delay (500);
          digitalWrite (LED_OutPin, HIGH); // delay (1000);
          //   digitalWrite (LED_OutPin, LOW); delay (1000);// End by turning off light
          Serial.println (alarm_count);
        }
      }
      trigsensor = false;
      readKeypad();
    }

    //////////////////////////////// read Keypad ///////////////////////////////////
    void readKeypad() {
      char key = keypad.getKey();
      if (key != NO_KEY) { // if a keypad input
        key_input[z] = key;
        tone(10, 900, 100);
        Serial.print ("Key_input["); Serial.print(z); Serial.print ("] = "); Serial.println(key);
        z++;
        if (z >= sizeof(key_input)) {
          z = 0;
        }
        switch (key) {
          case '*': // resets key_inputs to "0"
            z = 0;
            break;
          case '#': // pressed to "enter"
            z = 0;
            for ( i = 0;   i < 4 ;  i++ ) {
              Serial.print(key_input[i]);
            }
            Serial.println ("-------");
            delay(100); // for extra de-bounce
            checkPIN();
            break;
        }
      }
    }

    //////////////////////////////// check PIN ///////////////////////////////////
    void checkPIN() {
      Serial.println ("@ checkPIN ");
      int correct = 0;
      int i;
      for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
        if (key_input[i] == PIN[i]) {
          correct++;
        }
      }
      if (correct >= sizeof(PIN) - 1) {
        Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
        correctPIN();
      }
      else {
        incorrectPIN();
      }
    }

    //////////////////////////////// correct PIN ///////////////////////////////////
    void correctPIN() {              // do this if correct PIN entered
      Serial.println ("@ correct PIN ");
      digitalWrite (LED_OutPin, HIGH);
      digitalWrite (LED_OutPin, LOW);
      trigsensor = false;
      away = false;
      readKeypad();
    }

    ///////////////////////////// incorrect PIN ///////////////////////////////////
    void incorrectPIN() {           // do this if incorrect PIN entered
      noInterrupts();
      Serial.println ("@ incorrect PIN ");
      //detachInterrupt(0); Serial.println ("interrupt off 1");
      trigsensor = false;
      away = true;
      digitalWrite (LED_OutPin, HIGH);
      delay(timeout);
      attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); Serial.println ("interrupt on 2");
      alarm(); Serial.println ("here");
    }

body:
Well, yes, I think attaching and detaching interrupts isn't really something that you should do to often. It also won't really make your code very much more readable.

You may have a look at programming (embedded systems) in general. A technique I like to do is making a (non-blocking) state machine. In this way you don't even need interrupts (you can actually have interrupts if you want, though).

Also, it may be worth noting that making your code more readable and understandable is likely going to improve your "idea of what is going on" and thus improve it's reliability. This is commonly done by designing and applying "scope" to your code. You've done well on the keypad functions, giving them a sane name and reasoning. You could've put them in a class, but that's not where the errors are at.

Basically, your alarm has a few states:

 - Armed
 - Unarmed
 - Alarm!
 - Just activated

From these, you can form a state diagram.
Usually, "events" lead to the state of your system being changed.
For example:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/ovRMM.png)

<!-- End schematic -->

(Sorry for "abusing" the schematic editor (:  )
As you can see, events can be user interaction/sensors/timing, basically anything.

By designing your code in a state diagram, you get an idea of what you want your machine to do, at what moment. And what other states it can go to from there (and when/how).

Your code will become something along the lines of:

setup

    enum STATE{
      armed,
      unarmed,
      justActivated,
      alarm
    };

    STATE systemState = unarmed;
    long timeGettingArmed;

loop

    switch(systemState){
       case armed:
       if(breakinSensor.check() == HIGH){
          systemState = alarm;
       }else if(keyPad.check() == deactivated){
          systemState = unarmed;
       }
       break;
       case unarmed:
       if(armButton.check() == HIGH){
          timeGettingArmed = millis(); // Or you could just do a delay here.
          systemState = justActivated;
       }
       break;
       case justActivated:
       if(timeGettingArmed + waitTime < millis()){
         systemState = armed;
       }
       break;
       case alarm:
       if(keyPad.check() == deactivated){
         systemState = unarmed;
       }else{
         beep();
       }
       break;
    }

Ofcourse you'll have to highly adapt this code to suit your needs, I doubt it will even compile. But it can also be a part of designing your program, try just writing it out in words (or explaining it to someone), before you program it.

*You could make use of the interrupts by checking in the interrupt if the state is "armed" and then setting the state to "alarm". This way you avoid the interrupt messing up any of your logic and having to disable it.

The cool thing of this "non-blocking" (if you don't use delays) state machine is that you can actually add more statemachines to it, and it will seem like the processor does everything at the same time. This is because it skips rather fast through the "i/o checks".


message:
Running Multiple Languages on Arduino

This is mostly a conceptual question. Is it possible to have two scripts running on an Arduino, where one is a Julia script, and one is a Python script or something like that?

body:
Basically no, because you can't run either Julia *or* Python, let alone both together.

Bear in mind also what an Arduino is (what most of them are, anyway): a low (computational) power microprocessor with a tiny amount of RAM. No operating system, no multi-tasking. Not in the same league as, for example, a Raspberry Pi.


message:
Initially my Arduino executes a series of PWM signals simultaneously, but after some iterations it adds around a second between PWM executions

I am using 2 adafruit PWM servo shield in order to generate 25 PWM signals. In particular I am using this shield: https://www.adafruit.com/products/1411

A python script sends the commands to the Arduino (Mega 2560) through pyserial. The commands are like "A0 P1 S500\n". Each argument separated by a space. The first chooses the shield, the second one the pin, and the third one the speed.

The code running in the Arduino is as follows:

    #include <Adafruit_PWMServoDriver.h>

    #define BUFFER_SIZE 200

    // Init both adafruit boards
    Adafruit_PWMServoDriver pwm0 = Adafruit_PWMServoDriver(0x40);
    Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x41);

    int read_command(char *buffer)
    {

     static int pos = 0;
     int rpos;

     if (Serial.available() > 0) {
      Serial.println(Serial.available());
      char readch = Serial.read();

      switch (readch) {

       case '\n':
        rpos = pos;
        pos = 0; // Reset position index ready for next time
        Serial.println(buffer);
        return rpos;

       default:

        if (pos < BUFFER_SIZE -1) {
         buffer[pos++] = readch;
         buffer[pos] = '\0';
        } else {
         Serial.println("666"); //buffer overflow
        }
      }
     }
     // no end line or char found, return -1
     return -1;

    }

    void parse_command(char* command)
    {

     char* parameter;
     parameter = strtok(command, " ");
     long shield, pin, speed;

     while (parameter != NULL) {

      switch(parameter[0]) {

       case 'A':
        shield = strtol(parameter+1, NULL, 10);
        break;

       case 'P':
        pin = strtol(parameter+1, NULL, 10);
        break;

       case 'S':
        speed = strtol(parameter+1, NULL, 10);
        break;

      }
      parameter = strtok(NULL, " ");
     }

     for (int x=0; x < BUFFER_SIZE; x++)
      command[x] = '\0';

      if (shield == 0)
        pwm0.setPWM(pin, 0, speed);

      if (shield == 1)
        pwm1.setPWM(pin, 0, speed);

    }

    void setup()
    {

      Serial.begin(9600);
      Serial.flush();

      pwm0.begin();
      pwm0.setPWMFreq(100);  //Max is 1600, Kevin was using 1000
      pwm1.begin();
      pwm1.setPWMFreq(100);

    }

    void loop()
    {

      static char buffer[BUFFER_SIZE];

      if (read_command(buffer) > 0)
        parse_command(buffer);

    }

As said, I am sending the commands from a Python script, where for example I have a function called "activate all", that will send 25 commands like "A0 P1 S500\n" (obviously with different values after the A and the P) to the serial port. I also have a function called "disable all", which is very similar to the previous command, but setting the S to 0 so like "A0 P1 S0\n".

So, as I start the serial communication, if I execute from Python "activate_all", I can how all the PWM signals are generated at the same time. I know it is actually 1 by 1, but it is fast enough to seem simultaneously to the human eye. If I then send a disable_all, I can see how all the PWM signals are set to 0 at the same time.

This works as expected for a while, but after some point, when I send an activate_all, it will indeed activate all of them, but it activates each PWM signal one by one, with a delay of around 1 second between activations (so you can clearly see them going one by one), and a very similar effect when disabling them all. From this point on, which seems slightly different each time, every time I want to activate more than one pwm signal at the same time, it will add this 1s delay between activations.

The only way I have to fix this is to send from the python a "flush()". which seems to be fix it. Doing flushes from the Arduino code, like when for example serial.available is 0, doesnt seem to fix it.

I don't know what exactly I am doing wrong. I guess the way I am handling the communication buffer is wrong, but I haven't seen where my mistake is.

A very similar code to the one pasted here was used in another project, in that case it was interfaced with Labview, and in that case everything seem fine.

In case you wonder about the code running in the Python script, it is like this:

    import serial, time, json

    class BZBoard:

        def __init__(self, port):

            self.ser = serial.Serial(port, 9600, timeout=120)
            time.sleep(2) # serial docs recommend a wait just after connection
            self.ser.flush(); self.ser.flushInput(); self.ser.flushOutput();

            self.motors = {
                just naming the pins
                }

        def __del__(self):

            self.disable_all()
            self.ser.close()
            del self.ser

        def close(self):

            self.disable_all()
            self.ser.close()
            del self.ser

        def activate_motor(self, motor_code, speed=300):
            ''' code as in A1 or C2 as marked in the actual board. See the dict motors'''

            shield, pin = self.motors[motor_code]
            command = "A%d P%d S%d\n" % ( shield, pin, speed )
            self.ser.write(command.encode())

        def activate_all(self, speed=300):

            for key in self.motors.keys():
                self.activate_motor(key, speed)

        def disable_motor(self, motor_code):

            shield, pin = self.motors[motor_code]
            command = "A%d P%d S0\n" % ( shield, pin )
            self.ser.write(command.encode())

        def disable_all(self):

            for key in self.motors.keys():
                self.disable_motor(key)

    if __name__ == "__main__":

        board = BZBoard("/dev/ttyACM0")

So the user will do for example a lopp that repeats itself 20 times, where it will activate_all, wait 1 second, disable_all, wait 1 second. The first 10 iterations or so, everything will be fine and the PWM are generated all of them at the same time (with respect to the human eye), but after that, the PWM signals are generated 1 by 1, with a delay of 1s or so between them.

body:
There seems to be reason to think about filled buffers causing stalls and timeouts, but comments regarding 5-second sleeps between trials seem to rule that out.  To debug what's actually happening, you might blink an LED each time you receive a character, and another LED each time you call your `parse_command()` routine; and if you have an oscilloscope, look at the serial transmissions back and forth to see whether delay is due to something at the Arduino end vs at the host end.

That said, I think it would make sense to simplify the protocol by getting rid of your input buffer and just processing input as it comes.  For example, you could use the following letters as post-fix actions.

    A  Select shield 1
    B  Select shield 2
    P  Set pin number, eg 11P selects pin 11
    S  Set speed, eg 472S sets speed to 472
    N  Send current speed to current pin, then increment pin number

For example, the command sequence for “disable_all” could look like:

    0S0PANNNNNNNNNNNN 0PBNNNNNNNNNNNNN

This is easy to parse on the fly; declare `int val=0` and any other needed variables before `loop()`, then within `loop()` say:

      char inc;   // For incoming character
      while (Serial.available()) { // Get characters
        inc = Serial.read();
        if (inc >= '0' && inc <= '9') {
          val = 10*val + (inc-'0');
        } else {
          switch (toupper(inc)) {
          case 'A':
            board = 0;
            break;
          case 'B':
            board = 1;
            break;
          case 'P':
            pin = val;
            break;
          case 'S':
            speed = val;
            break;
          case 'N':
            if (PinNumberIsOk(board, pin))
              pwm[board].setPWM(pin, 0, speed);
            ++pin;
            break;
          default :
            ; // handle blanks, returns, whatever
          }
          val = 0;  // Set val to zero on any non-digit
        }

As another example, the sequence `4PA 11SN13SN17SN` would send speeds 11, 13, and 17, respectively, to motors 4, 5, 6 on the first shield.


message:
RTL8170 Web Server - client unable to connect

RTL8170 is a new module, which is in many ways better than the old ESP8266 module. We are able to flash this module with Arduino using an Ameba Writer, and it should be able to support any code that is supported by the ESP (with some adjustments). It has been officially supported by Realtek's environment but it does not use all the GPIO (only 2). Luckily, pvvx developed an environment for Arduino IDE, which we can install and use through this tutorial: https://hackaday.io/project/19163/logs

I have uploaded a modified SimpleWebServerWiFi sketch from Ameba RTL8170 examples by both trying the official Realtek and pvvx's environments, and using LEDs to troubleshoot (I don't have an SPI/I2C LCD or a Serial-to-USB) I found the module being able to connect to my Samsung's hotspot but unable to communicate with the module because server.available() never turns true. When my module connects to my Samsung Note 4's hotspot, I see its IP (192.168.43.123) and fail to connect to it via a browser (on the phone or with a Windows laptop). Android port scanning apps indicate that the target IP address of the module has no open ports. Code below.

Update2: I've made adjustments to the code according to suggestions, but it still didn't respond. Updated code below:

       /*-----------------------------------------------------------------|
      |  Build using pvvx's enviroment: https://github.com/pvvx/RtlDuino  |
      |  Tutorial: https://hackaday.io/project/19163/logs                 |
      |=================================================================*/

    #include <WiFi.h>

    char ssid[] = "WiFi_SSID";      //  your network SSID (name)
    char pass[] = "password";   // your network password
    int keyIndex = 0;   // your network key Index number (needed only for WEP)
    String currentLine = "";   // make a String to hold incoming data from the client

    int status = WL_IDLE_STATUS;
    WiFiServer server(80);

    void setup() {
      pinMode(1,OUTPUT);

      //Serial.begin(38400);      // initialize serial communication
      pinMode(LED_BUILTIN, OUTPUT);      // set the LED pin mode
      // check for the presence of the shield:
      if (WiFi.status() == WL_NO_SHIELD) {
        //Serial.println("WiFi shield not present");
        while (true); // don't continue
      }
      String fv = WiFi.firmwareVersion();
      if (fv != "1.1.0") {
        //Serial.println("Please upgrade the firmware");
      }

      // attempt to connect to Wifi network:
      while (status != WL_CONNECTED) {
        //Serial.print("Attempting to connect to Network named: ");
        //Serial.println(ssid);         // print the network name (SSID);

        // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
        status = WiFi.begin(ssid, pass);
        // wait 0.2 seconds for connection:
        delay(200);
      }

      server.begin();                   // start the web server on port 80

    }

    void loop() {

      WiFiClient client = server.available();   // listen for incoming clients

      if (client) {                             // if you get a client,

        //Serial.println("new client");           // print a message out the serial port
        while (client.connected()) {            // loop while the client's connected

          if (client.available()) {             // if there's bytes to read from the client,

            char c = client.read();             // read a byte, then
            //Serial.write(c);                    // print it out the serial monitor
            if (c == '\n') {                    // if the byte is a newline character

              // if the current line is blank, you got two newline characters in a row.
              // that's the end of the client HTTP request, so send a response:
              if (currentLine.length() == 0) {

                // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
                // and a content-type so the client knows what's coming, then a blank line:
                client.println("HTTP/1.1 200 OK");
                client.println("Content-Length: 88");
                client.println("Content-Type: text/html");
                client.println("Connection: Closed");
                client.println();

                // the content of the HTTP response follows the header:
                client.print("Click here turn the BUILTIN_LED on
");
                client.print("Click here turn the BUILTIN_LED off
");

                // The HTTP response ends with another blank line:
                client.println();
                // break out of the while loop:
                //break;
              } else {    // if you got a newline, then clear currentLine:
                //digitalWrite(1,HIGH); // Doesn't turn ON
                currentLine = "";
              }
            } else if (c != '\r') {  // if you got anything else but a carriage return character,
              //digitalWrite(1,HIGH); // Turns ON
              currentLine += c;      // add it to the end of the currentLine
            }
            //digitalWrite(1,HIGH); // Turns ON
            // Check to see if the client request was "GET /H" or "GET /L":
            if (currentLine.endsWith("GET /H")) {
              digitalWrite(LED_BUILTIN, HIGH);               // GET /H turns the LED on
            }
            if (currentLine.endsWith("GET /L")) {
              digitalWrite(LED_BUILTIN, LOW);                // GET /L turns the LED off
            }
          }
        }
        //digitalWrite(1,HIGH); // Turns ON
        // close the connection:
        client.stop();
      }
    }

**Update 1:**

I am still unable to fix the code. If no one can fix this code, please feel free to provide a totally new code.

P.S.: If this question keeps stagnating, I'll remove it and recreate it.

Any help is appreciated. Thank you!

body:
Inside the while loop, where you give the link to click you have a break that prevents the handling of the answer from the client.

I would reconsider the use of that break and structure the code to not use it at all.


body:
If you must use `String`, get its declaration out of `loop()`. You're only fragmenting your heap and reducing available RAM. Instead, declare it in the file scope and reserve sufficient space for a request line with the `reserve()` method in your `setup()`.

Though response headers are supposed to be case-insensitive, it's still a good idea to follow the 'standard', spaces and all, like this for instance:

    HTTP/1.1 200 OK
    Content-Length: 88
    Content-Type: text/html
    Connection: Closed

Try sending all the fields above, especially the content length. And get rid of the `break` like mico said. There's no way your builtin LED will turn on or off if you keep breaking right after you respond to the client.


message:
How to send command from coordinator to router in Xbee?

I am using an XBee-PRO S2b module. I have sent data from the router Xbee to the coordinator Xbee.

Now I want to send a command packet from the coordinator to the router Xbee to set a pin high.

My coordinator is in API mode and the router is in AT mode.

Can anyone say how to do that?

body: In order to change the router from the coordinator, you have to create a function that run in a microcontroller that is connected to the coordinator.You can refer to this link , https://www.youtube.com/watch?v=CzH146rR-7I&t=236s


message:
How do I check if a password is right? (keypad input)

Im having a problem with my arduino code.Im trying to make an alarm system with a pir sensor.So when the pir activates and the buzzer starts buzzing i want to be able to type a set password in the keypad and the buzzer should stop buzzing. since my passcode is 4-digit (1331) I wrote this code, but it`s not working.

     while(i<=4,i++)
    {
    char key = keypad.getKey();

    pass.append(key);
    }
    if(pass.evaluate())
    {
      digitalWrite(buzzer, LOW);
        keypad.waitForKey();
        delay(6000);
    }
My idea is that the program checks 4 times for the pressed key and adds it to the guessed password (im using the password library and the password is defined as well as int i=0;)
But for some reason when I type 1331 the buzzing continues. Please help me with that project and excuse my grammar, English is not my native language.

edit:
the full code:

    #include <Password.h>
    Password pass = Password( "1331" );

    #include <Keypad.h>
    int sensor = 11;
    int buzzer = 10;
    int i = 0;

    const byte rows = 4; //four rows
    const byte cols = 4; //four columns
    char keys[rows][cols] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'*','0','#','D'}
    };

    byte rowPins[rows] = {8, 7, 6, 9}; //connect to the row pinouts of the keypad
    byte colPins[cols] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

    void setup() {
    pinMode(sensor, INPUT);
    pinMode (buzzer, OUTPUT);
    digitalWrite(buzzer,HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
    delay(125);
    digitalWrite(buzzer,HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
    delay(125);
    digitalWrite(buzzer,HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
    keypad.waitForKey();
    digitalWrite(buzzer,HIGH);
      delay(125);
      digitalWrite(buzzer, LOW);
      delay(6000);

    }

    void loop() {

      char state = digitalRead(sensor);
      if (state == HIGH)
      {
        digitalWrite(buzzer, HIGH);
        while(i<4,i++)
        {
        char key = keypad.getKey();
        //keypad.waitForKey(); not sure if i should use that

        pass.append(key);
        }
        if(pass.evaluate())
        {
          digitalWrite(buzzer, LOW);
            keypad.waitForKey();
            delay(6000);
        }

      }
          }

body:
 1. Without knowing how the pass.* works, it will be impossible to pinpoint the problem.
 2. 'key' gets an ASCII value. Is that would you are expecting?
 3. Does pass.* reset (start over) once 4 digits?
 4. Just a guess, but I believe that *.waitForKey() does not consume the key.
 5. The algorithm only *gets* the key four times; then, it checks.


body:
This is classical indexing problem:

while with <= 4 actually runs five (5) rounds.

So, use < 4.


body:
This is completely the wrong way of doing a loop. Since Arduino uses C++ I made this test program:

    #include <stdio.h>

    int main (void)
      {
      printf ("starting\n");
      int i = 0;
      while(i<=4,i++)
         {
         printf ("%i\n", i);
         }
      printf ("done\n");
      return 0;
      }

This prints:

    starting
    done

Note that the loop is executed **zero** times. This is because you used the "comma operator".

From https://en.wikipedia.org/wiki/Comma_operator you can see:

> In the C and C++ programming languages, the **comma operator** (represented by the token `,`) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

In other words, your loop adds one to `i` and checks if it is zero (before adding one). Thus the loop terminates immediately.

A better construct would be:

    for (i = 0; i < 4; i++)
       {
       // whatever
       }

That is the standard C/C++ way of doing a loop a fixed number of times.

---

Also, most keypad libraries return `NO_KEY` if the user hasn't pressed a key.

You should test if `keypad.getKey()` returns `NO_KEY` and if so do nothing.

All your code would have done (if it had executed 4 times) was get 4 times `NO_KEY` (in a few microseconds) which would not be the correct password.


body:
In case anyone was wondering, heres the code I came up with and now it works.

    #include <Keypad.h>
    int sensor = 11;
    int buzzer = 10;
    int red = 12;
    int i = 0;
    String Pass = "1331";
    String tempPass = "";

    const byte rows = 4; //four rows
    const byte cols = 4; //four columns
    char keys[rows][cols] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'*','0','#','D'}
    };

    byte rowPins[rows] = {8, 7, 6, 9}; //connect to the row pinouts of the keypad
    byte colPins[cols] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

    void setup() {
    pinMode(sensor, INPUT);
    pinMode (buzzer, OUTPUT);
    StartingBuzz();
    keypad.waitForKey();
    digitalWrite(red,HIGH);
    digitalWrite(buzzer,HIGH);
      delay(200);
      digitalWrite(buzzer, LOW);
      delay(60000);
    }

    void StartingBuzz()
    {
    digitalWrite(buzzer, HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
    delay(125);
    digitalWrite(buzzer, HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
    delay(125);
    digitalWrite(buzzer,HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
      }

    void UnlockBuzz()
    {
      delay(200);
           tone(buzzer,3250,200);
           delay(300);
           tone(buzzer,3500,200);
           delay(300);
           tone(buzzer,4000,200);
      }

    void loop() {
      i=0;//resets the password-checking loop.
      tempPass = "";//resets the guessed password.
      char state = digitalRead(sensor);
      if (state == HIGH)
      {
        digitalWrite(buzzer, HIGH);
        A:
        {
        while(i < 4)
        {
        char key = keypad.getKey();
        if(key != NO_KEY)
        {
          tempPass += key;
          i++;
          }
        }
        }
        if(Pass == tempPass)
        {
          digitalWrite(buzzer, LOW);
          digitalWrite(red, LOW);
          UnlockBuzz();
          keypad.waitForKey();
          digitalWrite(buzzer,HIGH);
          delay(200);
          digitalWrite(buzzer, LOW);
          digitalWrite(red, HIGH);
          delay(60000);
        }
        else
        { tempPass = "";
           i=0;
          goto A;
          }

      }
    }


message:
door protector arduino program

Please check the arduino program given below and help me to find out error.
The program is for following hardware.
GSM 800 module
Arduino Uno board
Limit switch(2)

We place two limit switch at main door & back door as main door is open the message will be send that is Main door is open & when it closed it will send message Main door is closed. This is same for Back door also.

We run this program & it run but it sends the massage repeatedly after some time.
Please help me to find out error..

***my ARDUINO code is***

    const int Main = 7;
    const int Store = 8;
    const int Main_led =  13;
    const int Store_led =  14;
    bool i = true;
    bool j = true;
    bool k = true;
    bool l = true;
    int buttonState1 = 0;
    int buttonState2 = 0;
    void setup() {

      Serial.begin(9600);
      pinMode(Main_led, OUTPUT);
      pinMode(Store_led, OUTPUT);
      pinMode(Main, INPUT);
      pinMode(Store, INPUT);
    }

    void loop() {
      buttonState1 = digitalRead(Main);
      if (buttonState1 == HIGH && i == true ) {
        digitalWrite(Main_led, HIGH);
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"+91-------------");
        Serial.print("\"\r\n");
        delay(5000);
        Serial.print("Main Door is closed");
        Serial.write(0x1A);
        delay(5000);
        i = false;
        j = true;
      }
      else
      { if (buttonState1 == LOW && j == true )

        { digitalWrite(Main_led, LOW);
          Serial.println("OK");
          delay(1000);
          Serial.print("AT+CMGF=1\r\n");
          delay(500);
          Serial.print("AT+CMGS=\"");
          Serial.print("+91---------------");
          Serial.print("\"\r\n");
          delay(5000);
          Serial.print("Main Door is open");
          Serial.write(0x1A);
          delay(5000);
          i = true;
          j = false;
        }
      }

      buttonState2 = digitalRead(Store);
      if (buttonState2 == HIGH && k == true) {

        digitalWrite(Store_led, HIGH);
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91-------------");
        Serial.print("\"\r\n");
        delay(5000);
        Serial.print("Store room is Closed");
        Serial.write(0x1A);
        delay(5000);
        k = false;
        l = true;
      }
      else
      { if (buttonState2 == LOW && l == true)
        {
          digitalWrite(Store_led, LOW);
          Serial.println("OK");
          delay(1000);
          Serial.print("AT+CMGF=1\r\n");
          delay(500);
          Serial.print("AT+CMGS=\"");
          Serial.print("+91------------------");
          Serial.print("\"\r\n");
          delay(5000);
          Serial.print("Store room is Open");
          Serial.write(0x1A);
          delay(5000);
          k = true;
          l = false;
        }
      }
    }

body:
I can't see any obvious flaws in the code other than the excessive use of delay. However you could make your code a lot cleaner which makes it easier to spot the errors.<br>
The version below has the duplicate lines moved into a function and instead of using the poorly named i,j,k & l to track two states it uses two variables to do the same job. Finally things that don't need to be global have been moved to being local.

    const int Main = 7;
    const int Store = 8;
    const int Main_led =  13;
    const int Store_led =  14;

    void setup() {
      Serial.begin(9600);
      pinMode(Main_led, OUTPUT);
      pinMode(Store_led, OUTPUT);
      pinMode(Main, INPUT);
      pinMode(Store, INPUT);
    }

    void sendMessage(char *text) {
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"+91-------------");
        Serial.print("\"\r\n");
        delay(5000);
        Serial.print(text);
        Serial.write(0x1A);
        delay(5000);
    }

    void loop() {
      static int oldState1 = -1;
      static int oldState2 = -1;

      int buttonState1 = digitalRead(Main);
      if (buttonState1 != oldState1) {
        digitalWrite(Main_led, buttonState1);
        if (buttonState1 == HIGH)
          sendMessage("Main Door is closed");
        else
          sendMessage("Main Door is open");
        oldState1 = buttonState1;
      }

      int buttonState2 = digitalRead(Store);
      if (buttonState2 != oldState2) {
        digitalWrite(Store_led, buttonState2 );
        if (buttonState2 == HIGH)
          sendMessage("Store room is closed");
        else
          sendMessage("Store room is open");
        oldState2 = buttonState2;
      }
    }


message:
Enter timing value via keypad for bldc motor spin

I am trying to key in the timing for how long the bldc motor needs to spin via keypad. I hope you can help me with this. I'm using delay() to set the timing of bldc motor spin. How do I key in a series of numbers in seconds, and then put it in the delay()?

The idea for this code is to enter the speed and timing via keypad.  After entering the speed and timing, button '#' is used to move the bldc motor according to the speed and timing entered. My question is how do I make my code to compile where speed is keyed in first, timing second then button '#' to run the motor?

Here is my code so far...

    #include "Keypad.h"
    #include "LiquidCrystal.h"
    #include "Servo.h"

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

    Servo myservo;

    const byte ROWS = 4; //four rows
    const byte COLS = 3; //four columns
    char keys[ROWS][COLS] =
     {{'1','2','3'},
      {'4','5','6'},
      {'7','8','9'},
      {'*','0','#'}
      };
    byte rowPins[ROWS] = {9,8,7,6}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {5,4,3}; //connect to the column pinouts of the keypad
    int count=0;

    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

      lcd.begin(16,2);
      lcd.setCursor(0,0);
      lcd.print("S:");
      lcd.setCursor (0,1);
      lcd.print ("T:");

      myservo.attach(11);
    }

    void loop()
    {
        static char buffer[4], spintime[4];
        static byte i = 0, a = 0;
        char key = keypad.getKey();

        // i < 3: prevent buffer overflow
        if  ('0' <= key && key <= '9')   // this is for speed entry
        {
            buffer[i] = key;
            ++i;
            buffer[i] =0;  // null-terminate buffer
            lcd.setCursor (2,0);
            lcd.print(buffer);
        }

         if  ('0' <= key && key <= '9') // this is for timing entry
         {
            spintime[a] = key;
            ++a;
            spintime[a] =0;  // null-terminate buffer
            lcd.setCursor (2,1);
            lcd.print(spintime);
        }
        else if (key == '#')            // this is to run the motor after speed and timing are entered
        {
            int value = atoi(buffer);
            myservo.write(value);       //speed of motor
            int timing = atoi(spintime);
            delay (timing*1000);        // keep the motor spin for ( timing entered) second
            myservo.write(0);
            i = 0;
        }
    }

body:
As I understand it, you want to enter the speed, then the time, then '#'.

Let's imagine you want a speed of 22 and a time of 3.  The device will see `2`, `2`, `3`, `#`.  How will it know whether you're asking for a speed of 22 and a time of 3, or a speed of 2 and a time of 23?  Simple answer: it cannot know.  So we need to find a way to tell it.

My suggestion: we'll enter speed followed by `*`, and time followed by `#`.  (There are other possible solutions to this.)

We also need to decide the longest number the user can enter, and what happens if they enter a longer one, or if they don't enter one at all?  Let's say the longest number is 3 digits, and if they enter a longer one, we will ignore the extra digits.  So if they enter `123456789#`, we will register `123#`.  (Again, there are other solutions.)

There's some stuff in your code about an LCD, but you don't mention it in the question, so I have ignored it.

Lastly, I am assuming your code to drive the motor and read keys is correct.

Here's some `loop` code which I hope will do the above.  It will read numbers until it finds either a `*` or a `#`, convert the number to an integer, and store it as either `time` or `speed`.  When it has *both* speed and time, it will spin the motor and reset the values.

    void loop()
    {
        // Where we will store the number as we type it.
        // This buffer is large enough for a 3-digit number, pull a null terminator
        char buffer[4];

        // The speed of the motor
        static int speed = 0;

        // The time to spin for
        static int time = 0;

        // Input up to 3 numbers until we find a * or #
        int i=0;
        while (1)
        {
            char key = keypad.getKey();

            // If it's a number AND we have space left, add to our string
            if ('0' <= key && key <= '9' && i<3)
            {
                buffer[i] = key;
                i++;
            }
            // If it's a * or #, end
            else if ('#' == key || '*' == key)
            {
                // Null terminate
                buffer[i] = 0;

                // Convert to an integer
                int value = atoi(buffer);

                // Set the appropriate value
                if ('#' == key) time = value;
                if ('*' == key) speed = value;
                break;
            }
        }

        // If we have both speed and time...
        if (speed > 0 && time > 0)
        {
            // ...spin the motor at the required speed
            myservo.write(speed);
            // ...and for the required time
            delay(time*1000);
            // ...then stop it
            myservo.write(0);

            // Reset the values for next time
            time = 0;
            speed = 0;
        }
    }


message:
Wakeup Pin ESP8266

Is there a way to put an ESP8266 into a sort of "sleep" mode where it draws less power than usual, and then wakes up on a pin going high? I've tried doing this with delay, which still draws 20 mA, and with the deepsleep function that comes with the esp library, which can't sleep for short periods of time to watch for the pin going high. I'm building a watch, and power draw is of great concern to me. Is there possibly a way I could build or code this differently to make it more power efficient?
Basically it works like this, but the full code (at it's current state) can be found [here](https://gist.github.com/MrMai/f08da604c8a57844470407ad6b2604c6).

    void loop() {
        delay(1);
        // check for power signal stuff
        if(digitalRead(0)) {
            // execute data fetching 'n stuff
        }
    }

body:
Without seeing the code and optimizing it I can tell you the following:

ESP8266 has three ways to save power:

 1. Modem sleep - only wlan modem shutdown, connection kept open
 2. Light sleep - less cpu usage, fast recovery
 3. Deep sleep - suspend all, close wifi too, slow recovery

http://bbs.espressif.com/viewtopic.php?t=133


body:
ESP8266 does have deep sleep mode. The link to http://bbs.espressif.com/viewtopic.php?t=133 posted earlier sums it up pretty well, despite being old.

However, a few things that are different from Arduino or should be considered if you're building a battery-operated device:

  - when the MCU wakes up from deep sleep, the entire application is restarted. Yes, beginning from the setup() function - just as if it was reset. You cannot put it to the deep sleep and then resume from the same place keeping all variables etc. You can only detect that the device was woken up from the sleep by reading a flag in the setup() function.

  - check your board. If you're not using bare ESP8266, but some development board such as NodeMCU or WittyCloud, it usually has number of other circuits powered on even when the MCU is sleeping. Particularly, USB-UART bridge and maybe power LED.

  - check your power source. Again, if you're using a development board, very likely it has an inefficient LDO voltage regulator. Even when MCU is powered down, the LDO can still use a few mA just to power itself (quiescent current). There are special low quiescent current regulators exist, very useful for battery-operated application.

  - finally, I see your code refers some OLED display. Just to be sure - is it powered down or excluded from the measurement? OLED doesn't need a lot of energy, but will drain a battery in a few days.

Personally, I do have experience creating a battery-operated device on ESP8266, which wakes up every few minutes, connects to wifi and sends some data. An old 700mAh Lithium battery is enough to run it for approximately a month. And I managed to get the sleep power to about 40 microAmps. Still a few times more than the chip itself needs, but good enough for me.


message:
Unable to receive SMS on Android

I have a GSM/GPRS shield for Arduino. It uses a SIM800 from SIMCOM. I've done several projects using it. Previously I used to send SMS from the same module. which were delivered appropriately. Since yesterday, whenever I am sending an SMS to my Android mobile, all what I receive is:

    <<Content not supported>>

I also tried sending it to a basic mobile. It displayed:

    Content can't be displayed

I tried changing the encoding using the `AT` command.

    AT+CSCS="UCS2"
    AT+CSCS="GSM"

It didn't work for any encoding.

The command I use to send SMS is:

    ---> AT+CMGF=1
 <--- OK
 ---> AT+CMGS="10 digit number"
 <--- >
    > Hello!
    ^Z

Can someone please tell me what is going wrong? Thank you in advance!

body:
In the SIM900 is an AT command that let you do a factory reset, your module will restart to the default values. It must be an AT command very similar to the SIM800.

The AT commando that (perhaps) will work for you is the **ATZ**, in the SIM900 works for me.

You can look over [here][1] to see what command is. Look over page 33. And be carefull, the link that I send to you is the AT command list for the SIM900, not the SIM800.

Hope you can find an answer.

  [1]: http://www.propox.com/download/docs/SIM900_AT.pdf


message:
SSD1306 OLED LCD Library Errors

Recently i bought an "Serial 128X64 OLED LCD Display SSD1306".

I searched for available libraries and tried to find the best one to use before actually experimenting with this device.

I came across a hackaday article mentioning a "HIGH SPEED SSD1306 LIBRARY"

So that drew my attention and got on with it. This is the link to the afforementioned library for the Arduino DUE.

[DayOLED_SSD1306][1]

  [1]: https://github.com/GravCorp/DayOLED_SSD1306

Right from the beginning i had some trouble with the wiring.
I wired 3.3 volts to input, GND, RES, DC, CS pins are wired according to the library example..
But the library contains no info on how to wire D0 and D1 pins. Since this OLED works both I2C and SPI, i thought maybe these two pins are ommited.

So i hooked it up, load up the example code and got compilation errors.

Here are the errors:

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawPixel(int16_t, int16_t, uint16_t)':

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:114:14: error: 'swap' was not declared in this scope

         swap(x, y);

                  ^

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawFastHLine(int16_t, int16_t, int16_t, uint16_t)':

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:598:16: error: 'swap' was not declared in this scope

           swap(x, y);

                    ^

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawFastVLine(int16_t, int16_t, int16_t, uint16_t)':

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:666:16: error: 'swap' was not declared in this scope

           swap(x, y);

Anybody got a clue what is going on with the swap() function?
Maybe it's deprecated?

Anyone has managed to get this library working?
Or maybe has managed to get this Display working even with another library?

body:
I've had good success with the u8g2 library for the small I2C OLEDs.
[u8g2 on GitHub][1]

  [1]: https://github.com/olikraus/u8g2


body:
I have managed to get this somewhat working with these 4 libraries:
#include <SPI.h>,
#include <Wire.h>,
#include <Adafruit_GFX.h>,
#include <Adafruit_SSD1306.h>.
These should all be in the include library in the ide.
Hope this helps!


message:
toInt error when converting character of string to interger

with the following code:

    int foo = bar[1].toInt;

or

    int foo = bar[1].toInt();

I get this error

    request for member 'toInt' in '*(bar + 1u)', which is of non-class type 'uint8_t {aka unsigned char}'
the context for this is bar is the response from a HTTP client over web sockets

body:
I'm not quite clean on what you are trying to do.  So lets assume the String has "abc123" in and you want the numeric part.

    const String input = "abc123";
    const int foo = input.toInt();  // This will not work!

    const String input = "abc123";
    const String tmp = input.substring(3); // Take the end of the string
    const int foo = input.toInt();  // foo == 123

    const String input = "abc123";
    const String tmp = input.substring(3,4); // Take the end of the string
    const int foo = input.toInt();  // foo == 1 or 12 (can't quite tell from the docs)

Is one of those what you want to do?

You can't take a character and then apply a function from the string class to it without making it a String first.

    int foo = String(bar[1]).toInt();  // This should work


body:
The Arduino function `toInt` requires a `String` object.
You're passing it a single character, not a `String`.

    int foo = String(bar[1]).toInt();


message:
Connect Two Arduino Uno's

Essentially I am looking to build a remote controlled car using dc motors and one arduino uno to be on the car to supply the power logic and i wanted to use another arduino to be the remote. I was curious what the most effective method would be as to pairing these two devices in a way that it would provide the maximum range possible while still maintaining a decently high bandwidth limit. The reason for this is hopefully i can have the arduino mounted to the car connected to a camera where the camera would send a video feed over to the remote control. I was thinking about using a bluetooth module between the two such as a HM-10 but i wouldn't be able to send a video feed this way because bluetooth cannot transmit that much data at once. However if that is the most practical option i can get over the fact of not having a live video feed and send an image ever 5 seconds or so instead of live. Appreciate any insight on what the most effective method would be in terms of efficiency between range and data stream bandwidth.

body: You can use raspberry pi and computer to send commands and receive video feed