message:
Powering a 12v lock with batteries, via WiFi, and with low energy consumption

I'm a complete newbie in anything related to electronics, software or hardware; yet with a couple of friends we're going ahead with an interesting project related to automation through wireless devices: more or less IoT but involving electric locks.

The case scenario: there's a room without any power outlets. It has a regular door. **We want to be able to open this door through the internet, with a lock that lies inside the room, on the other side of the door**; all this, given we:

 - Can't make any modifications to the door's structure.

 - Can't drill or make holes or whatever so as to get a power cable to
   the inside of the room.

 - But **we can** glue certain pieces behind the door, this is, inside
   the room that hasn't any power outlets.

We've planned, so far, to use an Arduino Uno; enhance it with WiFi features (i.e. a module or shield) so as to bypass the limitation of not being able to connect an ethernet cable; and glue a solenoid or lock to the inside of the doors, so that it acts as a second lock that can only be unlocked through the internet, accessed via Arduino.

**Our ideal scenario would be opening this door remotely, from our home, even if this door is a hundred blocks away. If someone wants to get in, they should ask for our permission, as we don't control the built-in handle, but we do control a latch fixed on the inside.**

All this setup should be powered with a long-lasting battery: we can't plug anything, and we can't risk getting our batteries depleted fast, because we'll never be able to open the door once again. We need these batteries to last long enough so as to be able to change them in a prudent time window; a back-up battery system should also work well.

Standard solenoid locks are 12v. Arduino powers 5v devices, not 12v ones, as far as my understanding goes.

We should open this door only 5 times a day. That's it; the remaining time in between, the whole device setup can well stay 'dormant', in low-energy consumption mode, only to 'wake up' when we give the order: "Arduino, please tell the solenoid to open".

We haven't specified which battery we would use; ideally, the most cost-efficient option. If it lasts 3 months and costs, say, 20 dollars -- well, we would love that.

I've done this really inaccurate, schematic drawing to illustrate our idea and research. I know there's many details missing but I wanted to prove our point:

[![enter image description here][1]][1]

(The Arduino should be positioned on the wall and not on the door! My bad.)

I hope I'm clear enough up to now.

The questions, then, are:

I've done some research, and I've seen that Arduino can be enhanced so that it consumes the minimum possible energy so as to remain 'aware', but not in full-power mode, which in our case would be unnecessary.

1. So, can we make Arduino *super efficient* in terms of power consumption, even if we attach WiFi functions, which, as far as I'm concerned, really takes on battery life? So that we can make Arduino run for months before replacing the battery?

2. Arduino can send only 5v; but the solenoid powers on 12v; then, getting a second battery to power our solenoid sounds straightforward, except that as far as my knowledge goes, this battery should last next to nothing (maybe I'm wrong here). And we want it to last for months -- if not, our door will remain sealed forever! Can I make the solenoid dependant on the Arduino, so that it's part of the "almost-no-battery-consumption" scheme, and battery lasts, as I would really like, some months? We would be talking of only one battery to power the whole set-up, instead of two that I guess that we'll need.

I'm a newbie, but can't Arduino power 12v through a relay or a transistor? Can't post links.

To clarify: Getting two batteries for our complete setup (one for the Arduino, one for the solenoid), if these two batteries both last, is not a problem; but it would be catastrophic to make a battery last long enough while the other depletes in 48 hours. The solenoid needs to get electricity a modest 5 times a day; that's why I believe we can make it super efficient.

With our friends, we've so far programmed Arduino to open a solenoid from the Internet. The solenoid we've used was 220v because we had it in stock; it won't be what we need for our project. It was just a trial. On top of this, the Arduino has no WiFi module, just an Ethernet shield.

[![prototype][2]][2]

There's a remaining problem to solve, which is: what would happen if the Arduino fails? The door would be sealed 'forever'. We'll tackle that issue afterwards.

**TL;DR:** we'd love to open a lock via WiFi: the lock and Arduino should run solely on batteries that last more than 48 hours: a couple of months would be ideal! Can we work this out?

Thank you very much for your help, opinions, and time. I hope my question is up to the standards.

  [1]: https://i.stack.imgur.com/7nTnC.jpg
  [2]: https://i.stack.imgur.com/gkd59.jpg

body:
[I'm coming in late but since this question got reposted, here goes:]

If this not to be just a Proof of Concept, but to be actually installed, you really have to address the several points of failure (Arduino, Arduino power, solenoid, solenoid power) that could lock you out of the room forever ("ever" being the time needed to fetch and apply destructive tools :).

Assuming it's a POC, here are a few more ideas:

 1. You need 12v for the solenoid. You can take your 5v from the same source using an efficient regulator. Advantage: one fewer point of failure (power source), and the Arduino could monitor the 12v source and send an alert if/when it starts to sag (which would only be useful if there's some head-room between its charged voltage and the minimum needed to drive the solenoid).
 2. If you use Bluetooth LE on the Arduino instead of WiFi, but place another Arduino outside the door, somewhere with power (locked into the wall, the ceiling, or an adjacent room), the outer Arduino with "unlimited" power could talk BTLE to the inside Arduino. Advantage: Lower power consumption by the inside Arduino (unless step 1. makes it unnecessary). Disadvantage: More equipment (second Arduino); more complex system has additional ways to fail, though not necessarily to lock you out; possible additional point of vulnerability to intrusion.
 3. Is that a steel door? If not, an inductive charging coil on the inside of it might let you temporarily apply an inductive charger from outside to provide power - or charge a small battery or even a capacitor - enough to unlock the door. Advantage: One less point of failure (loss of 12v). Disadvantage: More equipment; applicability depends on door material and thickness.


sender: user

message:
How to convert bool array to byte?

I have following problem:
I'm reading 8 bit signal from one Arduino pin and store all informatin in bool array. Now I want to convert this array to single byte in decimal. How to do this?

I've tried this:

    bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
    int recivedID = int(ID);

and

    bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
    int recivedID = ID.toInt();

non works.

sender: assistant

body:
    byte BoolArrayToByte(bool boolArray[8])
    {
      byte result = 0;

      for(int i = 0; i < 8; i++)
      {
        if(boolArray[i])
        {
          result = result | (1 << i);
        }
      }

      return result;
    }


body:
try with this:

    int recivedID = ID[0] | (ID[1] << 1) | (ID[2] << 2) | (ID[3] << 3) | (ID[4] << 4) | (ID[5] << 5) | (ID[6] << 6) | (ID[7] << 7);

which is the same as

    int recivedID = 0;
    for(int i=0; i<8; i++){
       recivedID |= ID[i] << i;
    }

I haven't tested it though.


message:
DMX dimmer appears to receive data from Arduino but connected lights do not respond

I'm trying to control a DMX dimmer ([eurolite ES-12 IEC DMX Switchback][1]) through an Arduino Mega. In an earlier test, we were able to make one RGB DMX light run through the color spectrum. Now, a technician has installed this ES-12 dimmer pack with 12 1-channel DMX lights attached to it. The dimmer has some kind of built-in testing program and all the lights work.

The documentation on the dimmer is very sparse regarding the programming side of things. The dimmer is set to mode `d---` and when the Arduino is running its program, a little green light flickers next to the `d---`, apparently responding to the signals it's receiving, like so: `d---.` Unfortunately, that the only light that responds.

I've tried using the DMXSimple library (the DMX is connected to pin 3), but even the example code (after correcting the brightness-- to ++) does not get any response -- none at all, not even the little green light. The only thing the little green light responds to is an analogWrite() on pin 3.

I'm guessing it's an addressing issue, but I don't know enough to fix it. As I understand it, the dimmer is seen as the controller and is sent a LOW on channel 0 as the Start Code (SC): [http://www.dmx512-online.com/packt.html][2]. The first light on the dimmer will then be channel 1, the second light channel 2, etc. (since, the technician tells me, they are 1-channel lights). Is this correct? Or is the dimmer its own universe that should be addressed in some other way?

  [1]: http://eshop.steinigke.de/de/mpn70064250-eurolite-es-12-iec-dmx-switchpack.html
  [2]: http://www.dmx512-online.com/packt.html

body: The light technician, Toby Peperkamp, came with the solution. I'm not sure exactly where he found the information, but apparently the protocol for non-RGB DMX lights requires that the lights be switched on to maximum (255) at the beginning of the connection. So I added that to the setUp() and all the lights started to respond.


message:
Why isn't this pushbutton program working?

Here is my circuit:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/kMqM1.png

and here is my code:

    int LED = 13;
    int BTN = 7;

    void setup() {
    pinMode(LED,OUTPUT);
    pinMode(BTN,INPUT);
    }
    void loop() {
    if(digitalRead(BTN) == HIGH) {
    digitalWrite(LED,LOW);
    }
    else{
    digitalWrite(LED,HIGH);
    }
    }

When I press the button, the LED is supposed to go low, but it doesn't. What is wrong with this circuit/code?

body:
Paul is correct. Your button is wired wrong. The GPIO pin should be connected to the same side as the resistor. Also the button needs rotating through 90 degrees.

Also check how your LED is wired up. At the moment it looks like it's set up so that the GPIO sinks the current (LOW turns the LED on) yet the LED looks like it's connected the wrong way around for that.

In fact, I can't actually find anything *right* about that circuit...


body:
The Input port is going to always be at Gnd, because you have connected it to ground.  Sorry to put it in such basic terms but this is the way I understand it.  It needs to be more difficult for the output of the button to get to ground than to get to the BTN pin of your UNO.  So put a bigger resistor (1K-10K) in place of your yellow wire between the button and ground.

And your LED is the wrong way round in the diagram.

(And Majenko is a quicker typist than me! :) )


body:
In addition to the answers from Matt and Majenko, you code uses the wrong pin for the LED.

You have `int LED = 13;` whereas your LED is connected to pin 6.

NB: Pin 13 is connected to an LED soldered on to the Arduino board - as seen in the image below.

[![enter image description here][1]][1]

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


body:
Your code and schematic both seem to be wrong.

Try out this schematic:

[![schematic][1]][1]

And then code:

    const int kPinLed = 6; // LED - Pin 6
    const int kPinBtn = 7; // Push Button - Pin 7

    void setup()
    {
      pinMode(kPinLed, OUTPUT);       // LED as OUTPUT
      pinMode(kPinBtn, INPUT_PULLUP); // Push Button as INPUT wiith pullup
    }

    void loop()
    {
      if(digitalRead(kPinBtn) == LOW)  // When Push Button is pressed
      {
        digitalWrite(kPinLed, HIGH);   // LED ON
      }
      else digitalWrite(kPinLed, LOW); // LED OFF
    }

  [1]: https://i.stack.imgur.com/XiEvq.png


message:
Arduino program does not start when plugged in

I am having trouble with my Arduino Mega with getting the program to start when the Arduino is plugged into a computer via USB.  All that happens is the LED turns on and stays on.  The device does not initialize, and only when I press the reset button does it begin the setup.  How can I make the Arduino start the program when it is first plugged into the computer?

**EDIT:** my code

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

    void loop() {
      Serial.println("test");
    }

very simple, which is why i don't understand why this is happening

body:
I would recommend you to follow the following instructions step by step to verify your Arduino Mega.

1. Reboot your computer
2. Connect the Arduino using the USB cable to PC and check the Arduino itself if there is any jumper wires connected/grounded. If there are then remove them all.
3. Upload a blank sketch first. Go to ***File -> New***
4. Verify the Arduino has accepted the blank sketch and resetted.
5. Upload the Blink sketch from the ***File -> Examples -> 0.1Basics -> Blink***
6. Verify if the Pin 13/onboard LED is blinking. If yes then go to uploading your sketch, if no then there is a hardware/bootloader problem with your Arduino. Watch this video on how to burn bootloader [here][1]. https://www.youtube.com/watch?v=X5achE10rCI

  [1]: https://www.youtube.com/watch?v=X5achE10rCI


message:
Start to build a robot

I would like to start with a very simple robot, which should be based on an arduino uno.
I already have an uno and made the decision fpr my robot chassie:
https://www.roboter-bausatz.de/en/diy-electronics/kits/robotic-kits/97/2wd-motor-smart-car-chassis-fuer-roboter-mit-getriebemotor-und-batteriebox

Additionally I want to by an ultrasonic distance sensor and a infrared sensor.
What else do I need to start ? Only a DC motor driver or anything else?

Thanks in advance
LStrike

body:
You'll need:

 - Emergency switch (it should be easy to cut the power off, even for small robots)
 - A chassis (you've found one already)
 - Motors (Obviously)
 - Motor control (Probably a dual H-bridge, think if you need reverse or not.)
 - Power (powering on (single use) batteries may not be your best option)
 - Controller (Arduino Uno, or something smaller or faster)
 - Sensors (Can be anything, depending on the requirements)

A way to communicate with the robot is also nice, often wireless (bluetooth/wifi/443mhz).

And also, it will be nice if the robot fits some kind of purpose, but this could be added later.
You could think of the robot having to pick up and carry something, extinguish a flame etc.

I advise to check out one of the many tutorials on building a robot, they often have a detailed parts list (sometimes even shopping links).


message:
Compilation Error

Hi everyone I seem to have run into a problem while uploading a library to the board. I managed to import the library to Arduino Uno, however, i could not upload it

Please Help :)

Thanks in Advance

This is the error i received:

    Arduino: 1.6.11 Hourly Build 2016/08/05 02:12 (Mac OS X), Board: "Arduino/Genuino Uno"

    In file included from /Users/pendukenipandeni/Documents/Arduino/SimpleTimer/SimpleTimer.ino:1:0:
    /Users/pendukenipandeni/Documents/Arduino/libraries/SimpleTimer-master/SimpleTimer.h:37:22: fatal error: functional: No such file or directory
     #include <functional>
                          ^
    compilation terminated.
    exit status 1
    Error compiling for board Arduino/Genuino Uno.

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

body: I managed to fix this by simply downloading and uploading a different SimpleTimer Library from https://github.com/jfturcot/SimpleTimer


message:
Serial characters are corrupted

I try to send an "a" string via serial with

    Serial.println("a");

and I receive "Oy=" in Ascii or {4F}{79}{3D} in Hexa.

Where should I start investigating? What could be wrong?  Baudrate is 9600 on all sides.

PS: I suspect the cable. Any hints how to check it?

body:
On your setup function

    Serial.begin(115200);//<- 115200 is the baud rate, serial monitor must match this speed
    while(!Serial);//<-- wait for Serial to be ready

see: https://electronics.stackexchange.com/questions/9264/what-standard-uart-rates-are-there for more baud rates


message:
Use a 2.8" TFT with my Leonardo

for 2.8" diagonal color touchscreen TFT:

Readme states:
"Works with any classic Arduino '328. Solder closed three jumpers to use the ICSP header for use with Leonardo or Mega"

What should I solder? See image.[![enter image description here][1]][1]

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

body: It looks like that display doesn't have a touch screen, only a tft and sd card. The modifications you would need to make pertain only to the SD card and the nonexistent touch screen interface. The tft portion should work with any arduino since it is a bit banged 8 bit parallel interface.


message:
How is IF( object ) evaluated? Follows from SD card example sketch

The "DumpFile.ino" example sketch from the SD library tries to open a file off an SD card, read its contents, and write them to the Serial Monitor. I am confused in how the following `if()` statement is evaluated:

    File dataFile = SD.open("datalog.txt");

    if (dataFile) {
    // read and print, then close
    }
    else {
    // print error message
    }

There must be some implicit conversion on `dataFile` which depends on whether or not `SD.open("myFile.txt")` was successful. I would like to understand how this implicit conversion occurs. Which property of the `File` object determines if the `if()` statement evaulates `true` or `false`?

body:
There is an operator bool which does the test:

    File::operator bool() {
      if (_file)
        return  _file->isOpen();
      return false;
    }

When used inside an `if` the compiler invokes the `operator bool()` which does the test you see above.


message:
Why can't the Atmel ATtiny family delay over a minute?

I have some really simple code and tested on an 8 MHz [ATtiny85][1] and [ATtiny2313][2]. It's basically a blocking blink:

    int relayPin = 7;

    long offPeriod = 1 * 60 * 1000;
    long onPeriod = 1 * 60 * 1000;

    void setup()
    {
      pinMode(relayPin, OUTPUT);
    }

    void loop()
    {
      digitalWrite(relayPin, LOW);
      delay(onPeriod);
      digitalWrite(relayPin, HIGH);
      delay(offPeriod);
    }

When I assign `onPeriod` and `offPeriod` to be `1 * 1000` (1 second), the LED will blink as expected. When I add the 60 second multiplier in, it seems to fail.

For the ATtiny85 I use Arduino Pin 4 (physical pin 3) and for the ATtiny2313, I use Arduino pin 7 (physical pin 9).

I program through the Arduino IDE using boards manager to install the ATTinyCore library for the ATtiny2313 and [this][3] for the ATtiny85.

Am I doing something wrong here?

It looks like if I throw the delay in a function, and then invoke it with however many seconds I want, it will work. This is not good as it remains blocking. So perhaps the correct way to do this is to grab timestamps.
Here's the somewhat working code:

    int relayPin = 4;
    unsigned long offPeriod = 60;
    unsigned long onPeriod = 60;

    void setup()
    {
      pinMode(relayPin, OUTPUT);
    }

    void loop()
    {
      digitalWrite(relayPin, LOW);
      delaySeconds(onPeriod);
      digitalWrite(relayPin, HIGH);
      delaySeconds(offPeriod);
    }

    void delaySeconds(int s) {
      for (int i = 0; i < s; i++) {
        delay(1000);
      }
    }

  [1]: http://www.atmel.com/devices/ATTINY85.aspx
  [2]: http://www.atmel.com/devices/ATTINY2313.aspx
  [3]: https://github.com/damellis/attiny

body:
These are the problem lines:

    long offPeriod = 1 * 60 * 1000;
    long onPeriod = 1 * 60 * 1000;

Even though `long` should hold the result, integer operations in C++ are still done in `int` by default. And on AVR `int` is 16 bits. The fix is to tell the compiler what size the intermediate result should be:

    long offPeriod = 1 * 60L * 1000;
    long onPeriod = 1 * 60L * 1000;


body:
This is absolutely nothing to do with "why can't the atmel attiny family delay over a minute?". It is all to do with the way that C++ works.

See [my page about Integer arithmetic and overflow](http://www.gammon.com.au/forum/?id=12146).

To excerpt from that:

---

On the Arduino (Uno) platform, what do you think will be printed here?

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

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

      Serial.println (30000 + 30000); // twice 30000
      Serial.println (60 * 60 * 24);  // seconds in a day
      Serial.println (50 / 100 * 1000); // half of 1000
      }  // end of setup

    void loop () { }

Did you guess:

    60000
    86400
    500

Nope!

It prints:

    -5536
    20864
    0

This is because of **integer arithmetic**. If the compiler can, it treats an numeric literal (like 60) as an int type, which means it has the range -32768 to +32767.

And, arithmetic is done using the type of the largest argument, which means the arithmetic in each case is done as 16-bit arithmetic, and thus it overflows once it reaches 32767.

For example, 30000 + 30000 = 60000 which is 0xEA60 in hex. Unfortunately, 0xEA60 is exactly how -5536 is stored in an int type, which is why it prints -5536.

Meanwhile, 60 * 60 * 24 = 86400 which is 0x15180 in hex. As that doesn't fit in 16 bits, it is truncated to 0x5180 which is 20864 in decimal (as printed).

Finally, in integer arithmetic 50/100 is zero, multiply zero by 1000 and you still get zero, which is why the final result is zero.

---

## Solution

First, you can add a suffix to numeric literals (eg. L for long, or UL for unsigned long), and add a decimal place to floats, like this:

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

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

      Serial.println (30000L + 30000); // twice 30000
      Serial.println (60L * 60 * 24);  // seconds in a day
      Serial.println (50.0 / 100 * 1000); // half of 1000
      }  // end of setup

    void loop () { }

Now we get:

    60000
    86400
    500.00

You only need to help out with the first literal, once the compiler knows we are using longs (or floats) it sticks with them for the expression.*

---

\* It's actually somewhat more complex than that as this link explains: [Understand integer conversion rules](https://www.securecoding.cert.org/confluence/display/cplusplus/INT02-CPP.+Understand+integer+conversion+rules).

The compiler "promotes" a value in an expression to match another "higher-ranked" type, under certain circumstances. For example, adding an **int** and a **long** will result in the **int** being promoted to a **long** (regardless of whether it appears first in the expression or not). However if an **int** is being added to another **int**, it will not promote them to a **long**, even though the result may not fit into an **int**.


message:
How to use relay shield to control dc motor speed and direction?

I tried l298n before but its output voltage wasn't high

so I use relay shield but  it seems that the car can only go forward or stop

Can I control the speed and direction of dc motors?

body:
Yes you can, but the easiest way is by using a "motor shield".  There are more options than just L298N.

Are you sure it was the voltage that wasn't high enough, its normally the current (Amps)?

To do it with a relay you need to change the polarity of the feeds to the motor.  You could do this with 2 relays both connected all the time, but if you close the wrong one, you will short everything.  It would be better using a motor controller.


body:
Most refer to [relays][1] when talking about mechanical devices which are either closed or open.  If you arrange several in an H-bridge configuration, you can make you car go forward, stop and reverse.  But controlling speed is not possible.

  [1]: https://en.wikipedia.org/wiki/Relay


body:
Using a mechanical relay to control the speed is not a good idea. But you can control the directions.

I prefer you to use Solid state relays (SSR) to do this. Arrange 4 SSR as Hbridge and Use PWM to control the speed.

refer [this][1]

or you can use the devices like [this][2] which has direction control as well.

  [1]: http://www.power-io.com/library/appnotes/h-bridge.htm
  [2]: http://www.crydom.com/en/tech/newsletters/jan 2013 - solid statements - dc motor reversing.pdf


message:
SIM900 random shutdowns

I have a [SIM900 GPRS/GSM Shield][1] and an Arduino Mega. Now for the past week I have been using USB as power to send and receive GPRS data with no issue. Today the SIM900 module is continually randomly turning off, not even turning of at specific stages of communication.

I thought this could be power related, so have external power (5V 5A UBEC) into the 5V pin of the Mega, which I believe should cover the voltage and current requirements of the SIM900 shield. However this has not solved the problem.

Any ideas on what could be causing the random shutdowns?

EDIT:
Is it safe for me to wire power up like this:

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

  [1]: http://linksprite.com/wiki/index.php5?title=SIM900_GPRS/GSM_Shield
  [2]: https://i.stack.imgur.com/sImrM.png

body:
Pumping 5Amps into the Mega isn't going to make a difference to the current the SIM900 is receiving (needs >2A)  it will still get 500mA (?).

You need to feed the power directly into the SIM900 from the PSU, because when it transmits it needs a nuclear reactor to power it.  Don't forget the common ground.


body:
Cool, an UBEC is indeed a smart choice for powering a SIM900.
I could get away with a small switching power supply and just putting in a big capacitor (since the sim900 only draws high current in very short peaks).

But, the limiting factor in this case would be the 6AA batteries. Your UBEC may be able to supply 5A's but those AA's may not.

Also, look up "transient response" ([related][1]) according to the related article, you can have an 20A power supply, but still have the voltage drop out when the sim900 starts to transmit. This is because your supply needs to be able to deliver the required 2A in a very short period of time, so basically if your supply can't go from 100ma to 2A fast enough, it'll dip.

I suggest finding a more optimal source as AA's and adding a "big ass capacitor" close to the sim900's input.

  [1]: http://www.edaboard.com/thread207589-2.html


message:
Arduino servo motor on pushbutton

I'm working on my first arduino project and i have my first problem dealing with servo motor , i'm trying to control the servo from my pc with this code but it just spining :

      #include <Servo.h>

    Servo servo1;
    long num;

    void setup()
    {
       servo1.attach(7);
       Serial.begin(9600);
       Serial.print("Enter Position = ");
    }

    void loop()
    {
      while(Serial.available()>0)
      {
        num= Serial.parseInt();
        Serial.print(num);
        Serial.println(" degree");
        Serial.print("Enter Position = ");
      }
      servo1.write(num);
      delay(15);
    }
this is my setup
   [![enter image description here][1]][1]

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

body:
I have reformatted your code and the problem becomes very clear (to me).

    void loop()
    {
      while(Serial.available()>0)
      {
        num= Serial.parseInt();
        Serial.print(num);
        Serial.println(" degree");
        Serial.print("Enter Position = ");
      }
      servo1.write(num);
      delay(15);
    }

You are getting some input from the user and then setting the servo to that point.

When there is no data in the Serial buffer you set the servo to the value of write and delay 15ms before checking the buffer again.
I think what you want to do is if there is no data then you don't want to change the Servo position.  In short move the `servo1.write(num);` line inside the } of the while loop.

Now much more importantly the first time you enter loop() you won't have any data there so the servo will be moved to the number held in `num` which is? Undefined, it could be anything at all from 0 to 4294967295 and if its the upper end of that it will take a while for the servo to get there, it might seem like all it does is spin.  **ALWAYS INITIALIES VARIABLES BEFORE USE** :)

A minor point, your while loop could be, probably should be an if statement.  That will prevent a cat sitting on the keyboard and blocking the servo movement.


message:
Arduino audio output circuit

I am looking to build my own arduino-based board that, when triggered, will play a file (line out, not amped to a speaker). Most of the audio shields I see are more complicated than I need, so what I'm wondering is what is the barebones circuit I would need for audio output? I've got the atmega and SDcard side fine, I'm just not sure what IC's are involved in audio output. WAV's are fine so I don't have to deal with mp3 decoding.

PS feel free to move this to electronics instead of arduino, I'm not sure where it belonged since it's built into an arduino board but is more the electronic circuitry.

body:
If you don't care much about quality then all you need is two capacitors and a resistor. Use PWM to create the audio (there is a timerpcm pr something library that will do it). The resistor and pne capacitor form a low pass filter for the PWM, and the other capacitor removes the dc offset.

    ----/\/\/\----+----||------
                  |
                 ---
                 ---
                  |
                  _
                  -


message:
Using logical operators

This is a snip it of code from a program I am writing. I have the program turn an LED on and if a button is pressed when the LED is on I want it to add to a counter and print the counter value. The problem seems that my if statement is skipped. Right now the while loop is setup for 5 seconds using millis() and stays off using a short delay. This part (button_press_9())) is a function call to a Boolean I have setup for debouncing. If I put the function call in an if statement by its self for example to test it. It works and will turn an LED on and off. It seems the combination of the two is incompatible.

Thank you in advance.

 unsigned long previousMillis = millis();
 unsigned long currentMillis = millis();

 while ((currentMillis - previousMillis) < onTime)
 {
  digitalWrite(ledPin4, HIGH);
  if (ledPin4 == HIGH && (button_press_9()))
  {
   counter++;
   Serial.println(counter);
   currentMillis = onTime * 100;
  }
  currentMillis = millis();
 }
 digitalWrite(ledPin4, LOW);
 delay(1000);

body:
You should use

    if (digitalRead(ledPin4) == HIGH && (button_press_9()))

instead of

    if (ledPin4 == HIGH && (button_press_9()))


message:
Pneumatic cylinders with sensors with Arduino Uno

I'm working on my own project with Arduino Uno. There are controlled 4 pneumatic cylinders via 4 coils. Every pneumatic cylinder has got their own coil which switch air to the pneumatic cylinder. Every pneumatic cylinder has got 2 magnetic sensors (when the pneumatic cylinder is retracted and extended).
I created a program for arduino but it doesn't work correctly. When I write there that I want to control only 2 pneumatic cylinders, it works correctly. If I write there the others, it skip the second if statement, do the third if statement and then do the previous if. I don't know why. The behaviour is random. What's wrong with my code? Thank you for help!

    // Constants for pneumatic valves
       const int dvere = 2;
       const int davkovani = 3;
       const int lisovani = 4;
       const int vyhazovani = 5;
    // ----------------------------------------
    // Constants for sensors
       const int vyhazovaniZasunute = 6;
       const int vyhazovaniVysunute = 7;
       const int lisovaniVysunute = 8;
       const int lisovaniZasunute = 9;
       const int dvereZasunute = 10;
       const int dvereVysunute = 11;
       const int davkovaniVysunute = 12;
       const int davkovaniZasunute = 13;

    void setup() {
      // Pneumatic cylinders set as output
      pinMode(dvere, OUTPUT);
      pinMode(davkovani, OUTPUT);
      pinMode(lisovani, OUTPUT);
      pinMode(vyhazovani, OUTPUT);

      // Sensors set as input
      pinMode(vyhazovaniZasunute, INPUT);
      pinMode(vyhazovaniVysunute, INPUT);
      pinMode(lisovaniVysunute, INPUT);
      pinMode(lisovaniZasunute, INPUT);
      pinMode(dvereZasunute, INPUT);
      pinMode(dvereVysunute, INPUT);
      pinMode(davkovaniVysunute, INPUT);
      pinMode(davkovaniZasunute, INPUT);

      // Set pneumatic cylinders as they are retracted
      digitalWrite(dvere, HIGH);
      digitalWrite(davkovani, HIGH);
      digitalWrite(lisovani, HIGH);
      digitalWrite(vyhazovani, HIGH);
    }

    void loop() {

      if(digitalRead(dvereZasunute) == HIGH)
      {
          digitalWrite(dvere, LOW);      // extend the first pneumatic cylinder when the sensor is lighted on because the pneumatic cylinder is retracted
      }

      if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH
      )
      {
          digitalWrite(davkovani, LOW);      // extend the second pneumatic cylinder
          delay(4000);
          digitalWrite(davkovani, HIGH);    // retract the second pneumatic cylinder after 4 seconds,
          // this code works when it is alone there, the next if statements not
      }

      if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
      {
          digitalWrite(lisovani, LOW);    // extend the third pneumatic cylinder
          delay(3000);
          digitalWrite(lisovani, HIGH);   // retract the secondthird pneumatic cylinder after 3 seconds
      }

      if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
      {
          digitalWrite(dvere, HIGH);      // retract the first pneumatic cylinder
      }

      if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH && digitalRead(vyhazovaniZasunute) == HIGH)
      {
          digitalWrite(vyhazovani, LOW);    // extend the fourth pneumatic cylinder
      }

      if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH&& digitalRead(vyhazovaniVysunute) == HIGH)
      {
          digitalWrite(vyhazovani, HIGH);    // retract the fourth pneumatic cylinder
      }

      // sensors - HIGH - light on, LOW - light off,
      // pneumatic cylinders - HIGH - retracted, LOW - extended.
    }

body: Your code's variable names must be meaningful. You mention "2 magnetic sensors (when the pneumatic cylinder is retracted and extended)"-I guess it is solenoid valve. I hope I don't guess wrongly. This help us to understand your code. Otherwise, do you have any procedure diagram-it is like square and prismatic shape to illustrate your programing and its sequence.


body:
Hi~ The synchronized method is below. The function millis() you can refer Arduino.org. It is a function to show you current time. Here I use it to create a time interval to run synchronization.

Declaration the variables are below:

    /* Declaration time interval variables for synchronizing pneumaticValve1 and pneumaticValve2. The interval is 1000ms.  */
    long perviousTimepneumaticValve1 = 0;
    long perviousTimepneumaticValve2 = 0;
    long previousTimeLocal = 0;
    long interval = 1000;

   The loop() function is below:

    void loop() {
    checkPneumaticValve1();
    checkPneumaticValve2();
    }

    void checkPneumaticValve1() {
      if (millis()-previousTimeLocal>interval) {
        printPneumaticValve1();
        previousTimeLocal=millis();
       }
     }

    void printPneumaticValve1() {
         //Here write your code for PneumaticValve1
       }

    void checkPneumaticValve2() {
       if (millis() - previousTimeLocal > interval) {
         printPneumaticValve2();
         previousTimeLocal=millis();
       }
      }

    void printPneumaticValve2() {
      //Here write your code for PneumaticValve2
      }


body:
    void loop() {

    ...

      if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH
      )
      {
          digitalWrite(davkovani, LOW);      // extend the second pneumatic cylinder
          delay(4000);
          digitalWrite(davkovani, HIGH);    // retract the second pneumatic cylinder after 4 seconds,
          // this code works when it is alone there, the next if statements not
      }

    ...
    }

If the condition is met, then `davkovani` is going to be LOW 99.999% of the time. It will only briefly go HIGH, as there is no delay there. The loop will iterate and set it LOW again. So it may seem to be "not working" whereas the problem is that it "works" very briefly.


message:
Circuit with buzzer not working :(

so I have a circuit with a buzzer and a resistor:
[![enter image description here][1]][1]

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

This circuit should be working, but for some reason the buzzer doesn't sound. I pushed the buzzer into the breadboard as hard as I could, I put the + side to positive and the - side to negative but it still doesnt work :(. How can I fix this?

Quick curiosity question: When I was doing electricity in school, the teacher just called the buzzers 'buzzers' but when I started doing arduino I noticed that the arduino community seems to call them 'Piezo buzzers/piezo speakers'. Is there any significance in the word 'Piezo' and should I start referring to them as 'Piezo buzzers' myself?

body:
There is two kinds of buzzers - active and passive

 1. Passive buzzer means they can be operated by applying  just logic high to + and low to ground.

Digitalwrite function will do this job

2. Active buzzers needs pulses to make sound. Sound produced depends on the frequency.  Your buzzer might be a passive one. You can make a symphony by applying different frequencies..

'tone' function will help you for this


body: Try the toneAC library if it is a two pin piezo speaker... It generates weak alternating current, using two arduino pins. Your piezo will last longer. Works like old tone library. Remember to put a 100 ohm resistor in series :)


body: Buzzer coils get locked if a higher voltage is applied to the terminals - it could be 5-9 V. Once it gets locked it won't work even if you put direct battery to it. The only solution is to first take out your buzzer and give it a reverse voltage that will get the coil out of the lock position, then put 180 Ω resistor and run. It will work and it will never lock again.


message:
Arduino round to nearest 0.5

I am having a double value for example: 34.26 or 11.92 or 2.51. It should be rounded to the nearest 0.5 so 1.34 -> 1.50 and 32.78 -> 33 and 21.09 -> 21.00

How do to do this?

body:
I made a little algorithm from the first thing that popped into my mind.
I'm using integers, since I believe it works better as floats.

For example, you can represent euro's (with floating points) by expressing them in cents.

    unsigned int roundToFifty(unsigned int nonRound){
        unsigned int rest = nonRound % 50;
        unsigned int fits = floor(nonRound / 50);
        unsigned int add = 0;
        if(rest >= 25){
            if(rest >= 75){
                add = 100
            }else{
                add = 50
            }
        }
        return fits*50+add
    }

I actually think the algorithm is a tad weird and something simpler/more effective could also exist. It was just the first thing that popped into my mind.


body:
It is a very bad idea to use float.
That being said. multiply by 2 and do a standard round.
Then divide back by 2.

For example:

    1.34     *2 = 2.68
    round(2.68) = 3
    3        /2 = 1.5

and

    32.78    *2 = 65.56
    round(65.56)= 66
    66       /2 = 33


body:
    float i=1.5237475984328953;
    #include "math.h"
    void setup()
    {
     Serial.begin(9600);
    }

    void loop() {
     Serial.println(i,6);
     float price = i*1000;
     Serial.println(price,2);

     float roundNearest = roundf(i*1000) ; // x 100 for two decimal place
      roundNearest = roundNearest/1000;
     Serial.println(roundNearest,6);

     price = (roundNearest*1000);
     Serial.println(price,2);
     while(1){}
    }

you u can use roundf()
like in this video [Demo Video][1]

  [1]: https://www.youtube.com/watch?v=pCcANoDHIdU


message:
Problem with code for IR remote controlled robot

I recently wrote the code for this project but it's weird because when I press button on the remote nothing shows up on the Serial Monitor and consequently the robot doesn't respond. I know it's not a hardware issue because when I used the IRrecv Demo sketch values were displayed on the serial monitor

Please tell me what's wrong! I'm sure there are a lot of talented programmers out there!!

    #include <IRremote.h>
    #include <AFMotor.h>
    AF_DCMotor rightMotor(1); // Right motor connected to port 1
    AF_DCMotor leftMotor(2); // Left motor connected to port 2
    IRrecv irrecv(A2);// IR receiver connected to pin A2(ANALOG PINS ON MOTOR             SHIELD USED AS DIGITAL INS!)
    decode_results results;
    #define Straight 0xC1CC42BD
    #define Right 0xC1CCA25D
    #define Left 0xC1CC22DD
    #define Back 0xC1CCC23D

    void setup(){
      Serial.begin(9600); // Establishing Serial Communication, THIS IS     IMPORTANT!!
      irrecv.enableIRIn(); // Start the receiver
    }
    void loop() {
      if (irrecv.decode(&results))
      {
          Serial.println(results.value, HEX);

          if((results.value)== Straight)
          {
          moveForward();
          }
          if((results.value)== Right)
          {
            turnRight();
           }
          if((results.value)== Left)
          {
            turnLeft();
          }
          if((results.value)== Back)
          {
            moveBackward();
          }
          else
          {
            Stop();
          }
          irrecv.resume();
      }
      delay(100);
    }

    void moveForward() {

        leftMotor.setSpeed(255);
        rightMotor.setSpeed(255);
        leftMotor.run(FORWARD);
        rightMotor.run(FORWARD);
    }

    void turnRight(){

      leftMotor.setSpeed(200);
      rightMotor.setSpeed(200);
      leftMotor.run(FORWARD);
      rightMotor.run(BACKWARD);
      delay(400);

      leftMotor.run(FORWARD);
      rightMotor.run(FORWARD);
    }

    void turnLeft() {

      leftMotor.setSpeed(200);
      rightMotor.setSpeed(200);
      leftMotor.run(BACKWARD);
      rightMotor.run(FORWARD);
      delay(400);

      leftMotor.run(FORWARD);
      rightMotor.run(FORWARD);
    }
    void moveBackward() {

        leftMotor.setSpeed(200);
        rightMotor.setSpeed(200);
        leftMotor.run(BACKWARD);
        rightMotor.run(BACKWARD);
    }

    void Stop(){
        leftMotor.setSpeed(0);
        rightMotor.setSpeed(0);

    }

body:
Try replacing you loop function with this one.  It won't fix it.

    void loop()
    {
     if (irrecv.decode(&results))
     {
      Serial.println(results.value, HEX);

      switch (results.value)
      {
      case Straight:
       moveForward();
       break;
      case Right:
       turnRight();
       break;
      case Left:
       turnLeft();
       break;
      case Back:
       moveBackward();
       break;
      default:
       Stop();
      }
      irrecv.resume();
     }
     else
     {
      Serial.println ("Nothing received"); // This message will annoy you so comment it out as soon as you are happy with what is happening.
     delay(100);
    }

The switch statement is just a neater way of doing your ifs.  The Nothing received message will show you if decode is ever returning.  If it is returning you need to work out why it is returning false, by looking in the library code.  If it isn't returning then you need to look in the library code and see why.  If it is returning, but not giving you an expected value, you need to look in the library code and see why.

Sorry but from what you describe it seems to be an issue with the library or your use of it, could be anything, but when you can get some more info post it back here.


body:
You are using two libraries ([Arduino-IRremote][1] & [Adafruit-Motor-Shield-library][2]) which both use Timer2 on the microcontroller.

The motor library actually changes the setup of timer 2 (see line 92 of AFMotor.cpp) which will disrupt the timing that the IR sensor uses to determine the IR code received.

As far as I can see, the IR library is using Timer2 only. This means you should be able to change your motors over to port 3 & 4 which use Timer0 instead.

    AF_DCMotor rightMotor(3); // Right motor connected to port 3
    AF_DCMotor leftMotor(4); // Left motor connected to port 4

  [1]: https://github.com/z3t0/Arduino-IRremote
  [2]: https://github.com/adafruit/Adafruit-Motor-Shield-library


message:
How to turn servo to a specific location and then turn over

I work on my first arduino car project and i want to turn my servo to a position with a letter input

This is my code so far

     #include <Servo.h>
    Servo servo;

     void setup() {
     Serial.begin(9600);
    pinMode(7,OUTPUT);
    pinMode(8,OUTPUT);
     }

     void loop() {

     if(Serial.available()>0){
     int  caz=Serial.read();
     switch(caz)
    {
      case 'w':
          digitalWrite(8,LOW);
          digitalWrite(7,HIGH);
          break;
      case 's':
          digitalWrite(7,LOW);
          digitalWrite(8,HIGH);
          break;
      case'd':
           servo.attach(12);
           servo.write(0);
           break;
      case'a':
           servo.attach(11);
           servo.write(180);
           break;
       default:
           digitalWrite(7,LOW);
           digitalWrite(8,LOW);
           servo.attach(0);
      }
    }

when i input 'a' or 'd' it starts turning until i input something else and i want it to stop after 10-30 degree .

And also i would like to do that to my motor , moving a bit when i input the key.

body:
Rather than writing to 180 and 0 write to a variable.

    static const int MovementAmount = 30; //degrees
    int position = 90;  // 90 is the start position.
    ...
    case 'd':
       servo.attach(12);
       position += MovementAmount;
       if (position > 180)
       {
         position = 180;
       }
       servo.write(position);
       break;


message:
POST data from Arduino to website

I am working on a project where I am trying to send data using HTTP and POST method from my Arduino Mega2560 to a website which I host on localhost. I am living to a students' accommodation and thus, I do not have access to the router. However, I have bought a router and have connected it to the wall via the WAN. Also, the Arduino is connected to one of the ethernet plugs of the router via an Ethernet shield and my laptop to another ethernet plug. I am trying to retrieve the data from the website, but I cannot seem to load them.

**Arduino Code**

    #include <dht.h>
    #include <SPI.h>
    #include <Ethernet.h>

    dht DHT1;
    int temperatureSensorPin1 = 25;

    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    EthernetClient client;
    EthernetServer server(80);

    long previousMillis = 0;
    unsigned long currentMillis = 0;
    long interval = 250000;
    String data;

    long lastUpdate = 0;

    void setup() {

      Serial.begin(9600);
      if(Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
      }

      data = "";

      pinMode(temperatureSensorPin1, INPUT);
    }

    void loop() {

    int temp1 = DHT1.read11(temperatureSensorPin1);

    switch (temp1)
      {
        case DHTLIB_OK:
            Serial.print("OK,\t");
            break;
        case DHTLIB_ERROR_CHECKSUM:
            Serial.print("Checksum error,\t");
            break;
        case DHTLIB_ERROR_TIMEOUT:
            Serial.print("Time out error,\t");
            break;
        case DHTLIB_ERROR_CONNECT:
            Serial.print("Connect error,\t");
            break;
        case DHTLIB_ERROR_ACK_L:
            Serial.print("Ack Low error,\t");
            break;
        case DHTLIB_ERROR_ACK_H:
            Serial.print("Ack High error,\t");
            break;
        default:
            Serial.print("Unknown error,\t");
            break;
      }

      currentMillis = millis();
      if(currentMillis - previousMillis > interval) {
        previousMillis = currentMillis;
      }
      String data="temp1="+String(DHT1.temperature, 0)+"&temp2="+String(DHT2.temperature, 0)+"&temp3="+String(DHT3.temperature, 0)+"&temp4="+String(DHT4.temperature, 0)+"&temp5="+String(DHT5.temperature, 0)
                      +"&hum1="+String(DHT1.humidity, 0)+"&hum2="+String(DHT2.humidity, 0)+"&hum3="+String(DHT3.humidity, 0)+"&hum4="+String(DHT4.humidity, 0)+"&hum5="+String(DHT5.humidity, 0)+"&gas="+gasValue;

      Serial.println(Ethernet.localIP());
      if(client.connect("192.168.0.1", 80)) {
        client.println("POST /home/visualisation.php HTTP/1.1");
        client.println("Host:  192.168.0.1");
        //client.println("User-Agent: Arduino/1.0");
        //client.println("Connection: close");
        client.println("Content-Type: application/x-www-form-urlencoded;");
        client.print("Content-Length: ");
        client.println(data.length());
        client.println();
        client.print(data);
        //Serial.println(data);
        Serial.println("We have connection");
      }

      if(client.connected()) {
        Serial.println("We have abc");
        client.stop();
      }

      delay(4000);
    }

**PHP Code**

    <?php
    $temp1 = "";
    if(isset($_POST['temp1'])) {
     $temp1 = $_POST['temp1'];
    }
    echo $temp1;
    ?>
[Windows ip configuration][1]
[Router ip configuration][2]

Is the connection that I have made the appropriate one? How should I do it in order to work?

P.S.: I would like to clarify that I do not have an extended knowledge regarding networking.

**Router ip configuration**
*LAN*
MAC Address: 60-E3-27-E7-70-7A
IP Address: 192.168.0.1
Subnet Mask: 255.255.255.0

*Wireless*
Wireless Radio: Enable
Name (SSID): TP-LINK_707A
Mode: 11bgn mixed
Channel Width: Automatic
Channel: Auto (Current channel 3)
MAC Address: 60-E3-27-E7-70-7A
WDS Status: Disable

*WAN*
MAC Address: 60-E3-27-E7-70-7B
IP Address: 100.66.166.2 Dynamic IP
Subnet Mask: 255.255.255.192
Default Gateway: 100.66.166.1

DNS Server: 77.244.128.44 , 77.244.128.45

[![Windows ip configuration][1]][1]

  [1]: https://i.stack.imgur.com/FMhoZ.png

body:
The ip that I have Arduino send data to is the router's and thus, I should have used the 192.168.0.100 ip which is the one of my computer.

I also needed to save the value to a database to notice the changes because *echo $temp1;* did not seem to work, probably I should have it included into HTML *label* tags. Anyway, I just loaded the value from the database into a PHP variable and I was able to accomplish the task.


message:
connecting 3.3V to +3V

Well, I hope this question won' t be buried to the dark depths of this forum as my previous q' s:) But I suppose it won' t this time cause it's pretty short without this introduction part...

I have an Arduino pro mini works with 3.3V and in the other hand, I have a DS1307 DIP ic, works with +3V. I was wondering if I could connect the ic to my Arduino directly.

Thats all. Thanks already:)

body: The 3V input on the DS1307 is for a 3V battery, usually a CR2032 or similar. The *supply* voltage of the DS1307 is 5V, which means that it won't work with a 3.3V Arduino without a separate supply and level shifter.


message:
Voice recognition module: avrdude: stk500_getsync(): not in sync: resp=0x00

I am using a GeeeTech voice recognition module, I have recorded my voices using CoolTerm, and imported these voice commands in my sketch. However, when I plug in that voice recognition module, an error gets thrown: `avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00`; otherwise, it uploads normally. How can the computer and the Arduino lose connection when the voice recognition module gets plugged in? [![This is the USB that I used to record my commands][1]][1][![This is the Geetech voice recognition module I am using][2]][2]. I have checked my com ports, and checked the everything that it is connected to is correct.

  [1]: https://i.stack.imgur.com/LNtvb.png
  [2]: https://i.stack.imgur.com/rl7BJ.png

    #include <avr/sleep.h>
    #include <avr/power.h>
    //#include "math.h"
    //This sketch is a metronome, in which each led pin shows one beat.
    /**************************************/
    const int speaker = 13;//speaker at pin 13
    int ts = 6;//highest led pin
    int count = 3;//"beat 1 pin"
    const int keyPin = 11;//button to change time signature
    const int keyPinR = 10;//button to change rhythm
    const int keySwitch = 2;//sleep mode/wake up button

    //All pins below use a pull-up resistor, so the states are inverted
    int buttonState = LOW;
    int buttonState2 = LOW;
    int switchState = LOW;
    int silentState = LOW;

    int bpm = 120;//you do not need to know this,
    //it's just a variable for the potentialmeter to change the tempo
    int comdata;

    int rthm = 1;//rhythm
    int pressed = 0;//
    long silent = 0;

    byte com = 0; //reply from voice module
    /**************************************/

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

     for(int thisPin = 3;thisPin <= ts;thisPin++)
      {
         pinMode(thisPin,OUTPUT); //initialize thisPin as an output
         pinMode(12, INPUT); //potentialmeter for changing tempo

       //Pin 9 to 11, along with pin 2, are all push buttons with pull-up resistors
        for(int i = 9; i<=11; i++)
        {
          pinMode(i, INPUT);
          digitalWrite(i, HIGH);
        }
        pinMode(2, INPUT);
        digitalWrite(2,HIGH);
      }
    delay(2000);

    //imported voice commands
    Serial.write(0xAA);
    Serial.write(0x37);
    delay(1000);
    Serial.write(0xAA);
    Serial.write(0x21);

     Serial.print("Type in beats per minute");

    }

    /****************************************/
    void loop()
    {
      turnOn();
      getTS();
      getVoiceCommand();
    }

    void turnOn()
    {
        buttonState = digitalRead(keyPin);//key for
        buttonState2 = digitalRead(keyPinR);
        switchState = digitalRead(keySwitch);
        silentState = digitalRead(9);

        if(switchState==LOW) pressed++;

        if(pressed!=0)
        {
          sleep_enable();
          set_sleep_mode(SLEEP_MODE_PWR_DOWN);
          attachInterrupt(0, interrupt, LOW);
          sleep_cpu();
        }

      else{
        //The beat starts at pin 3, runs in consecutive pins, and ends at pin 8 at maximum

         if(buttonState==LOW){//changing time signature - up to 5 beats
                ts++;
              if(ts==8) ts = 3;  //8 - 3 = 5 beats max
         }
         if(buttonState2==LOW){//changing rhythm - quarter note to eighth, then
                 //triplets and sixteenths, back to quarter notes
               rthm++;
              if(rthm==5) rthm = 1;
         }
         if(silentState==LOW) silent++; //if silent key pressed, go to silence (only LED's showing)

          runMetronome();//Run the metronome
         }
      }

      void runMetronome(){
        for(int thisPin = 3;thisPin <= ts;thisPin++)
          //LED's blinking beats (thisPin - LED pin (beat number + 2))
          {
               for(int r = 1; r<=rthm; r++){//nested loop for the rhythm
                   bpm = pulseIn(12, HIGH);//pin 12 - tempo potentialmeter
                   digitalWrite(thisPin,HIGH);//each LED blinks
                   pinMode(13,OUTPUT); //pin 13 - speaker

                  silent%2==0 ? noTone(13) : (count==3 && r==1 ? tone(13,4400,80) :
                       r==1 ? tone(13,2500,80) : tone(13,2200,60));
                  delay((bpm-52)/rthm);
                  digitalWrite(thisPin,LOW);//turn each off as we proceed to the next beat (LED)
                  pinMode(13,INPUT);//speaker input
                }
              count++;//beat++

              if(count>ts) count = 3; //go back to beat 1
            }
        }

      void interrupt()  {
          sleep_disable();
          detachInterrupt(0);
      }

       void getTS(){
          if(Serial.available()>0){
              comdata = Serial.read();
              switch (comdata){
                  case '1': ts = 3; break;
                  case '2': ts = 4; break;
                  case '3': ts = 5; break;
                  case '4': ts = 6; break;
                  case '5': ts = 7; break;
                }
         }
       }
         void getVoiceCommand(){
            while(Serial.available()){
                com = Serial.read();
                switch(com){
                    case 0x11: ts = 3; break;
                    case 0x12: ts = 4; break;
                    case 0x13: ts = 5; break;
                    case 0x14: ts = 6; break;
                    case 0x15: ts = 7; break;
                  }
              }
          }

body:
It's not loosing connection, there just can't be two devices on the same serial port (I suppose this setup)

You can use software serial for VR module, arduino with more hardware serials (=mega) or you can use another arduino as ISP programmer.


message:
millis() function always returns same value

I'm trying to program an Arduino MKR1000 and I am using the `millis()` function to emulate a traditional timer.  The problem is that any call to `millis()` inside the `debounceTimer()` function returns the same value.  I only added the `Serial.print` to debug.

I left out a decent bit of the code to simplify your reading of it.  It works by waiting for an interrupt on pin 4 which then calls the `runTimers()` function and that calls the `debounceTimer()` function and within that the `millis()` function is called. The `debouncetimer()` function keeps getting called until the 10 ms has elapsed and then should end the timer.  The problem is that the `millis()` function stops returning a value that goes up.

    #define doorIntPin 4
    unsigned char sysEnabled = 0;
    unsigned long debounceTimerPlace =0;
    unsigned char debounceTimerOn =0;

    void setup() {
      Serial.begin(9600);
      attachInterrupt(doorIntPin, doorOpens, LOW);
      interrupts();
    }

    void loop() {

    }
    void runTimers(){
      Serial.print('r');
      while(alarmTimerOn || debounceTimerOn || enablingTimerOn){
         if(alarmTimerOn)
          alarmTimer();
        if(enablingTimerOn)
          enablingTimer();
        if(debounceTimerOn)
          debounceTimer();
      }
    }

    void debounceTimer(){
      unsigned long time = millis()- debounceTimerPlace;
      Serial.println(millis() & 0xFFFF, DEC);
      if(sysEnabled && time> 10){
        debounceTimerOn=0;
      }
    }
    void doorOpens() {
      Serial.print('o');
      if(!debounceTimerOn){
          debounceTimerPlace = millis();
          debounceTimerOn=1;
      }
      runTimers();
    }

I suspect that in the background an interrupt is being called than increments the value `millis()` returns and somehow my external interrupt is disabling that.  I don't know why this is happening or how to fix it.

Any ideas?

body: You never exit the ISR, hence all interrupts are disabled. Do the *minimum* work possible within an ISR, and have the main loop outside.


body: To answer your question about millis(), it uses interrupts to function, and so you can't call it within an ISR.  According to this: https://www.arduino.cc/en/Reference/AttachInterrupt, you should be able to use delayMicrosconds() within an ISR, since it (reportedly) doesn't use interrupts.


body:
> The problem is that the millis() function stops returning a value that goes up.

That's right. The value returned by `millis()` is incremented by an ISR which won't be called inside your other ISR.

You can use `micros()` which *will* increment. However that will only be good up to approximately 1 ms. The main rule of ISRs is that you don't attempt to do delays inside them.


message:
Arduino MCP23S17 I/O Expander (SPI)

I found this [post][1] and I am having almost the exact same issue. Nick Gammon (the god of arduino) has an excellent answer but I can't for the life of me implement it myself. I am not an advanced user like the initial question asker.

So What I want to do is use 2 MCP23S17's ([picture here][2]).
I have been messing with one of them all week and have it reading like a charm. I am using the [githib library][3] by n0mjs710 to do this. But writing to one will not work.

Along with the zipped library is a few examples. I am trying to read some BCD switches off of one "input MCP" and then display the digits on the "output MCP"

I have used external pullups so I did make one change to the code by commenting out the call for pullups. Here is what Doesn't work:

    #include <SPI.h>              // We use this library, so it must be called here.
    #include <MCP23S17.h>         // Here is the new class to make using the MCP23S17 easy.

    MCP inputchip(1, 10);             // Instantiate an object called "inputchip" on an MCP23S17 device at address 1
                 // and slave-select on Arduino pin 10
    MCP outputchip(2, 10);            // Instantiate an object called "outputchip" on an MCP23S17 device at address 2
                // and slave-select on Arduino pin 10

    void setup() {
      inputchip.begin();
      outputchip.begin();
      inputchip.pinMode(0xFFFF);     // Use word-write mode to set all of the pins on inputchip to be inputs
      //inputchip.pullupMode(0xFFFF);  // Use word-write mode to Turn on the internal pull-up resistors.
      inputchip.inputInvert(0xFFFF); // Use word-write mode to invert the inputs so that logic 0 is read as HIGH
      outputchip.pinMode(0x0000);    // Use word-write mode to Set all of the pins on outputchip to be outputs
    }

    void loop() {
      int value;                        // declare an integer to hold the value temporarily.
      value = inputchip.digitalRead();  // read the input chip in word-mode, storing the result in "value"
      outputchip.digitalWrite(value);   // write the output chip in word-mode, using our variable "value" as the argument
      // outputchip.digitalWrite(inputchip.digitalRead()); // this one line replaces the three above, and is more efficient
    }

I have tried:

 - slowing the SPI bus by changing the library to SPI_Divide the clock by 2
 - changing the ss line and even splitting the lines so one chip uses pin 10 and the other uses pin 9

So after reading Mr. Gammon's post I have made some changes to the code attempting to rid myself ***of the old slave select pin low trick*** he mentioned. Here is my attempt:

    MCP inputchip(1, 10);             // Instantiate an object called "inputchip" on an MCP23S17 device at address 1
                 // and slave-select on Arduino pin 10
    MCP outputchip(2, 9);            // Instantiate an object called "outputchip" on an MCP23S17 device at address 2
                // and slave-select on Arduino pin 10
    int ssPin = 9;

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

      inputchip.begin();
      digitalWrite(ssPin, HIGH);
      digitalWrite(ssPin, LOW);
      outputchip.begin();
      inputchip.pinMode(0xFFFF);     // Use word-write mode to set all of the pins on inputchip to be inputs
      //inputchip.pullupMode(0xFFFF);  // Use word-write mode to Turn on the internal pull-up resistors.
      inputchip.inputInvert(0xFFFF); // Use word-write mode to invert the inputs so that logic 0 is read as HIGH
      digitalWrite(ssPin, HIGH);
      digitalWrite(ssPin, LOW);
      outputchip.pinMode(0x0000);    // Use word-write mode to Set all of the pins on outputchip to be outputs
    }

    void loop() {
      int value;
      // declare an integer to hold the value temporarily.
      value = inputchip.digitalRead();  // read the input chip in word-mode, storing the result in "value"
      digitalWrite(ssPin, HIGH);
      digitalWrite(ssPin, LOW);
      outputchip.digitalWrite(value);   // write the output chip in word-mode, using our variable "value" as the argument
    }

So any advice would be great to get this working. Help me Obi wan Gammon your me only hope.

  [1]: https://arduino.stackexchange.com/questions/14191/mcp23s17-programming-iodirx-register-works-in-loop-but-not-in-setup
  [2]: https://i.stack.imgur.com/XZman.jpg
  [3]: https://github.com/n0mjs710/MCP23S17

body: Majenko's library works. All praise to Majenko https://github.com/MajenkoLibraries/MCP23S17


body:
This sketch uses the [Majenko Library][1] with two MCP23S17 chips to demonstrate the library functions.

It was tested on an Arduino Uno with IDE 1.6.5.

    /*
     * MultiTest_Majenko_02.ino
     * Library Ref: github.com/MajenkoLibraries/MCP23S17
     *
     * Lowell Bahner
     * 2016-12-11
     *
     * Hardware: Arduino UNO
     * IDE: Arduino 1.6.5
     *
     * Useful SPI Ref: gammon.com.au/spi
     *
     * Wire the SPI Interface common lines (Mega2560 SPI pins shown in [ ]):
     * Arduino SPI_MOSI pin 11 [51] <->   SI  MCP23S17 pin 13
     * Arduino SPI_MISO pin 12 [50] <->   SO  MCP23S17 pin 14
     * Arduino SPI_CLOCK pin 13 [52]<->   SCK MCP23S17 pin 12
     * Arduino SPI_CS pin 10 [53]   <->   SS  MCP23S17 pin 11
     * MCP23S17 VDD pin 9 to +5V
     * MCP23S17 VSS pin 10 to Gnd
     * MCP23S17 Reset pin 18 to +5V
     * MCP23S17 Interrupt pins 19-20
     * MCP23S17 A0,A1,A2 pins connect to Gnd or +5V (000 = Address 0, 100 = Address 1, 010 = Address 2, etc)
     * MCP23S17 Port A pins are chip pins 21-28
     * MCP23S17 Port B pins are chip pins 1-8
     *
     * This sketch runs a series of functions to demonstrate library capabilities.
     * This sketch does not demonstrate interrupt functionality.
     *
     * This sketch instantiates 2 MCP23S17 chips.
     * Bank2 (MCP23S17 address 1) pins are set as INPUT or INPUT_PULLUP.
     *    Normally HIGH, use switch to set a pin LOW.
     * Bank1 (MCP23S17 address 0) pins are set as OUTPUT.
     *    MCP23S17 outputs will power LEDs up to 25ma through 1000ohm resistor to ground.
     *
     * Majenko MCP23S17 library functions (see .h,.cpp files for details):
     *
     *  bank.pinMode(uint8_t pin, uint8_t mode)
     *    where modes are:
     *      OUTPUT - sets pin HIGH
     *      INPUT  - sets pin LOW for sensing change to HIGH +V
     *      INPUT_PULLUP - sets pin HIGH for sensing change to LOW 0V
     *
     *  bank.digitalWrite(uint8_t pin, uint8_t value)
     *    if mode=OUTPUT, pin value = LOW (0) or HIGH (1)
     *    if mode=INPUT, value LOW disables pullup on pin, value HIGH enables pullup on pin
     *
     *  uint8_t value = bank.digitalRead(uint8_t pin)
     *    read the state of the pin
     *
     *  uint8_t value = bank.readPort(uint8_t port)
     *    read entire 8-bit port of all INPUT pins on Port A (port=0) or Port B (port>=1)
     *
     *  uint16_t longValue = bank.readPort()
     *    read both ports as 16-bit combined
     *
     *  bank.writePort(uint8_t port, uint8_t val)
     *    write val (0 or 1, hex example 0x55) to all OUTPUT pins on Port A (port=0) or Port B (port>=1)
     *
     *  bank.writePort(uint16_t val)
     *    write val (hex example 0x55AA) to all OUTPUT pins on Port A and Port B
     *
     *  Also, interrupt functions are defined:
     *      enableInterrupt(uint8_t pin, uint8_t type);
     *      void disableInterrupt(uint8_t pin);
     *      void setMirror(boolean m);
     *      uint16_t getInterruptPins();
     *      uint16_t getInterruptValue();
     *      void setInterruptLevel(uint8_t level);
     *      void setInterruptOD(boolean openDrain);
     *
     *
     *
     *
    Run Sketch: Serial Monitor Output

     -- RWpins() --

    Bank2: Switch i15: 1 (Push button switch not pushed, Bank2 INPUT pin 15 is HIGH +5V)
    Bank1: Output j4:  1 (Bank1 OUTPUT pin 4 is HIGH.
                          Arduino pin 7 is set HIGH.
                          LED on pin 4 is ON. LED on pin 7 is ON.)

    Bank2: Switch i15: 0 (Push button switch pushed, grounds Bank2 INPUT pin 15)
    Bank1: Output j4:  0 (Bank1 OUTPUT pin 4 switches to LOW.
                          Arduino pin 7 is set LOW.
                          LED on pin 4 is OFF. LED on pin 7 is OFF.)

     -- RWport() --

    Bank1: Port A BIN: 00000000
    Bank1: Port B BIN: 00000000

    Bank1: Port A BIN: 11110100  DEC: 244
    Bank1: Port B BIN: 00001011  DEC: 11

     -- RWlongPortValue() --

    Bank1: Port A & B BIN: 0000101111110100  HEX: 0x0BF4    DEC: 3060

     -- RWlongPort() --

    Bank1: Port A & B BIN: 1011100101000010  HEX: 0xB942    DEC: 47426

     -- CyclePins() --

    Bank1: Port A & B BIN: 0000000000000000  HEX: 0x0000    DEC: 0
    Bank1: Port A & B BIN: 0000000000000001  HEX: 0x0001    DEC: 1
    Bank1: Port A & B BIN: 0000000000000011  HEX: 0x0003    DEC: 3
    Bank1: Port A & B BIN: 0000000000000111  HEX: 0x0007    DEC: 7
    Bank1: Port A & B BIN: 0000000000001111  HEX: 0x000F    DEC: 15
    Bank1: Port A & B BIN: 0000000000011111  HEX: 0x001F    DEC: 31
    Bank1: Port A & B BIN: 0000000000111111  HEX: 0x003F    DEC: 63
    Bank1: Port A & B BIN: 0000000001111111  HEX: 0x007F    DEC: 127
    Bank1: Port A & B BIN: 0000000011111111  HEX: 0x00FF    DEC: 255
    Bank1: Port A & B BIN: 0000000111111111  HEX: 0x01FF    DEC: 511
    Bank1: Port A & B BIN: 0000001111111111  HEX: 0x03FF    DEC: 1023
    Bank1: Port A & B BIN: 0000011111111111  HEX: 0x07FF    DEC: 2047
    Bank1: Port A & B BIN: 0000111111111111  HEX: 0x0FFF    DEC: 4095
    Bank1: Port A & B BIN: 0001111111111111  HEX: 0x1FFF    DEC: 8191
    Bank1: Port A & B BIN: 0011111111111111  HEX: 0x3FFF    DEC: 16383
    Bank1: Port A & B BIN: 0111111111111111  HEX: 0x7FFF    DEC: 32767
    Bank1: Port A & B BIN: 1111111111111111  HEX: 0xFFFF    DEC: 65535

    Bank1: Port A & B BIN: 1111111111111111  HEX: 0xFFFF    DEC: 65535
    Bank1: Port A & B BIN: 0111111111111111  HEX: 0x7FFF    DEC: 32767
    Bank1: Port A & B BIN: 0011111111111111  HEX: 0x3FFF    DEC: 16383
    Bank1: Port A & B BIN: 0001111111111111  HEX: 0x1FFF    DEC: 8191
    Bank1: Port A & B BIN: 0000111111111111  HEX: 0x0FFF    DEC: 4095
    Bank1: Port A & B BIN: 0000011111111111  HEX: 0x07FF    DEC: 2047
    Bank1: Port A & B BIN: 0000001111111111  HEX: 0x03FF    DEC: 1023
    Bank1: Port A & B BIN: 0000000111111111  HEX: 0x01FF    DEC: 511
    Bank1: Port A & B BIN: 0000000011111111  HEX: 0x00FF    DEC: 255
    Bank1: Port A & B BIN: 0000000001111111  HEX: 0x007F    DEC: 127
    Bank1: Port A & B BIN: 0000000000111111  HEX: 0x003F    DEC: 63
    Bank1: Port A & B BIN: 0000000000011111  HEX: 0x001F    DEC: 31
    Bank1: Port A & B BIN: 0000000000001111  HEX: 0x000F    DEC: 15
    Bank1: Port A & B BIN: 0000000000000111  HEX: 0x0007    DEC: 7
    Bank1: Port A & B BIN: 0000000000000011  HEX: 0x0003    DEC: 3
    Bank1: Port A & B BIN: 0000000000000001  HEX: 0x0001    DEC: 1
    Bank1: Port A & B BIN: 0000000000000000  HEX: 0x0000    DEC: 0
     *
     *
     *
     */

    // Majenko MCP23S17 Library
    #include <MCP23S17.h>

    // Arduino Library SPI.h
    #include <SPI.h>

    // SPI CS/SS chipselect pin can be changed by user as desired
    const uint8_t chipSelect = 10;

    // example Arduino board pin
    uint8_t pin7 = 7;

    // Create an object for each chip
    // Bank1 is address 0. Pins A0,A1,A2 grounded.
    // Bank2 is address 1. Pin A0=+5V, A1,A2 grounded.

    MCP23S17 Bank1(&SPI, chipSelect, 0);
    MCP23S17 Bank2(&SPI, chipSelect, 1);

    void setup() {

      // Slow down the master a bit if desired
      SPI.setClockDivider(SPI_CLOCK_DIV8);

      Serial.begin(9600);

      Bank1.begin();
      Bank2.begin();

      // LED connected to Arduino pin 7 to test inter-device communication
      pinMode(pin7, OUTPUT);

      //
      // Set MCP23S17 pin modes:
      // example set one pin: chip.pinMode(0, OUTPUT); // sets chip pin 0 (Port A 0) to OUTPUT mode
      //
      // setChipPins(); // use loop to set individual pins
      // or, since this library does not have a setPortPinMode, do 8 pin loops
      setPortPins(); // example: set pins on each Port on each chip to different modes.
      //

    }

    // Set all Chip pins to desired mode
    void setChipPins() {
      // Example usage

      // Set all Bank1 pins to be OUTPUT
      for (uint8_t i = 0; i <= 15; i++)
        Bank1.pinMode(i, OUTPUT);

      // Set all Bank2 pins to be INPUT_PULLUP
      for (uint8_t i = 0; i <= 15; i++)
        //Bank2.pinMode(i, INPUT);  // unswitched pin voltages about +0.1V, switch must pull pin to +5V
        Bank2.pinMode(i, INPUT_PULLUP);  // unswitched pin voltages about +4.9V, switch must ground pin
    }

    // Set Port pins to desired mode
    void setPortPins() {
      // Example usage

      // Set all Bank1 Port A pins to OUTPUT
      for (uint8_t i = 0; i <= 7; i++)
        Bank1.pinMode(i, OUTPUT);

      // Set all Bank1 Port B pins to OUTPUT
      for (uint8_t i = 8; i <= 15; i++)
        Bank1.pinMode(i, OUTPUT);

      // Set all Bank2 Port A pins to be INPUT
      for (uint8_t i = 0; i <= 7; i++)
        Bank2.pinMode(i, INPUT);

      // Set all Bank2 Port B pins to be INPUT_PULLUP
      for (uint8_t i = 8; i <= 15; i++)
        Bank2.pinMode(i, INPUT_PULLUP);
    }

    //
    // Change LED On/Off with button push
    // 1) Switch an INPUT_PULLUP pin to ground
    // 2) Read the pin value
    // 3) Write the value to an OUTPUT pin
    // 4) Turn LED On/Off
    // Use functions digitalRead(pin) and digitalWrite(pin,value)
    //
    void RWpins() {

      Serial.print("\n -- RWpins() --"); Serial.println("");

      uint8_t b15 = 0;  // Bank2 input pin value (0 push LOW, 1 normally open HIGH) with push button switch to gnd
      uint8_t i = 15;   // Bank2 pin number
      uint8_t a4 = 0;   // Bank1 output pin value
      uint8_t j = 4;    // Bank1 pin number

      // read the switch value into b15
      b15 = Bank2.digitalRead(i);
      Serial.print("\nBank2: Switch i"); Serial.print(i); Serial.print(": ");  Serial.println(b15);

      // write the switch pin i, value b15, to the output pin j
      Bank1.digitalWrite(j, b15);

      a4 = Bank1.digitalRead(j);
      Serial.print("Bank1: Output j"); Serial.print(j); Serial.print(": ");  Serial.println(a4);

      // Turn on/off LED connected to Arduino pin 7 through resistor to ground
      digitalWrite(pin7, a4);
    }

    //
    // Read and Write Port values
    //
    void RWport() {

      Serial.print("\n -- RWport() --"); Serial.println("");

      // set the port pin modes
      setPortPins(); // all Bank1 pins are OUTPUT but set as Ports

      // clear the port pin values to 0
      uint8_t port = 0; // Port A
      uint8_t val = 0x00; // set to 0000 0000
      Bank1.writePort(port, val);
      port = 1; // Port B
      Bank1.writePort(port, val); // set to 0000 0000

      // read the port pin values
      uint8_t valueA = Bank1.readPort(0);
      Serial.print("\nBank1: Port A BIN: "); print8Bits(valueA); Serial.println("");
      uint8_t valueB = Bank1.readPort(1);
      Serial.print("Bank1: Port B BIN: "); print8Bits(valueB); Serial.println("");

      // set the port pin values
      port = 0; // Port A
      val = 0xF4; // set to 1111 0100
      Bank1.writePort(port, val);
      port = 1; // Port B
      val = 0x0B; // set to 0000 1011
      //val = 0xB0; // set to 1011 0000
      Bank1.writePort(port, val);

      // read the port pin values
      valueA = Bank1.readPort(0);
      Serial.print("\nBank1: Port A BIN: "); print8Bits(valueA);
      Serial.print("  DEC: "); Serial.println(valueA, DEC);

      valueB = Bank1.readPort(1);
      Serial.print("Bank1: Port B BIN: "); print8Bits(valueB);
      Serial.print("  DEC: "); Serial.println(valueB, DEC);
    }

    void RWlongPortValue() {

      Serial.print("\n -- RWlongPortValue() --"); Serial.println("");

      // Read the Bank1 Port pin values as a combined long value
      uint16_t valueLong = Bank1.readPort();
      Serial.print("\nBank1: Port A & B BIN: "); print16Bits(valueLong);
      Serial.print("  HEX: "); crPrintHEX(valueLong, 4);
      Serial.print("  DEC: "); Serial.println(valueLong, DEC);
    }

    void RWlongPort() {

      Serial.print("\n -- RWlongPort() --"); Serial.println("");

      // Write the Bank1 Port pin values as a combined long value
      uint16_t valueLong = 0xB942;
      Bank1.writePort(valueLong);

      // Read the Bank1 Port pin values as a combined long value
      uint16_t valueLongIn = Bank1.readPort();
      Serial.print("\nBank1: Port A & B BIN: "); print16Bits(valueLongIn);
      Serial.print("  HEX: "); crPrintHEX(valueLongIn, 4);
      Serial.print("  DEC: "); Serial.println(valueLongIn, DEC);
    }

    //
    // Cycle through OUTPUT pins with count-up count-down
    //
    void CyclePins() {

      Serial.print("\n -- CyclePins() --"); Serial.println("\n");

      // Set all Bank1 pins to be OUTPUT
      for (uint8_t i = 0; i <= 15; i++)
        Bank1.pinMode(i, OUTPUT);

      // clear Bank1 using writePort
      uint16_t valueLong = 0x0000;
      Bank1.writePort(valueLong);

      // Read the Bank1 Port pin values as a combined long value
      for (int8_t i = -1; i <= 15; i++) {
        if (i >= 0) Bank1.digitalWrite(i, 1); // i=-1 allows print of 0 data
        valueLong = Bank1.readPort(); // read 16 bits
        Serial.print("Bank1: Port A & B BIN: "); print16Bits(valueLong);
        Serial.print("  HEX: "); crPrintHEX(valueLong, 4);
        Serial.print("  DEC: "); Serial.println(valueLong, DEC);
      }

      Serial.println("");

      for (int8_t i = 15; i >= -1; i--) { // i=-1 allows print of 0 data
        // decrement after the read while reading down the values
        valueLong = Bank1.readPort(); //  read 16 bits
        Serial.print("Bank1: Port A & B BIN: "); print16Bits(valueLong);
        Serial.print("  HEX: "); crPrintHEX(valueLong, 4);
        Serial.print("  DEC: "); Serial.println(valueLong, DEC);
        Bank1.digitalWrite(i, 0);
      }
    }

    void loop() {

      // Change LED On/Off with button push
      RWpins();

      // Read and Write Port pins as a group
      RWport();

      // Read the Bank1 Port pin values as a combined long value
      RWlongPortValue();

      // Read and Write Chip 16 pins as a group
      RWlongPort();

      // Cycle through OUTPUT pins with count-up count-down
      CyclePins();

      delay(1000);

    }

    // print 8-bit byte as 8 bit binary string
    void print8Bits(uint8_t myByte) {
      for (byte mask = 0x80; mask; mask >>= 1) {
        if (mask  & myByte)
          Serial.print('1');
        else
          Serial.print('0');
      }
    }

    // print 16-bit word as 16 bit binary string
    void print16Bits(uint16_t myWord) {
      for (uint16_t mask = 0x8000; mask; mask >>= 1) {
        if (mask  & myWord)
          Serial.print('1');
        else
          Serial.print('0');
      }
    }

    //---------------------------------------------------------------------------------
    // crPrintHEX print value as hex with specified number of digits
    //---------------------------------------------------------------------------------

    void crPrintHEX(unsigned long DATA, unsigned char numChars) {
      unsigned long mask  = 0x0000000F;
      mask = mask << 4 * (numChars - 1);
      Serial.print("0x");
      for (unsigned int i = numChars; i > 0; --i) {
        Serial.print(((DATA & mask) >> (i - 1) * 4), HEX);
        mask = mask >> 4;
      }

      Serial.print("  ");
    }

  [1]: https://github.com/MajenkoLibraries/MCP23S17


message:
Powering Down Arduino MKR1000

The MKR1000 is still pretty new and I'm having a hard time getting good information on it. I'm using the Arduino IDE but don't find any functions to sleep the MKR1000. Most libraries I encounter are for AVR chips while the MKR1000 has an ARM chip. I want to put it to sleep until an external interrupt is called. I also use the millis() function, will this function be rendered useless if it goes to sleep?

In the data sheet for the ATSAMD21 it talks about the Wait for Interrupt instruction which puts the machine to sleep but it doesn't say how to call the instruction. How can I do this in the Arduino IDE?

body:
The [rocketscream low power library][1] looks like it supports the ATSAMD21.

  [1]: https://github.com/rocketscream/Low-Power/commit/9692ae155b0395c1a0676c063995cf06fe761203


message:
How come my code does not wait for a specific time before going into an if statement?

I have an HC-SR04 attached to a servo. When the 90 degree reading is less than 30 cm, I want the motor to take 2 seconds to turn to 130 degrees, get a measurement on the right, and turn back to 90 degrees. My code does not seem to work. Even though I tell it to wait for 2000 ms, it skips directly to the if statement where the turning to 90 degrees is done. Here is the main code:

     #include <Servo.h>
    #define trig 22
    #define echo 24
    long duration;
    boolean turned130 = false;
    int cm50, cm, cm130;
    Servo servo;
    boolean checkRight = false;
    boolean mainPing = true;
    unsigned long counter;
    unsigned long servoTimer = millis();
    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(echo, INPUT);
    pinMode(trig, OUTPUT);
    servo.attach(12);
    servo.write(90);
    delay(2000);

    }

    void loop(){
    counter=millis();//my timer
      if(((counter-servoTimer) >= 250) && mainPing){//distance measured 4 times a second
        ping();
        cm=duration/29.1/2;
        Serial.println(cm);
        servoTimer=counter;//this if statement works fine
      }
      if((cm<30) && mainPing){

        mainPing=false;//makes the 90 degree ping and this if statement unable to run
        checkRight = true;//enables next if statement to run
        servoTimer=millis();
        servo.write(130);
        cm=30;//so that this if statement does not get called again until distance is obtained
        Serial.println("Inside less than 30 loop");//I added this for debugging, to let me know when the loop is called

      }
      if(checkRight && ((counter-servoTimer) >= 2000)){//after 2 seconds passes

        checkRight=false;
        ping();
        cm130 = duration/29.1/2;
        mainPing = true;//enable to other 2 if statements to run
        servoTimer=millis();
        Serial.println(cm130);
        servo.write(90);//turn motor back
        Serial.println("Inside other loop");//for debugging

      }

      delay(2);
      }

    void ping(){

        digitalWrite(trig, LOW);
        delayMicroseconds(2);
        digitalWrite(trig, HIGH);
        delayMicroseconds(10);
        digitalWrite(trig, LOW);
        duration = pulseIn(echo, HIGH);

    }
This is what I got in the Serial monitor:

    25//distance triggers 2nd if statement
    Inside less than 30 loop
    261
    Inside other loop
    13
    Inside less than 30 loop
    14
    Inside other loop
    14
    Inside less than 30 loop
    14
    Inside other loop
    3242
    13
    Inside less than 30 loop
    14
    Inside other loop

This all happened within milliseconds. There was no 2 second pause and the servo never turned. What is wrong with my code that prevents the motor from turning and waiting 2 seconds? The order of the Serial messages is correct, but it is happening fast.

EDIT:

When I remove the Serial messages and disconnect from the computer, it kind of works. By that, I mean it turns and waits for 2 seconds 50% of the time. Other times, the servo just shakes a little bit and stops.

Another thing I noticed is that if I leave only Serial.println(cm) message and Serial.println("Inside less than 30 loop"), this is the result that I observe.

        12
        13
        Inside less than 30 loop

        15
        3
        Inside less than 30 loop

For some reason the loop does not get triggered the first time. Is there a possibility that I have a defective Arduino Mega?

EDIT 2:

I tested the same setup on an official Arduino Uno and it did not work either. This means that I do not have a broken Arduino. Could the servo motor be broken? That won't explain the Serial messages though.

body:
I added some more debugging, and I think I have your issues detected.

Amended code:

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

    #include <Servo.h>
    #define trig 22
    #define echo 24
    long duration;
    boolean turned130 = false;
    int cm50, cm, cm130;
    Servo servo;
    boolean checkRight = false;
    boolean mainPing = true;
    unsigned long counter;
    unsigned long servoTimer = millis();
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      pinMode(echo, INPUT);
      pinMode(trig, OUTPUT);
      servo.attach(12);
      servo.write(90);
      delay(2000);
    }

    void loop() {
      counter = millis(); //my timer
      if (((counter - servoTimer) >= 250) && mainPing) { //distance measured 4 times a second
        Serial.print ("Doing ping at time ");
        Serial.println (counter);
        ping();
        cm = duration / 29.1 / 2;
        Serial.println(cm);
        servoTimer = counter; //this if statement works fine
      }
      if ((cm < 30) && mainPing) {

        mainPing = false; //makes the 90 degree ping and this if statement unable to run
        checkRight = true;//enables next if statement to run
        servoTimer = millis();
        servo.write(130);
        cm = 30; //so that this if statement does not get called again until distance is obtained
        Serial.println("Inside less than 30 loop");//I added this for debugging, to let me know when the loop is called
      }
      if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes
        Serial.print ("counter = ");
        Serial.println (counter);
        Serial.print ("servoTimer = ");
        Serial.println (servoTimer);
        checkRight = false;
        ping();
        cm130 = duration / 29.1 / 2;
        mainPing = true;//enable to other 2 if statements to run
        servoTimer = millis();
        Serial.print ("cm130 = ");
        Serial.println(cm130);
        servo.write(90);//turn motor back
        Serial.println("Inside other loop");//for debugging
      }
      delay(2);
    }

    void ping() {
      digitalWrite(trig, LOW);
      delayMicroseconds(2);
      digitalWrite(trig, HIGH);
      delayMicroseconds(10);
      digitalWrite(trig, LOW);
      duration = pulseIn(echo, HIGH);
    }

With no server (or anything) attached I get this output:

<!-- language: lang-none -->

    Doing ping at time 1999
    0
    Inside less than 30 loop
    counter = 1999
    servoTimer = 2693
    cm130 = 0
    Inside other loop

First note that `servoTimer` is somewhat higher than `counter` because the `pulseIn` function takes a while to execute (times out after 1 second allegedly, although that was less than a second).

Now we come to the problem "if" statement.

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

      if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes

That can't be right, eh? `counter` is 1999 and `servoTimer` is 2693, and there is not 2000 difference. However you are doing the maths the other way:

<!-- language: lang-none -->

    counter - servoTimer =  1999 - 2693 = -694

Since we are using **unsigned long**, it cannot hold negative numbers so the result of the subtraction is 4294966602.

[![Unsigned long calculation][1]][1]

That is much larger than 2000, so the "if" branch is taken.

  [1]: https://i.stack.imgur.com/K1kXn.png


message:
Gas Sensor Library for Proteus

Does any one know how to use Gas Sensor module in Proteus. I wanna use Gas Sensor but I am unable to find it in Proteus. So, does anyone know any way of adding Gas Sensor Library for Proteus software. Thanks in advance.

body:
I have found the [Gas Sensor Library for Proteus][1], so I thought to share it here so that others can also get benefit out of it. They have also posted the complete method of How to use this Gas Sensor Library and have also given an example to download.

Thanks.

  [1]: http://www.theengineeringprojects.com/2016/05/gas-sensor-library-proteus.html


message:
TCS230 Low Pulse Length with Arduino

My son and I are attempting to connect a TCS230 Color Sensor to an Arduino Nano using the tutorial at TopTechBoy.com (http://www.toptechboy.com/arduino/lesson-15-super-cool-arduino-color-sensor-project/) as guidance.

Everything seems to be working except that the conversion from pulseIn to RGB used on TopTechBoy is expecting a maximum pulse count of 102,400. Instead I am receiving pulseIn readings with a maximum of 2000.

Our Wiring

 S0  - GND
 S1  - 5V
 OE  - No Connection (Tried GND)
 GND - GND
 S2  - D8
 S3  - D7
 OUT - D4
 VCC - 5V

Our Code:

    int S2 = 8;
    int S3 = 7;
    int OUT = 4;

    void setup() {

    Serial.begin(9600);
    pinMode (S2, OUTPUT);
    pinMode (S3, OUTPUT);
    pinMode (OUT, INPUT);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      int red , green, blue;

      red = getRed();
      Serial.print("Red : "); Serial.println(red);
      Serial.println("**********************");
      Serial.println();

      blue = getBlue();
      Serial.print("Blue : "); Serial.println(blue);
      Serial.println("**********************");
      Serial.println();

      green = getGreen();
      Serial.print("Green : "); Serial.println(green);
      Serial.println("**********************");
      Serial.println();

      delay(3000);

    }

    int getRed(void){ return getColor(0, 0, 19000, 24000); }

    int getGreen(void){return getColor(1, 1, 13600, 19200);}

    int getBlue(void){return getColor (0, 1, 16400, 21600);}

    int getColor(int s2Value, int s3Value , int typicalPulseWidth, int maxPulseWidth){

      long divideForScale = typicalPulseWidth / 255 ;

      digitalWrite(S2, s2Value);
      digitalWrite(S3, s3Value);

      unsigned int pulseWidth = pulseIn(OUT,LOW);

      Serial.print("Pulse Width : "); Serial.println(pulseWidth);

      unsigned int rColor = pulseWidth / divideForScale ; //401.5686274509804
      Serial.print("Response Color - Inverted : "); Serial.println(rColor);

      rColor = 255 - rColor ;
      Serial.print("Response Color - Final : "); Serial.println(rColor);

      delay(500);

      return rColor ;

    }

The pulses appear correct, just out of scale. Red items produce short Red pulses and so on.

I tried to correct for the shorter pulses by using the Typical Output Frequency (f0) found on page 4 of the data sheet. I'm not sure if this is the right use of this frequency output spec.

http://www.unihedron.com/projects/darksky/tcs230-e33.pdf

Lowering the max possible pulses per second from 100,400 to around 20,000 gave us a little more variation between RGB values, but still the output is nothing like the expected color.

Can anybody offer some insight as to why the TCS230 pulse count is far fewer than the TTB code expects and what can I do to fix either the pulse count or the scale? Kind regards.

Output from Measuring a Blue RFID Keyfob:
    divideForScale : 74
    Pulse Width : 673
    Response Color - Inverted : 9
    Respponse Color - Final : 246
    Red : 246
    **********************

    divideForScale : 64
    Pulse Width : 376
    Response Color - Inverted : 5
    Respponse Color - Final : 250
    Blue : 250
    **********************

    divideForScale : 53
    Pulse Width : 737
    Response Color - Inverted : 13
    Respponse Color - Final : 242
    Green : 242
    **********************

body:
From the project page (a comment by Marius David) it seems some integer datatypes may not be the same on different platforms. If he is correct, you may be working with a 16 bit pulseWidth while 32 bits are needed.

Try using an `unsigned long` for the `pulseWidth` variable.


body:
Connect S0 to 5V to get 100% OUTPUT FREQUENCY SCALING.

Currently, with S0 LOW and S1 HIGH, you get 2% OUTPUT FREQUENCY SCALING. Which would explain the 50 times to low values you get (100% / 2% = 50).


message:
Can I convert 3.7V to 5V's using 3.3v to 5v converter

[![Bidirectional logic level converter][1]][1]
[1]: https://i.stack.imgur.com/NL4YV.jpg

THe product: (https://www.sparkfun.com/products/12009)

So guys, here' s a pretty simple but important question for me:
Can I convert 3.7V (li-po battery's voltage level) to 5V's (I do have arduino pro mini running on 5 volts) using 3.3v to 5v converter (picture shown above...) ??

Thanks already...

body:
No. That is a level shifter. It uses a low voltage (3.3V) to switch a separate high voltage (5V) supply to create different logic levels.

It does not convert voltage, it merely switches.

To create 5V from 3.7V you need either a *boost converter* (inductor based circuit) or a *charge pump* converter (capacitor based circuit).


message:
Pin 0 (62) you are trying to use is not supporting interrupts

Using `RCLib` ([github][1]) I'm getting this error. The trick is that the RCLib [example][2] works on it's own but does not work in my program ([github][3]).

**Serial Output "Error"**

    Pin 0 (62) you are trying to use is not supporting interrupts
    Pin 1 (63) you are trying to use is not supporting interrupts
    Pin 2 (64) you are trying to use is not supporting interrupts
    Pin 3 (65) you are trying to use is not supporting interrupts
    Pin 4 (66) you are trying to use is not supporting interrupts
    Pin 5 (67) you are trying to use is not supporting interrupts

  [1]: https://github.com/jantje/ArduinoLibraries/tree/master/RCLib
  [2]: https://github.com/jantje/ArduinoLibraries/blob/master/RCLib/Examples/Maga6ChanelsA8_A13/Maga6ChanelsA8_A13.ino
  [3]: https://github.com/jacksonkr/SwatBotSpine

body:
It is quite right. Those pins aren't interrupt pins. What you want to do is make it use *PinChange interrupt* pins instead.

This can (by the look of things) be done by including the PinChangeInt.h library before including the RCLib library.