body:
I need to connect a lot (~100) of modules with a computer (Raspberry pi). The modules are based on Arduino micro and are very simple. They will be spread around, but for the two adjacent the distance would not be larger than 2 meters.
From time to time they receive information from the computer and also can send some data back. So bandwidth requirement is small.

My first idea was connecting them in one i2c network. It would be fine, except I have figured out that i2c is not good for a distances. Signal degrades and communication is unreliable if works in the first place.

Second idea is the nrf24 network (mash). But I am not sure how reliable communication is with them? Wired seams more reliable.

What would you recommend? It needs to be as cheap as possible, because of number of modules. Reliability of communication is important. The bandwidth requirement is very small (1Kbps is enough). Also modules are not battery powered so no need to be low power option.

What is the best way of doing this?

EDIT:
Network topology (it can be changed):

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

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

<!-- End schematic -->

title: Inexpensive way of connecting a lot of modules on a distance

Answers: 0


body:
I've seen a few different User-Agents used in demo sketches and am curious as to what the various User-Agent options are and how to determine which one to use.

For example...

    `User-Agent: Mozilla/4.0`

    `User-Agent: Arduino/1.0`

    `User-Agent: ESP8266`

    `User-Agent: ArduinoWiFi/1.1`

I've used Arduino/1.0 successfully with an Uno/WiFi101 but want to use an ESP8266 now.  Do I continue using Arduino/1.0 or switch to ESP8266 (Arduino IDE 1.6.5)?

When would someone use Mozilla?

Any guidance is appreciated.

title: User-Agent question

Answers: 1

body: You can use anything you like. It's used by the remote server to (try and) determine what browser you're using in order to give you the best visual experience. On an Arduino you really don't care about the visual experience. You don't even *need* to provide a `User-Agent` field, but it is courteous to do so.


body:
I have an arduino where I looking for an input event then do something. Unfortunately this input event can occur like 200 times and I only care about the first notification. Since I have a DS1302 timer handy in the circuit already for other purposes I was thinking using the minutes reading out of this to squelch this event.

Here is the code I come up with:

    if (digitalRead(sensor_event)==HIGH)
      {

          if (RTC.read(tm)) {

                  if(time_set)
                    {
                           if (tm.Minute > time_pushed+5)
                               time_set=0; // Unlock
                     }
                   else
                     {
                            if (tm.Minute >= 55)
                              time_pushed=0;
                            else
                              time_pushed=tm.Minute; // Set global volatile min value

                            print("Sensor event");
                            time_set=1;
                     }
          }
      }

About the seconds and hours I don't care all I need is if this event is detected then go ahead with a function and put it on a 5 minutes hold before checking it again.

The small issue here is the minute overflow. For example if the minute is just at 56 when this happens the time_pushed would be set to 56 then the time_pushed+5 would give 61 (which of course is never reached).

Is there a better way to code this? What is the name of this time issue I having to ignore an event until x minutes? What I found for this was mostly debounce but I'm sure this has to be handled by others sometimes too.

Thanks

title: Ignore event until x minutes

Answers: 5

body:
Use the `millis()` function instead if you can accomodate a rollover after 50 days.

- Take a reading of millis() at the start time.
- time_pushed = millis() + 5 * 60 * 1000;   // 5 minutes into future.

The rest of your code shouldn't require too much editing.

body:
Don't bother with the RTC, just use millis().  Or just convert the time in hours/minutes/seconds to a single number in seconds (i.e. UNIX timestamp) and use that.  Then use these time comparison macros:

    #define time_after(unknown, known) ((long)(known) - (long)(unknown) < 0)
    #define time_before(unknown, known) ((long)(unknown) - (long)(known) < 0)
    #define time_after_eq(unknown, known) ((long)(unknown) - (long)(known) >= 0)
    #define time_before_eq(unknown, known) ((long)(known) - (long)(unknown) >= 0)

Then do something like this in your main loop, with a variable unsigned long sample_timer that's initialized to 0 at the start of your program:

    if (time_after_eq(millis(), sample_timer))
    {
        if (event)
        {
            sample_timer = millis() + 5*60*1000;
            // handle event...
        }
    }

These time comparison macros will properly handle overflow if you use unsigned long for your timestamps.

body:
Calculate target time, rollover if necessary and check if time is already passed that point. As long as you are checking the time multiple times per minute you shouldn't run into any issues.

    if (digitalRead(sensor_event)==HIGH)
    {

      if (RTC.read(tm)) {

              if(time_set)
                {
                       if (tm.Minute >= targettime)
                           time_set=0; // Unlock
                 }
               else
                 {
                        targettime=tm.Minute+5; // Set global volatile min value
                        targettime=targettime % 60;

                        print("Sensor event");
                        time_set=1;
                 }
      }
    }

body:
The proper way to do that depends on whether the event is guaranteed to
happen at least once every 49.7 days. If this is the case then, as
Tom Carpenter suggested in a comment, you can just test for
`now - last_event >= hold_time`:

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

    void loop()
    {
        uint32_t now = millis();
        static uint32_t last_event = -hold_time;

        // Detect the event if it did not happen in the last five minutes.
        if (now - last_event >= hold_time
                && digitalRead(sensor_event) == HIGH) {
            Serial.println("Sensor event");
            last_event = now;
        }
    }

If you can have 49.7 days without a single event, then this approach
fails because `last_event` is ambiguous. The simplest solution is
probably to implement a state machine with only two states, as the event
detection is either “on hold” or it is not:

    void loop()
    {
        uint32_t now = millis();
        static bool on_hold;
        static uint32_t last_event;

        // Remove the hold after five minutes.
        if (on_hold && now - last_event >= hold_time) {
            on_hold = false;
        }

        // Detect the event.
        if (!on_hold && digitalRead(sensor_event) == HIGH) {
            Serial.println("Sensor event");
            on_hold = true;
            last_event = now;
        }
    }

Now I would want to insist on a specific point: in either approach
[the millis() rollover is not an issue][millis rollover]. The choice
between the first and the second approach depends solely on the maximum
time between the events, not on how long the program is meant to run.

[millis rollover]: https://arduino.stackexchange.com/a/12588

body:
Just to save a lot of headaches for everybody who wonders here and still have  a problem with this code:

    uint32_t hold_time = 1*60*1000; // 1 minute will never work

    uint32_t hold_time = 60000; // 1 minute will work

You must define the value as an EXACT number, not putting in multiplication and rely on the compiler to calculate it for you.

Probably because it's unsigned long and screws up something with the multiplication but with the first example you will be put on hold for days, maybe forever.


body:
I am trying to create my own home automation using Arduino. I am using shift register for reading input(via push buttons) and writing output to led's. I am using SPI interface to communicate with shift registers.

Apart from SPI Arduino also deals with I2C devices. When push button is clicked Arduino ISR is invoked via pin 2, which then checks exact button that was pushed and takes action accordingly. The functionality currently works well with one small problem.

Sometimes when push button is clicked Arduino ignores the button press. After debugging for some time I observed that it happens when Arduino is busy with I2C communication with other devices.

I would like to know if it is possible to temporarily delay the push button input while Arduino busy with I2C communication? or is it possible to prioratize interrupt handling over I2C communication?

Below is the simplified code

    #include <SPI.h>
    #include <Wire.h>
    byte Input=1;
    volatile byte Check=1;
    volatile byte Output=1;

    int j;
    //Pin connected to ST_CP of 74HC595
    int latchPin = 8;
    //Pin connected to SH_CP of 74HC595
    int clockPin = 13;
    ////Pin connected to DS of 74HC595
    int dataPin = 11;

    int interruptPin=2;

    int espPin=7;

    char arduinoStatus[100]="\0";

     void pin_read(){

        for(j=0; j<50; j++)
        delayMicroseconds(1000);

        Check=1;
        for(j=0; j<8; j++){
          digitalWrite(latchPin, LOW);
          delayMicroseconds(500);

         SPI.transfer(Check);
         SPI.transfer(Output);

         digitalWrite(latchPin, HIGH);

         delayMicroseconds(500);
        if(digitalRead(interruptPin)==HIGH){
          //Serial.println(Check);

          if(bitRead(Output, j)==1)
          bitWrite(Output, j, 0);
          else
          bitWrite(Output, j, 1);
        }//dig check

        Check = Check<<1;

        }

        digitalWrite(latchPin, LOW);
        delayMicroseconds(500);
        SPI.transfer(255); //to push buttons
        SPI.transfer(Output); //to LEDs

        digitalWrite(latchPin, HIGH);
        delayMicroseconds(500);

    }//pin_read

    void setup() {
      //set pins to output so you can control the shift register
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(espPin, OUTPUT);
      pinMode(interruptPin, INPUT);//Input from buttons

      delay(1000);
      // the LEDs don't change while you're sending in bits:
        digitalWrite(latchPin, LOW);
      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE0);
      SPI.setClockDivider(SPI_CLOCK_DIV2);
      SPI.begin();
      SPI.transfer(255);
      SPI.transfer(255);
       //take the latch pin high so the LEDs will light up:
        digitalWrite(latchPin, HIGH);

        Serial.begin(115200);
        attachInterrupt(0, pin_read, RISING);

        Wire.begin(8);                // join i2c bus with address #8
      Wire.onRequest(requestEvent); // register event
      Wire.onReceive(receiveEvent);

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

    void loop() {
      Serial.println("Interrupting...");
     digitalWrite(espPin, HIGH);

     while(digitalRead(interruptPin)==HIGH){}
      delayMicroseconds(500);
     digitalWrite(espPin, LOW);
     delayMicroseconds(500);
     Serial.println("Done...");
    Serial.print("Output:");
    Serial.println(Output);
    delay(3000);
    }

    // function that executes whenever data is received from master
    // this function is registered as an event, see setup()
    void receiveEvent(int howMany) {
      int i=0;
      Serial.println("received::");
      while (Wire.available()) { // loop through all
        char c = Wire.read(); // receive byte as a character
        arduinoStatus[i++]=c;

        Serial.print(c);         // print the character

      }
      arduinoStatus[i]='\0';
      Serial.println("###");
    }

    // function that executes whenever data is requested by master
    // this function is registered as an event, see setup()
    void requestEvent() {
      Serial.println("Sending...");
      Wire.write("hello"); // respond with message of 6 bytes
      Wire.write(Output);
      Serial.println("Sent");
      // as expected by master
    }

title: Delaying pushbutton input to microcontroller while it's busy processing I/O

Answers: 2

body:
Without looking any further than the first `delaymicroseconds()` command I would say that that's where the trouble lies. The `delay()` functions are very handy for getting the beginner's first LED to blink and are a big problem after that. The problem is that the CPU is completely tied up during the delay and can't do anything else other than interrupts and you only have a limited supply of those. Your button press is missed.

You need to develop your own timers in the code and keep the main loop running constantly checking on each pass to see if the delay is complete.

body: What about polling the buttons periodically instead of using an interrupt?  If you check them every 10 ms or so, you should still be able to detect a button press reliably.  Connecting buttons to interrupt inputs is not necessarily the best idea due to contact bounce - this can cause a number of back-to-back interrupts.  My guess is that interrupts are being disabled during some part of your code and when the interrupt pin level changes during that period, it gets ignored.


body:
Can I connect a Bluetooth module to usual digital pins, other than D0/D1 (RX/TX) pins as the shield is already using the D0 and D1 pins?

My Bluetooth module is an HC-05 MODULE.

title: Connecting Bluetooth module to Arduino Uno without RX/TX pins

Answers: 2

body:
Classic Arduinos use pins 0 and 1 for serial communication to the host computer, so it is problematic to connect a bluetooth module there anyway - it can be done, but basically means that programming the board and communicating with it by serial will not work (at least not reliably) until the interfering bluetooth module is removed or disabled.  For these boards you need to use a software serial instance to talk to the module, and you can put it on most any digital pins.

ATmega32u4 boards like the Leonardo do not have debug/programming on pins 0 and 1 but do have a hardware UART there, so those would be the best choice for a bluetooth module, but you can still use software serial.

The Arduino Mega has additional hardware serial pins that would be good choices, but you can use software serial.

Various ARM based boards with Arduino ports typically have additional hardware serial pins which you should use.  Software serial may or may not be an option on these (it's not that an implementation cannot exist, but that software serial is generally disadvantageous, so when a chip has more hardware UARTs that particular function may not be ported).

body: you can define pin and can use after defining int RX=any pin TX=any pin


body: can i unplug my Arduino project when i'm done installing the libraries and it still work the way it did when it is plugged in

Answers: 1

body: Once you compile and upload your arduino sketch and any libraries it uses, your code is stored in nonvolatile memory inside the processor. You can unplug your arduino and power it up later and it will run your code again with out any help from your computer.


body:
I'm working on an Arduino robot and I ran into a problem when reorganizing my code. I have an Adafruit Motor Shield v2.3 connected to an Arduino Uno. My robot can be controlled using a bluetooth connection (BlueSMIRF module) or it can be told to avoid obstacles using an ultra sonic range finder.

Everything worked fine and the robot moved nicely until I decided I wanted to organize the code better, so that my code for moving the robot would be in a separate class, my code for servo movement also in a class as well as my code for the logic for movement (received bluetooth command - do this, or avoid obstacles like so, etc.). Suddenly, none of the motors respond or just one.

I'm not sure if I have a problem with my C++ and passing pointers to my functions or what is going on...

Here is my main .ino file, its relevant parts, I left out stuff that concerns the bluetooth connection etc. And yes, I know the hardcoded include paths look ugly, I'll figure out what to do with includes at some point... :

    // bluetoothRobot.ino

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include <Servo.h>
    #include <SonarSRF08.h>
    #include <SoftwareSerial.h>
    #include <MemoryFree.h>
    #include "utility/Adafruit_PWMServoDriver.h"

    #include "\Users\Jarno\Arduino\bluetoothOhjausBot\MotorController.h"
    #include "\Users\Jarno\Arduino\bluetoothOhjausBot\AvoidObstacleController.h"
    #include "\Users\Jarno\Arduino\bluetoothOhjausBot\MemoryFree-master\MemoryFree.h"

    MotorController* motorController;

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();

    Adafruit_DCMotor *rightRearMotor = AFMS.getMotor(1);
    Adafruit_DCMotor *leftRearMotor = AFMS.getMotor(2);
    Adafruit_DCMotor *rightFrontMotor = AFMS.getMotor(3);
    Adafruit_DCMotor *leftFrontMotor = AFMS.getMotor(4);

    void setup()
    {
        motorController->start(&AFMS, leftRearMotor, leftFrontMotor, rightFrontMotor, rightRearMotor);
        AFMS.begin();
    }

    void loop()
    {
        if(bluetooth.available())  {
            char command = (char) bluetooth.read();

            if (controlMode == 2) {
                motorController->executeBluetoothCommand(command);
            }
        }
    }

Here is my MotorController.h:

    // MotorController.h

    #ifndef MotorController_h
    #define MotorController_h

    #include "Arduino.h"
    #include <Wire.h>
    #include <Adafruit_MotorShield.h>

    class MotorController {
        public:
          int executeBluetoothCommand(char command);
          void start(Adafruit_MotorShield *AFMS, Adafruit_DCMotor *rightRearMotor, Adafruit_DCMotor *leftRearMotor, Adafruit_DCMotor *rightFrontMotor, Adafruit_DCMotor *leftFrontMotor);
          void turnRight();
          void turnLeft();
          void moveForward();
          void moveBackward();
          void stopRobot();
          void setRobotSpeed(int leftWheelsSpeed, int rightWheelsSpeed);
        private:
          Adafruit_MotorShield* AFMS;
          Adafruit_DCMotor* leftRearMotor;
          Adafruit_DCMotor* rightRearMotor;
          Adafruit_DCMotor* rightFrontMotor;
          Adafruit_DCMotor* leftFrontMotor;
      };

    #endif

And here is MotorController.cpp:

    // MotorController.cpp

    #include "\Users\Jarno\Arduino\bluetoothOhjausBot\MotorController.h"

    void MotorController::start(Adafruit_MotorShield *shield, Adafruit_DCMotor *rrm, Adafruit_DCMotor *lrm, Adafruit_DCMotor *rfm, Adafruit_DCMotor *lfm) {
          AFMS = shield;
          rightRearMotor = rrm;
          leftRearMotor = lrm;
          rightFrontMotor = rfm;
          leftFrontMotor = lfm;
          setRobotSpeed(80,80);
      }
    int MotorController::executeBluetoothCommand(char command) {
            switch(command) {
                case 'F':
                  moveForward();
                  break;

                case 'B':
                  moveBackward();
                  break;

                case 'L':
                  turnLeft();
                  break;

                case 'R':
                  turnRight();
                  break;

                case 'S':
                  stopRobot();
                  break;

                /*case 'W':
                  stopRobot();
                  controlMode = 1;
                  tiltServoAngle = 120;
                  panServoAngle = 90;
                  motorController.setPanAndTilt(panServoAngle, tiltServoAngle);
                */
                default:
                  return -1;
                  }
        return 0;

    }
    void MotorController::setRobotSpeed(int leftWheelsSpeed, int rightWheelsSpeed) {
            leftFrontMotor->setSpeed(leftWheelsSpeed);
            leftRearMotor->setSpeed(leftWheelsSpeed);
            rightRearMotor->setSpeed(rightWheelsSpeed);
            rightFrontMotor->setSpeed(rightWheelsSpeed);
      }
    void MotorController::moveForward() {

            setRobotSpeed(80,80);
            leftRearMotor->run(FORWARD);
            rightRearMotor->run(FORWARD);
            leftFrontMotor->run(FORWARD);
            rightFrontMotor->run(FORWARD);

      }

    void MotorController::moveBackward() {
            leftRearMotor->run(BACKWARD);
            rightRearMotor->run(BACKWARD);
            rightFrontMotor->run(BACKWARD);
            leftFrontMotor->run(BACKWARD);
            setRobotSpeed(80,80);
      }

    void MotorController::turnLeft() {
            leftRearMotor->run(BACKWARD);
            rightRearMotor->run(FORWARD);
            rightFrontMotor->run(FORWARD);
            leftFrontMotor->run(BACKWARD);
            setRobotSpeed(80, 80);
      }

    void MotorController::turnRight() {
            leftRearMotor->run(FORWARD);
            rightRearMotor->run(BACKWARD);
            rightFrontMotor->run(BACKWARD);
            leftFrontMotor->run(FORWARD);
            setRobotSpeed(80, 80);

      }

    void MotorController::stopRobot() {
            leftRearMotor->run(RELEASE);
            rightRearMotor->run(RELEASE);
            rightFrontMotor->run(RELEASE);
            leftFrontMotor->run(RELEASE);
      }

I used to have a constructor for MotorController with the Motor Shield library `AFMS.begin()` call in it and all. But this caused the Arduino to constantly reset for some reason. I coudn't understand why but I moved the motor configurations and call to `begin()` to my .ino file where the problem doesn't occur.

**Problem:** What happens with the code as it is, is which ever pointer to motor is passed last seems to work and that particular motor turns but the others won't. If I comment out the call to `setRobotSpeed` in `MotorController::start`, nothing happens with any motor even though speed is also set in the relevant functions.

As said, the robot worked fine when the code was in my .ino file. Although, for some reason I had to call the Motor Shield library's `begin()` function always before any other commands to motors. So it was called every time the user told the robot to move forward, move backward etc. Otherwise nothing happened with the motors. Now, if I add a call `AFMS->run()` to my MotorController.cpp, the Arduino starts to constantly reset...

Also, none of the other stuff (blueSMIRF, the range finder code etc.) should interfere since they were also there when it worked and I even commented out that stuff.

I'm baffled. Maybe its some silly mistake with my C++? Or is there really something weird going on here?

Any help would be much appreciated, I've spent hours trying to figure this thing out! Thanks in advance!

title: Problem with wrapping Adafruit Motor Controller function calls in a class

Answers: 2

body:
One thing about instantiating classes before `setup()` is called is that `init()` (which you don't see) may undo all of your careful setup.

Your code starts:

    Adafruit_DCMotor *rightRearMotor = AFMS.getMotor(1);
    Adafruit_DCMotor *leftRearMotor = AFMS.getMotor(2);
    Adafruit_DCMotor *rightFrontMotor = AFMS.getMotor(3);
    Adafruit_DCMotor *leftFrontMotor = AFMS.getMotor(4);

but these are constructed before `setup()`. And then you call `MotorController::start()` with those values. You haven't provided the code for `AFMS::getMotor()` - so it may be doing things internally that is undone by `init()`.

Instead of creating the whole pointer, why not do this:

    const byte rightRearMotor = 1;
    const byte leftRearMotor = 2;
    const byte rightFrontMotor = 3;
    const byte leftFrontMotor = 4;

and then callig `AFMS.getMotor()` inside `MotorController::start()`:

    void MotorController::start(Adafruit_MotorShield *shield,
                                byte rrm, byte lrm, byte rfm, byte lfm) {
        AFMS = shield;
        rightRearMotor = AFMS.getMotor(rrm);
        leftRearMotor = AFMS.getMotor(lrm);
        rightFrontMotor = AFMS.getMotor(rfm);
        leftFrontMotor = AFMS.getMotor(lfm);
        setRobotSpeed(80,80);
    }

body:
The obvious issue in your current code is that `motorController` is a pointer to your class but I don't see any place it was instantiated properly.

Hence, it points **anywhere** the first time you use it, which can explain resets of the MCU.

Now, either you keep it as a pointer:

    MotorController* motorController;

**And then you instantiate it in place**:

    MotorController* motorController = new MotorController();

**Or you can also instantiate it in `setup()` as first line (ie before it is used anywhere else)**:

    void setup() {
        motorController = new MotorController();
        ...
    }

**However**, for reasons discussed elsewhere on this site, I would not use dynamic allocation but **I'd rather define `motorController` as an instance of `MotorController` instead of a pointer**:

    MotorController motorController;

Now everywhere you were using `motorController->xxx` you'll have to replace it it with `motorController.xxx`.

That should remove the most important bug of your current code (I can-'t tell if there are other issues but this one must be fixed in priority).


body:
I have this SIM900 board and working just fine.
But i can't find a way to soft power on this board from arduino.
I read for JP pads. They need soldering first, but from my board this JP pads missing.
Know someone other way to soft power on this from arduino?
[![enter image description here][1]][1]

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

title: SOLVED: Soft Power On SIM900 module - JP pads missing!

Answers: 2

body:
OK for anyone who has the same problem. I solved this by soldering a cable on the underside of the board on this pin (see image) on power button. Then I connect the cable to pin 9 on Arduino and run this on sketch:

      pinMode(9, OUTPUT);
      digitalWrite(9,LOW);
      delay(1000);
      digitalWrite(9,HIGH);
      delay(2000);
      pinMode(9, INPUT);

I don't know how it works, but it solves my problem.

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

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

body:
Near C6 and J15 you have 2 points.  You need to solder it.
Before soldering yon can hold wire on one of it (down pin , during code execution).

![1]][1]

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


body:
I'd like to receive on my arduino live coordinates of planets of solar system. Because there are already websites listing every planet coordinates, I thought it would be easier to just use a wifi module (in my case an ESP8266) and connect the arduino to one of these website.

I have the option of getting it from [this][1] website, but I have no idea how to do that.

The other way of doing it may be to connect to [Horizon][2] via their telnet server at this adress :telnet://horizons.jpl.nasa.gov:6775

Though I know how establish a connection with this server on my computer using Putty, I have no idea how to connect my arduino to it, execute commands, and, more importantly, get data (RA and DEC) of every solar system main objects.

This is my first time using Arduino wifi module, so I have no experience with it, and I don't know what it is capable of.

Thanks a lot for your attention,

Thomas

  [1]: http://theskylive.com/planets "Live coordinates of planets"
  [2]: http://ssd.jpl.nasa.gov/?phys_data

title: Receiving live astronomical coordinates on Arduino Mega using telnet and ESP8266 wifi module

Answers: 1

body:
That telnet interface is an interactive service. Getting an Arduino to interact with it is not an easy task - certainly not a task for a beginner with no experience of network programming.

A much easier task is to *scrape* the website since that just returns text which you then need to search through a bit at a time looking for the information you need.


body:
Hi SE (and Majenko in particular, if I'm lucky) -
I have a setup with an SD module (on SPI) and an Elechouse PN532 NFC reader (on I2C). I would like to use a master tag to enter MASTER MODE [sic] to add tags if they are not present in a file on my SD card, or remove tags which are present in the same file. I am currently checking tag UID against a hardcoded master UID, and it works well enough for now. What trips me up is making the tag database in the most arduino-friendly way. How would you advise me to do this in the most spartan way? And when removing existing tags from the database, how would you suggest I update it, to remove unwanted UIDs? I am using a flat text database now, but it could be a binary file - I am just puzzled by what is the best method to remove an entry(line) from a file using SD library.

title: NFC 'dynamic' UID database

Answers: 1

body:
You got me ;)

Since a UID is a fixed size you don't need to think in "lines", only in bytes.

The most efficient way of storing the UIDs is as pure bytes. I am not familiar with that specific card and reader combination, but I will assume as an example an 8 byte UID (though this all holds true for any other length you care to choose).

You treat your file on SD card like a kind of database with a number of records in it. Each record is the exact same size (8 bytes in this case) . To read or write a specific record you just "seek" to the record number multiplied by the record size - so multiples of 8 in this example.

    myFile.seek(recordNumber * 8);

If `.seek()` returns `false` then you have reached the end of the file.

So to find a tag you can:

    myFile.seek(0); // Start at the beginning of the file
    int recno = 0;
    char foundUID[8];
    bool found = false;
    while (myFile.read(foundUID, 8)) {
        if (strncmp(foundUID, myUID, 8) == 0) { // 8 bytes match
            found = true;
            break;
        }
        recno++;
    }

At the end of that `found` will be `true` if there is a match, and `recno` will be set to the record number. Now the magic begins...

If it has been found and you want to delete it, think again. That's a very wasteful idea. Instead you just want to "invalidate" it - that is, replace the UID in the database with something the UID can never be - all 0xFF is a good choice. Simply:

    myFile.seek(recno * 8);
    for (int i = 0; i < 8; i++) {
        myFile.write(0xFF);
    }

Now the tag has gone from the database. You may want to add a filter at the card reading phase to stop anyone using a card that has a UID of all 0xFF, of course.

Now for adding a new card...  This is where the fun starts.  You could just add 8 bytes to the end of the file, but then the file will grow and grow and grow. Instead, you can first search through the file for a tag entry that is all 0xFF and replace that data with your new UID. Just the same as when you deleted it - seek to 8x the record number and write 8 bytes.

It might help to write a function to wrap the tag seeking routine so you can easily call it multiple times from multiple places. Returning the record number would be most useful - and you could return -1 if it's not found.

If you really want it to be plain text you can do the exact same thing but work with the ASCII representation of the UID bytes instead of the raw values - maybe as HEX. So your 8 byte records would become 18 bytes (16 bytes for 2 ASCII characters per UID byte, plus two for the `\r\n` line ending). Doing the conversion between bytes and text and back to bytes again though is wasteful if you don't really need it.

----

In case you're wondering why I recommended 0xFF as the deleted tag fill value and not 0x00 or anything else, it is simply because when you erase flash memory it is set to 0xFF. When you change the contents of a block on an SD card the block is read, it is modified in memory, the block is then erased (the whole lot set to 0xFF), then the modified block re-written back to the card. The act of erasing the block slightly damages it as it forces electrons through bits they don't really want to go through to make it all 0xFF. By setting your empty records to 0xFF, when it comes time to filling them again, the flash doesn't have to work as hard to erase that block since those bits are already in the erased state. Therefore the lifetime of the flash card should be extended slightly.


body:
I'm trying to make the transition from coding in the Arduino language to AVR-C, but I'm having some issues with my microcontrollers.

I don't have an ISP, so I'm using one of my Arduino UNOs with the ArduinoISP sketch. The problem is that when I try to run avrdude it gives me this error:

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
      Double check connections and try again, or use -F to override
      this check.

However, when I try to run the command with the sugested -F it uploads the code to the Arduino UNO I'm using as an ISP instead of the ATmega328p on my breadboard.

Does anyone have any idea about whats going on here, or how to fix it?

title: Issues graduating to AVR-C

Answers: 1

body: "invalid device signature" is due to bad connection or inability to reset the device (RST pin fuse setting for example).


body:
I have an Arduino Nano and was adding up some values `2^i from 0..7`:

    void setup() {
      Serial.begin(9600);
      int i,k;
      k = 0;
      for (i=0;i<8;i++){
         k += pow(2, i);
         Serial.println(k);
      }
    }

Those numbers should sum up to `255`, but that's the output:

    1
    3
    6
    13
    28
    59
    122
    249

Is my Arduino not working or what can be the reason for this behaviour?

title: Strange adding behaviour

Answers: 2

body:
No, there is nothing "wrong" there. In fact it's the expected results.

The problem here is that `pow()` returns a float, and some numbers just can't be represented with floating point. When that floating point value is converted to an integer it truncates the decimal portion leaving you with the wrong integer value.

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

        int t = 0;
        for (int i = 0; i < 8; i++) {
            float f = pow(2, i);
            int d = f;
            t += f;
            Serial.print("2^");
            Serial.print(i);
            Serial.print(": float = ");
            Serial.print(f, 10);
            Serial.print(" int = ");
            Serial.print(d);
            Serial.print(" total = ");
            Serial.println(t);
        }
    }

    void loop() {
    }

    2^0: float = 1.0000000000 int = 1 total = 1
    2^1: float = 2.0000000000 int = 2 total = 3
    2^2: float = 3.9999995231 int = 3 total = 6
    2^3: float = 7.9999980926 int = 7 total = 13
    2^4: float = 15.9999961853 int = 15 total = 28
    2^5: float = 31.9999885559 int = 31 total = 59
    2^6: float = 63.9999771118 int = 63 total = 122
    2^7: float = 127.9999542236 int = 127 total = 249

Instead you should use bit-shifting to perform the same operation on an integer:

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

        int t = 0;
        for (int i = 0; i < 8; i++) {
            int d = 1 << i;
            t += d;
            Serial.print("1<<");
            Serial.print(i);
            Serial.print(": int = ");
            Serial.print(d);
            Serial.print(" total = ");
            Serial.println(t);
        }
    }

    void loop() {
    }

    1<<0: int = 1 total = 1
    1<<1: int = 2 total = 3
    1<<2: int = 4 total = 7
    1<<3: int = 8 total = 15
    1<<4: int = 16 total = 31
    1<<5: int = 32 total = 63
    1<<6: int = 64 total = 127
    1<<7: int = 128 total = 255

body:
Granted that integer arithmetic is a computationally better approach to this problem; if your intent was to learn to use floating point and float to int conversions, then you need to round up the floating result before the conversion truncates it. As you saw in @Majenko's example, the floating results are close but not quite exact. In your own example, you'd change

    k += pow(2, i);

to

    p = pow(2, i); k += (p < 0. ? -0.5 : 0.5);

to so the float would truncate to the nearest int instead to the next lower int.


body: What should be expected if the code in the timer interrupt ISR does not finish before the interrupt is called again?  For example Timer0 ISR(TIMER0_COMPA_vect){} on the Uno.  This is for debugging purposes in a complex program.  Thanks.

title: interrupting an interrupt

Answers: 2

body: It won't be called until the current interrupt is finished. As soon as the current interrupt function returns the pending interrupt would trigger and call the ISR again.

body:
1. the timer will set the Timer Interrupt Flag (TIFR0 register)
 2. The ISR will be called, and the flag will be cleared
 3. you do some long calculations or something
 4. the timer will match OCR0A, and set the interrupt flag again.
 5. you calculations are done, and the ISR function will end.
 6. the uC will jump back to the main loop code, and execute 2 1 instructions.
 7. The uC will see the flag, and call the ISR again. As per step 2.

PS please note that by default the ISR macro will turn off global interrupt (cli) at the beginning of the function, and set it back at the end. You can re-enable interrupts inside the ISR, but you have to be very careful here, as interrupts can be nested, and cause stack-overflows.

You can re-enable interrupts inside the ISR, but that only means other interrupt may interrupt this ISR, but never the same vector. (i.e. only one ISR per vector can run at the same time). So in your case the timer ISR can't be interrupted by the same timer interrupt.


body:
Given that there is a circuit with two pins (12 and 10) from an Uno providing power to LEDs on two separate branches, why is the yellow LED dimmer than the green LED? (Please see below image.) To my understanding, the branches attach to GND in parallel, so the LEDs should be equally bright.

If it helps, the two branches are programmed so one LED is off when the other is on and vice versa, with a 1s interval between changing pin state. This isn't a PWM thing as using pin 8 instead of 10 makes no difference.

[![Arduino UNO and Breadboard setup][1]][1]

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

title: Why is one LED more luminous (brighter) than the other?

Answers: 1

body:
Just like men, all LEDs have been made different.

Practically, that means two different LEDs (one green and one yellow for instance) will have different brightnesses (more precisely, **luminous intensities**) when they are traversed by the same current (**forward current**).

LED luminous intensity is a function of the current that traverses it (among other factors).

If you want the same brightness for those 2 LEDs, then you'll have to:

1. Get both LEDs datasheets (should be a couple of A4 pages for each)
2. Find the luminous intensity/forward current function curve in each
3. Determine which brightness you want for both
4. Deduce the current for each
5. Calculate the resistor value to get that current for each

Then you will have to use two different resistors values in your wiring, based on calculations of step 5.

**Simpler,** you could just replace one of your 2 resistors with one small pot that you can use to tune brightness of the second LED until it fits brightness of the first one.

**Be careful with pot manipulation though,** as a 0 resistance would probably grill your LED (and potentially the Arduino pin it is wired to).


body:
Today I tried to update the sketch on my Arduino Uno, but was unable to due to this error:

    Sketch uses 1,870 bytes (5%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 188 bytes (9%) of dynamic memory, leaving 1,860 bytes for local variables. Maximum is 2,048 bytes.
    D:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/bin/avrdude -CD:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\User\AppData\Local\Temp\build2f7b4a32c3810b2d8e42648954faba05.tmp/nes_controller.ino.hex:i
    An error occurred while uploading the sketch

Nothing will upload to the board now. I tried uploading a simple sketch with empty setup() and loop() functions, I've tried different PCs and gotten the same error, I've swapped USB cables, I've double-checked that I'm using the right COM port, I've disconnected every wire from the Arduino pins - nothing has helped.

The old sketch is still running fine on the Uno. It was uploaded a few days ago using the exact same setup I'm trying right now.

The Arduino IDE doesn't even indicate any errors, everything compiles and looks good until "An error occurred while uploading the sketch"

title: Sketches won't upload to Uno

Answers: 5

body: right click on computer, manage, device manager and disable the usb driver and enable it again.

body:
assumption is windows, so with the old ide's a reboot to free up the usb ports, or sometimes simply swapping the usb port, and changing the port in the tools > port menu.

does it identify the board you are using when you choose the port? (Genuino / Arduino)

body:
You can set the verbosity level in the Arduino IDE:

* File menu
* Preferences
* Settings tab
* "Show verbose output during" => check "upload"
* Click OK

Upload again, and note the additional output telling you what is wrong.

It should also point you to [this URL][1], which points out the most occurring issues.

The issue I have most, is that I forget to switch between Micro and Uno board (as I deploy my sketch on both boards).

  [1]: https://www.arduino.cc/en/Guide/Troubleshooting#upload

body:
In my experience, sketch upload error occurred due to 4 different mistakes:
(1) Silly mistake: did not connect the serial cable to the PC
(2) I did not choose the right com port (Tools/port).
(3) I chose the wrong board type (Tools/board). connected a Nano, but selected Uno while uploading.
(4) While updating my Arduino IDE to the a version, I failed to select 'download USB drivers' option. There are 2 or 3 of them.

body:
This is a guess based on what I have encountered previously. With all the information given remember I just took a guess!

Is it possible you are experiencing a serial flood, ie it is constantly sending something to the console.
Take these steps several tries may be needed:
1) Power off the board completely
2) Remove the USB cable
3) Hold down the Reset button
4) keep it held down (or, run a jumper wire from the RESET pin to the GND pin).
5) Still holding down Reset reconnect the USB cable.
6) Start uploading a sketch that does not have this problem (I use the Blink sketch).
7) When you see the Receive light blink, release the Reset button
Note: I have seen this happen several times when I flood the serial output. An indication is the tx light is on.

You can check the hardware as follows.
Here is a trick I use on some boards but first be the baud rate is the same in the terminal as in the sketch (Serial.begin(115200). If so then remove everything then put a jumper between ground and reset. Then put a jumper between TX and RX (pin o and pin 1 on uno). launch the IDE and what you type in the console should be echoed back to you. If this works the hardware is connected fine.


body:
I just bought a new stepper motor (400 steps for revolution, 0.9°/step) and I would like make a turn of 180° by 200 steps, but it doesn't work as expected.
It looks like the motor needs only 110 steps to make a turn of 180° and I don't know the cause. The driver motors is the Keyes L298. It is wired to my Arduino UNO rev3.

In order to clarify, please see the image below:

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

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

The code is as follows:

    #define negativeSteps -55
    #define positiveSteps 55
    #define Speed 7500

    int motorPin1 = 11;
    int motorPin2 = 10;
    int motorPin3 = 9;
    int motorPin4 = 8;

    int steps;
    unsigned int tmp2;

    byte modeR[] = {B00001001, B00001010, B00000110, B00000101};
    byte modeF[] = {B00000101, B00000110, B00001010, B00001001};

    void setup() {

      Serial.begin(115200); //Opens serial connection at 115200 baud.

      pinMode(11,OUTPUT);
      pinMode(10,OUTPUT);
      pinMode(9,OUTPUT);
      pinMode(8,OUTPUT);

      pinMode(3,OUTPUT);    // Enable pin motorA
      pinMode(2,OUTPUT);    // Enable pin motorB

      digitalWrite(2,HIGH);
      digitalWrite(3,HIGH);
    }

    void loop()
    {
        while (Serial.available())
        {
          char cmd = (char)Serial.read();
          if (cmd == 's')   while(1) Seek();
        }
    }
    void motorR(){
      int bitMask=B00001111; // bitmask to modify only last 4 bit

              for (int id = 0; id <4; id++) {
                PORTB = (PORTB &~bitMask) |  modeR[id];
                while (tmp2++<Speed);
                tmp2=0;
              }
    }
    void motorF(){
      int bitMask=B00001111; // bitmask to modify only last 4 bit

              for (int id = 0; id <4; id++) {
                PORTB = (PORTB &~bitMask) |  modeF[id];
                while (tmp2++<Speed);
                tmp2=0;
              }
    }
    void Seek() {
      steps = negativeSteps;      //Init Steps
      while (1)
      {

        while (steps<positiveSteps) //  starts from "negative" steps to "positive" steps ( -55 to +55)
        {
           if (steps<0) motorF(); // if steps = 0 it will change the direction
           else motorR();

          Serial.println(steps);
          steps++;
       }
     }
    }

title: Arduino - stepper motor wrong steps number

Answers: 1

body:
You're driving the stepper too fast, unintentionally though.

The while loop you use to delay is likely optimized out by the compiler:

    while (tmp2++<Speed);

Easiest way to fix would be to declare **tmp2** as a *volatile* variable when you declare it up in the top of your program.  Thusly:

    volatile unsigned int tmp2;

This will inform the compiler that **tmp2** might possibly change at any time and not to optimize it away. It's more complicated than that really, but it'll fix your issue in a single tweak.

Better, would be to use the **delay()** function, to pause execution for some specified **milliseconds**, much like you're attempting to do with the empty while loop.

You're using an UNO, so probably running at 16Mhz, so your delay of 7500 loops is technically about 5 instructions long, multiplied by 7500... so 37,500 instructions executed, and at approximately 16,000,000 instructions per second, that's (37500/16M) that's about 2.34 milliseconds.  So maybe a **delay()** of 3-5 milliseconds would be useful.

Basically, you're trying to step the motor too fast, and it can't keep up.  Mass, inertia and all that stuff are involved too.

Try replacing the while statements with delays, start with big delays (25 or so), and work lower as long as stepper motion is consistent.  As you said, 200 steps **should** be 180°.

replace:

    while (tmp2++<Speed);

with:

    delay(Speed);

and change **Speed** to an appropriate value (25 or so to begin with, play with it!).

There are many improvements to your code which could be discussed, but you need to crawl before you walk, before you run.  Get THIS code working, then finesse it.


body:
Trying to get started with the Arduino, so I'm trying to do something kinda simple. I'm following this tutorial: [Build Your Own Dynamic Ambient Lighting For A Media Center](http://www.makeuseof.com/tag/build-your-own-dynamic-ambient-lighting-for-a-media-center/)

However, I'm still confused about one, most likely simple and self-explainatory, thing:
Take a look at [this image](http://i.1n9i9c7om.com/r3tnBj.png) - is that DC connector on the bottom left the one that's one my Arduino? Do I simply have to connect the 12V wire from the RGB LED stripe to Vin?

After using google for a bit, I read this: `the diode and trace width are other limiting factors. The diode is rated at 1 amp and the board traces can't handle much above 2 amp.`
Does that mean I can only use 1A because of the diode? If so, why does it matter how much the board traces can handle?

I'm trying to power a 12V 2A RGB LED stripe.

I'd appreciate your help and I hope this is the correct subreddit to ask that. :S

title: Arduino Uno VIN 2A

Answers: 2

body:
No, that connector is a completely separate one.

You can connect a power supply to the on-board power socket of the Arduino and take power out from the VIN pin to power other things.  However the *total current* that is used by both the Arduino *and* whatever you power from it *cannot* exceed 1A.

So to have more than 1A available you have to have the power connected externally to the Arduino. That doesn't mean that the Arduino can't share that power, just that the Arduino can't *provide* that power.

You can connect the +12V of the LED strip to VIN on the Arduino as long as the 12V power supply is connected to the LED strip not to the Arduino - that way the power for the Arduino comes *from* your external circuit.

body:
It will be dangerous to take 12V from VIN pin. Please have a look at following picture. That is the diode you mentioned. the diode can burn out if the current get exceeded.

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

there are three ways to solve this.

 1. Use two different supplies. Use a 6V battery(or 5V USB power) to power arduino and 12v supply for LED strip. You should connect both grounds( grounds of supplies)

2. Solder a wire from bottom(from the point shown in picture) of arduino board for 12v

3. connect 12v power directly to VIN (not by using power jack)

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

  [1]: https://i.stack.imgur.com/3zgKh.png
  [2]: https://i.stack.imgur.com/YMyb9.png


body: I am pretty new to arduino.I am working on a project which requires comparison of two keypad inputs to operate a relay using arduino. I have found lot of info on connecting single keypad but none about connecting two keypad inputs.So how can i connect two keypad and a relay to arduino?Thanx in advance.

title: connecting two keypad with arduino

Answers: 1

body:
It should be no problems as long as you can get enough digital inputs into the Arduino.  Search for the library KeyPad, it lets you define the pins that control each row and column and so you could use 2 2*2 keypads quite easily.

I think Keypad is very easy to use, but if you get stuck, just show what code you have so far and describe the problem and people will help you.


body:
I am having an Arduino Uno and I want to add a LCD to it. My LCD is a C2042A with I2C shield on it. I tried the LiquidCrystal_I2C library but it doesnt work. I am not getting any errors the LCD is just not showing the text. I just used the example code 'Hello World' from the library. I only changed the adress from 0x27 to 0x63 because I found that with the I2C scanner.

So all in all the LCD is connected right. It shows I2C mode which is also fine and it is find by the I2C Scanner code. Which library do I have to use that it will work? http://www.wentztech.com/filevault/Electronics/Arduino/

title: Arduino which library for led 4x20

Answers: 1

body:
0x63 is the correct address - the module is at 0xC6 which is the 8-bit equivalent of 0x63 (0x63 shifted left once for the read/write bit to be added).

The LCD03 uses its own custom I2C protocol, not compatible with the "normal" I2C LCD library. Instead you have to use their own special commands.

The commands are detailed here: http://www.robot-electronics.co.uk/htm/Lcd03tech.htm

There may be a library available that wraps those commands, I don't know, but you can just use the Wire library to send the commands you need to send.


body:
To start, I am a software guy, and I really want to ensure I not going to destroy any components. I previously looked at power through a USB power bank, but the issue with these is that they turn themselves off with low current pull.

My question is: I have a number of Arduino shields and would like to power them with 4 rechargeable AA batteries, and therefore would like some advice on what to use without frying any electronics.

The rechargeable batteries I have are [these][1] 1.2V AA (NiMH). Going on their rated value they should supply 4.8V. Testing the 4 batteries in serial gives me 5.3V overall, or around 1.325V per battery at full charge.

So if the batteries provide more than 5V, I cannot safely plug them into the 5V pin on the Arduino. But if the batteries could potentially provide around 4.8V to 5.5V plugging them into VIN means that the voltage regulator will take too much power, reducing the overall voltage to be too low for all of the shields (Which require 5V). What should I do in this situation?

This is a list of the current equipment that will require power:

 - [Arduino Mega 2560][2]
 - [SIM900 GPRS/GSM Shield][3]
 - [Sparkfun GPS Logger Shield][4]
 - [Sparkfun Wifi Shield - ESP8266][5]

The shields will be stacked on top of each other.

  [1]: https://www.duracell.co.uk/en-gb/products/duracell-rechargeable/duracell-rechargeable-batteries
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560
  [3]: http://linksprite.com/wiki/index.php5?title=SIM900_GPRS/GSM_Shield
  [4]: https://www.sparkfun.com/products/13750
  [5]: https://www.sparkfun.com/products/13287

title: How to power Arduino and shields with 4 rechargeable AA batteries?

Answers: 1

body:
Most 5V devices will function fine at up to 5.5V - however, check the datasheets for the major components and modules on the boards.

The main thing to watch though is that a 3.3V device, which can normally communicate fine with a 5V one, may not be able to. The problem is that the logic HIGH signal from the 3.3V device may be below the threshold for a logic HIGH on the Arduino:

    V_IH = 0.6Vcc = 0.6 x 5 = 3V

    V_IH = 0.6Vcc = 0.6 x 5.5 = 3.3V

Thus a 3.3V device would have to output at the very minimum 3.3V as a logic HIGH in order for it to register as one on the Arduino, which may be a problem...

You can easily drop the battery voltage by 0.7V though by inserting a single silicon diode (such as the trusty 1N4001) in series with the batteries. That will take your voltage down from your measured 5.3V down to 4.6V which will improve matters somewhat.

However, it is important to note that you have so far measured the *open circuit* voltage of the batteries. That is, the voltage with no load on them. The voltage will most likely be lower once they are actively driving the Arduino etc.

The Arduino itself will be fine running off 5.3V, so I suggest you power just the Arduino direct into the 5V pin from the batteries and measure the actual voltage while powering the Arduino. That will give you a more accurate voltage reading. Then, if needed, you can add the diode to drop it by 0.7V.


body: I recently started with Arduino and I have my starter kit. However, there are some strange looking components I can't recognize. Is there some way to find out the names of these components?

title: How do I find names of components I don't know?

Answers: 2

body:
The Arduino webpage has a section about their [Starter Kits][1], including pictures (and technical specs if you scroll down the page). Particularly, if you go to the Arduino store, there is a sub-menu for components - for example, for [actuators][2] (there are more categories to the left of the image).

There is a blog by Aaron Eiche, [Arduino Starter Rundown][3], that if you scroll down, there is a chart that labels the main components.

There are several websites that have pages that identify components by image - an example is the uCHobby webpage [Identifying Electronic Components][4], with pictorial menus of the main types of components.

In Google images, searching "arduino starter kit components" yields a considerable amount of labelled component charts.

  [1]: https://www.arduino.cc/en/Main/ArduinoStarterKit
  [2]: https://store.arduino.cc/category/31
  [3]: https://aaroneiche.com/2009/07/16/arduino-starter-rundown-part-2/
  [4]: http://www.uchobby.com/index.php/2007/07/15/identifying-electronic-components/

body:
A slightly more general answer to this question would be to browse the catalogue of a component supplier. Printed catalogues seem to be becoming rarer (Maplin used to sell a catalogue, but it seems to be discontinued this year), but RS and Farnell still seem to have printed ones.

I'm not suggesting you find specific components by searching the catalogue, but skimming through a catalogue will give you an idea about some of the components that do exist, and will help you to narrow things down a little.


body:
I have a load sensor for measuring weights , it has for wires labelled E+,E-,S+,S-. I assume S means sensor and E means excitation and the power is sent into E+ and E-.
The output of any load sensor would be the order of typically millivolts if it takes a load (depending on the weight of the load of course) so I guess amplifying it with a darlington would make its output useful for an interface to an arduino.
What would be a generic circuit using a darlington transistor (e.g. a TIP 120) that can make the load sensor output useful for building an interface to an arduino with the minimal number of components? Ans this circuit is to be as simple as possible.
Im trying to build a circuit with the components I have which does include a tip 120 and I have a lot of other common components.

title: How to interface an arduino to load sensor with darlington transistor?

Answers: 1

body:
What you have there is (or sounds like) a full wheatstone bridge.

You require either a special amplifier (such as the [HX711](https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide)) or a highly sensitive and accurate differential ADC (such as the [MCP3428](http://ww1.microchip.com/downloads/en/DeviceDoc/22226a.pdf) - ([on  a shield](http://majenko.co.uk/hpdaq.php))).


body:
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

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

Answers: 3

body:
This is not the place to answer all the questions and design options that you have, but, to give you a starting point, you need to look at very low power arduino-compatible boards.

My suggestion is to use an ESP8266 module which can be programmed as an Arduino (have a look at [here][1]). The module is quite low power, and [it may run for some days with AA batteries][2]. You can use a 12V power source for both the module and the solenoid (you need a voltage regulator). The solenoid will only be activated when needed, so the rest of the time it won't consume any power.

The whole project is not a simple one. I would definitely suggest you to go step by step.

Good luck.

  [1]: http://www.esp8266.com/
  [2]: https://www.youtube.com/watch?v=IYuYTfO6iOs

body:
As far as the 12V motor is concerned, you can construct a decent H-bridge to shift polarity. I am assuming you are using a linear actuator or servo. Use a mechanical relay with 2 channels. Wire GND to NO1 and NO2, VCC (12V) to NC1 and NC2, and pull VOUT  to motor from COM1 and COM2 - IIRC - and in your code track state of when each channel is on or off... It will short out if both relay channels are ON simultaneously, so that must not be possible.

Mechanical relays are slower to switch than transistors (can haul 230VAC/30VDC/10A with no voltage drop), but if you want a transistor H-bridge use the rather old TIP120 NPN Darlington (0.6-0.7V voltage drop per transistor), or MOSFETs. At least the TIP120s require heatsinking for >=0.5A, but can drive 5-6A upto 60V, which is plenty.

As far as the wifi bit goes, I don't have enough experience. I would use a GET request to a web server/page and read what state the lock should be in at short intervals... no more than 5 seconds. A simple '1' or '0' in a text file will do. To output state, heartbeat (is the Arduino OK right now, or is something wrong?) and other stuff from the Arduino, use POST requests. You should use a simple database for this... PostgreSQL is my favourite, but you may want something simpler.

If you need precise timekeeping for events like open at 9.00 am, use a DS3231. Be careful to conserve SRAM, the Uno has only 2KB. There are guides on arduino.cc to help you with that (PROGMEM for immutable variables and the F macro for static strings). This is a good method, hope it helps.

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.


body:
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.

title: How to convert bool array to byte?

Answers: 2

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.


body:
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

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

Answers: 1

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.


body:
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?

title: Why isn't this pushbutton program working?

Answers: 4

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


body:
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

title: Arduino program does not start when plugged in

Answers: 1

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


body:
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

title: Start to build a robot

Answers: 1

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).


body:
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.

title: Compilation Error

Answers: 1

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


body:
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?

title: Serial characters are corrupted

Answers: 1

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


body:
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

title: Use a 2.8" TFT with my Leonardo

Answers: 1

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.


body:
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`?

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

Answers: 1

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.


body:
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

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

Answers: 3

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:
According to [AVR libC][1] the implementation of the delay function has a limited value range that varies with the F_CPU macro definition. So your `delaySeconds(int)` function is the only solution.

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__util__delay.html

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**.


body:
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?

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

Answers: 3

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


body:
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

title: SIM900 random shutdowns

Answers: 2

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


body:
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

title: Arduino servo motor on pushbutton

Answers: 1

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.


body:
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.

title: Arduino audio output circuit

Answers: 1

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.

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


body:
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);

title: Using logical operators

Answers: 1

body:
You should use

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

instead of

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


body:
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.
    }

title: Pneumatic cylinders with sensors with Arduino Uno

Answers: 3

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.