body:
For some reason, the Arduino IDE can't find the file I have made for the project:

    #include <foo1.h>
    #include <foo2.h>
    #include "foo3.h"

Where foo1 and foo2 are normal libraries thus included with <..> but foo3 is another file I wrote which resides in the same directory as the .ino file from where this code is taken.
If I essentially convert foo3 into a library and include it as a library in my project it works but makes the project harder to move.

Error I get:

    Project.ino:6:23: fatal error: foo3.h: No such file or directory
    :#include "foo3.h"
    :compilation terminated
    Error compiling project sources

Note: Error is persistent in both the Arduino IDE and VMicro

title: Can't include files

Answers: 3

body:
The question is a bit unclear, however as far as I know, for the included libraries use:

    #include <SPI.h>

So the `<` and `>` are used for common libraries which are in the C:\Program files...\Arduino folder

And for specific (own made or sketch-depending) include files

    #include "MyFile.h"

should be used, which should be located in the same folder as the sketch file.

body:
It seems that my mistake was that I just created new files with another program and simply put them in the project directory. This probably confused the IDE as the files were not included in the build of the project.

Managed to fix this issue by creating new files within the project itself and simply copying my code into them. For VMicro/Visual Studio:

> VMicro\Add Code\Add Empty Arduino .h and .cpp files

body: Changing to double quotes with header files in the same folder worked for me.


body:
I'm relatively new to arduino projects and am trying to solve a real world problem on a parking lot space counter.
My Idea is to have a sensor placed on the entrances and exit to count the total number of cars in the parking lot.
Now there are several codes online but they only implement for 1 entrance.

Scaling for 4 entrances:

> Would it be ideal to implement 1 main unit with multiple cables running to each sensors placed on the entrances and exits of the parking lot.

Given that the parking lot is huge:

> Is there a wireless way to transmit data from each sensor to the central unit ?

I'm welcoming any recommendations regarding this project.

EDIT:
This is for an actual prototype. I've scoped around the garage to find that I only need  multiple entry exit (2) system for the ground floor. Rest of the two floors have their own 1 entry and exit points.
The entrance and exit are the same point so I was thinking of a bidirectional sensor.

> Does 10 feet of width pose a problem for the sensor ?
> Could I instead use two bi-directional sensors placed on either sides of the entry and exit, and then hook them up to the same input in the Arduino ? So incase 1 misses the other one registers.

Edit 2: The parking deck is big enough to hold about 20-25 cars on each of the 3 floors. I don't know the exact measurement though
> Besides Sensors could I use a wire on the floor to register when a car crosses over ? Would that be easier?

title: How can I implement a parking counter with multiple entrances and exit?

Answers: 0


body:
I am trying to run a strip of APA102 addressable LED's using a Mini pro.

The same strip I can run using a raspberry pi using SPI so I know the Strip works and what data I need to send to get it running.

My current code is as follows and I have striped it back to the bare minimum as I see it.

It all compiles and runs but nothing on the LED strip. The stip only has data and clock that should be connected to the CLK and Data in to connect to the MOSI.

All i want is to be able to send a 32bit value,

I had also tried

    uint32_t value = 0xE0ffffff

but again no luck

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

      Serial.begin(9600);

      SPI.begin();

      byte start = 0x00;
      SPI.transfer(start);
      SPI.transfer(start);
      SPI.transfer(start);
      SPI.transfer(start);

      SPI.transfer(0xEF);
      SPI.transfer(255);
      SPI.transfer(0);
      SPI.transfer(10);
    }

title: SPI.H library to control APA102

Answers: 1

body:
take a look at the datasheet, compare it vs. your code for any incompliance.

based on my quick reading, your code isn't consistent with the datasheet.

put the communications in a routine would help maintain uniformity.


body:
I'm working on a project where my arduino talks to another device that uses serial communication. I've connected my USB cable to a USB-to-serial adapter, so it can communicate with the device.

The problem I'm running into is powering the device: if I'm using the USB for serial, I can't use it for power. I have made sure that the device isn't turning on by putting

    pinMode(13, OUTPUT);
    for (int i = 0; i < 10; i ++) {
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
        delay(1000);
    }

at the start of the `setup` function: if it works, it should start by blinking LED 13.

I tried powering it with a 5V power supply through the power jack, next to the USB connector, but that didn't work. Is there something I'm missing? Do I need a different type of power supply?

title: How do I power an arduino without USB?

Answers: 2

body:
> my arduino talks to another device that uses serial communication

What other device? You haven't said which Arduino, but Arduinos are generally "devices" which talk to a "controller" (host) which is generally a PC / Mac.

The host has the job of supplying power (via the USB cable) to the device. Thus your Arduino will be powered by the device it is plugged into.

Disregarding this issue for the moment, you can supply *regulated* 5V power directly to the 5V pin on the Arduino. On the Uno (and many others) this is labelled "5V".

The power jack is to supply 7V to 12V (eg. from a wall-wart) which then goes through the voltage regulator on the Arduino (depending on the model in question).

There is quite a discussion about this on <https://www.arduino.cc/en/main/arduinoBoardUno>. On that it mentions:

>  Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

This is true. Directly supplying 5V to the 5V pin bypasses the regulator and also bypasses the reverse-voltage protection diode. However it is *possible* to do it.

---

> What about the Vin pin?

For a Uno you can see from the reference schematic what happens:

[![Uno input schematic][1]][1]

The power jack (on the left) goes into the reverse-voltage protection diode (D1). The other side of that becomes Vin. Then it goes into the 5V voltage regulator (U1). The other side of that becomes the 5V line.

Thus to supply 5V you can provide 5V power to the pin marked 5V. It is probably not ideal, because the voltage regulator may not be designed to have power applied on its "output" side.

There is more circuitry to decide whether to use the USB power or the Vin power (not shown above).

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

body: The kind of voltage regulator on the Arduino board will need about 7v to give 5v out to the board. If you trust that your 5v supply is well regulated - at least that it won't exceed 5v, no spikes, etc. - you can connect it directly to the 5v pin on the board edge. Just be aware that you'll be bypassing the protection of the voltage regulator so it will be on you to make sure you're providing the proper polarity, well regulated 5v. Exceed that value and you'll stand a good chance of damaging the board.


body:
I'm trying to program a Nano by using an Uno as the ISP. So far, I've followed along with the example project for getting the Uno running as the ISP on https://www.arduino.cc/en/Tutorial/ArduinoISP.

After a bit of tinkering, it works, but the serial monitor won't work correctly. I'm uploading a super simple program that delays for 500 ms and prints to the log.

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

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

I've wired the TX pin on the Nano to the RX pin on the uno. The monitor updates every 500 ms as expected after doing so, but displays ��� instead of the word test. When I tried wiring TX -> TX, the serial monitor does not update. Does anyone have any insight what's missing here?

title: Forwarding serial output from a Nano to Uno that's used as the ISP

Answers: 1

body:
As [Chris Stratton][1] suggests in his comment above:

>You can't really connect an ordinary Arduino's serial pins to both another device and the on-board USB serial converter at the same time.

To solve your serial monitor problem use a separate USB serial converter and connect that to your Arduino Nano.

If you don't have access to a dedicated USB serial converter you could use [software serial][2] on the Arduino Nano. This allows you to connect the Arduino Uno Rx pin to the software serial Tx pin. You will also need to program the Arduino Uno with a program that re-transmits the data it receives back out to the PC serial monitor.

  [1]: https://arduino.stackexchange.com/users/612/chris-stratton
  [2]: https://www.arduino.cc/en/Reference/SoftwareSerial


body:
I am using following code to send message using Arduino Uno & SIM800 module.
But I need to send same message on multiple numbers then what changes should I make in my code.

    const int buttonPin = 8;   // Main gate sensor 1
    const int buttonPin1 = 7;  // Main gate sensor 2
    const int buttonPin2 = 9;  // Store room sensor 1
    const int buttonPin3 = 10; // Store room sensor 2

    bool i = false;
    bool j = false;
    bool k = false;
    bool l = false;

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

      pinMode(buttonPin, INPUT);
      pinMode(buttonPin1, INPUT);
      pinMode(buttonPin2, INPUT);
      pinMode(buttonPin3, INPUT);

      digitalWrite(buttonPin, LOW);
      digitalWrite(buttonPin1, LOW);
      digitalWrite(buttonPin2, LOW);
      digitalWrite(buttonPin3, LOW);

      delay(1000);
    }
    void loop()

    {
      sensor1();
      sensor2();
    }
      void sensor1()
      {
      if (digitalRead(buttonPin1)== LOW && digitalRead(buttonPin) == HIGH  && i == false)

      {
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91...................");
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Main Gate is Closed");
        Serial.write(0x1A);
        delay(1000);
        i = true;
        j = false;

      }

      if (digitalRead(buttonPin)== LOW && digitalRead(buttonPin1) == HIGH &&  j == false)
      {
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91........................");
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Main Gate is open");
        Serial.write(0x1A);
        delay(1000);
        j = true;
        i = false;
      }
      }
      void sensor2()
      {
      if (digitalRead(buttonPin2) == HIGH && digitalRead(buttonPin3)==LOW && k == false)
      {
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91....................");
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Store room is Closed");
        Serial.write(0x1A);
        delay(1000);
        k = true;
        l = false;
      }
      if (digitalRead(buttonPin3) == HIGH &&digitalRead(buttonPin2)== LOW && l == false)
      {
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91....................");
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Store room is Open");
        Serial.write(0x1A);
        delay(1000);
        l = true;
        k = false;
      }
    }

title: How to send messages to multiple numbers using Arduino uno & SIM800 module?

Answers: 3

body:
Try out this one. Here, I made the code for two number. Just simply add a new function for every new number. I hope it will help you.

    const int buttonPin = 8;   // Main gate sensor 1
    const int buttonPin1 = 7;  // Main gate sensor 2
    const int buttonPin2 = 9;  // Store room sensor 1
    const int buttonPin3 = 10; // Store room sensor 2

    bool i = false;
    bool j = false;
    bool k = false;
    bool l = false;

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

      pinMode(buttonPin, INPUT);
      pinMode(buttonPin1, INPUT);
      pinMode(buttonPin2, INPUT);
      pinMode(buttonPin3, INPUT);

      digitalWrite(buttonPin, LOW);
      digitalWrite(buttonPin1, LOW);
      digitalWrite(buttonPin2, LOW);
      digitalWrite(buttonPin3, LOW);

      delay(1000);
    }
    void loop()

    {
      sensor1();
      sensor2();
    }

    void sensor1()
    {
      if (digitalRead(buttonPin1)== LOW && digitalRead(buttonPin) == HIGH  && i == false)
      {
        numOneGateClose();
        numTwoGateClose();
        i = true;
        j = false;
      }

      if (digitalRead(buttonPin)== LOW && digitalRead(buttonPin1) == HIGH &&  j == false)
      {
       numOneGateOpen();
       numTwoGateOpen();
        j = true;
        i = false;
      }
    }

    void sensor2()
    {
      if (digitalRead(buttonPin2) == HIGH && digitalRead(buttonPin3)==LOW && k == false)
      {
        numOneRoomClose();
        numTwoRoomClose();
        k = true;
        l = false;
      }

      if (digitalRead(buttonPin3) == HIGH &&digitalRead(buttonPin2)== LOW && l == false)
      {
        numOneRoomOpen();
        numTwoRoomOpen();
        l = true;
        k = false;
      }
    }

    void numOneGateClose()
    {
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91...................");
      Serial.print("\"\r\n");
      delay(2000);
      Serial.print("Main Gate is Closed");
      Serial.write(0x1A);
      delay(1000);
    }

    void numTwoGateClose()
    {
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91...................");
      Serial.print("\"\r\n");
      delay(2000);
      Serial.print("Main Gate is Closed");
      Serial.write(0x1A);
      delay(1000);
    }

    void numOneGateOpen()
    {
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91........................");
      Serial.print("\"\r\n");
      delay(2000);
      Serial.print("Main Gate is open");
      Serial.write(0x1A);
      delay(1000);
    }

    void numTwoGateOpen()
    {
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91........................");
      Serial.print("\"\r\n");
      delay(2000);
      Serial.print("Main Gate is open");
      Serial.write(0x1A);
      delay(1000);
    }

    void numOneRoomClose()
    {
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91...................");
      Serial.print("\"\r\n");
      delay(2000);
      Serial.print("Main Gate is Closed");
      Serial.write(0x1A);
      delay(1000);
    }

    void numTwoRoomClose()
    {
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91...................");
      Serial.print("\"\r\n");
      delay(2000);
      Serial.print("Main Gate is Closed");
      Serial.write(0x1A);
      delay(1000);
    }

    void numOneRoomOpen()
    {
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91........................");
      Serial.print("\"\r\n");
      delay(2000);
      Serial.print("Main Gate is open");
      Serial.write(0x1A);
      delay(1000);
    }

    void numTwoRoomOpen()
    {
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91........................");
      Serial.print("\"\r\n");
      delay(2000);
      Serial.print("Main Gate is open");
      Serial.write(0x1A);
      delay(1000);
    }

body:
@nilesh just add some delay between two massege

I modified your code check it

    const int Main1 = 8;
    const int Main2 = 9;
    const int Store1 = 7;
    const int Store2 = 10;
    bool i = false;
    bool j = false;
    bool k = false;
    bool l = false;

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

      pinMode(Main1, INPUT);
      pinMode(Main2, INPUT);
      pinMode(Store1, INPUT);
      pinMode(Store2, INPUT);

      digitalWrite(Main1, LOW);
      digitalWrite(Main2, LOW);
      digitalWrite(Store1, LOW);
      digitalWrite(Store2, LOW);

      delay(1000);
    }
    void loop()

    {
      sensor1();
      sensor2();
    }
    void sensor1()
    {
      if (digitalRead(Main1) == HIGH && digitalRead(Main2) == LOW && i == false)

      {
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91-----------");// first number
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Main gate closed");
        Serial.write(0x1A);
        delay(5000);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91-----------");// Second number
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Main gate closed");
        Serial.write(0x1A);
        delay(1000);
        i = true;
        j = false;

      }
      if (digitalRead(Main2) == HIGH && digitalRead(Main1) == LOW && j == false)
      {
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91---------------");//first number
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Main gate Open");
        Serial.write(0x1A);
        delay(5000);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91--------------"); second number
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Main gate Open");
        Serial.write(0x1A);
        delay(1000);
        j = true;
        i = false;
      }
    }
    void sensor2()
    {
      if (digitalRead(Store1) == HIGH && digitalRead(Store2) == LOW && k == false)
      {
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
       Serial.print("+91-----------");// first number
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Store room is closed");
        Serial.write(0x1A);
        delay(10000);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91-----------");// second number
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Store room is Closed");
        Serial.write(0x1A);
        delay(1000);
        k = true;
        l = false;
      }
      if (digitalRead(Store2) == HIGH && digitalRead(Store1) == LOW && l == false)
      {
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
       Serial.print("+91-----------");// first number
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Store room is Open");
        Serial.write(0x1A);
        delay(5000);
        Serial.print("AT+CMGS=\"");
       Serial.print("+91-----------");// Second number
        Serial.print("\"\r\n");
        delay(2000);
        Serial.print("Store room is Open");
        Serial.write(0x1A);
        delay(1000);
        l = true;
        k = false;
      }
    }

thanks

bhupendra.sinkar727@gmail.com

body:
I have same question but minor different.

sim.println("AT+CMGS=\"+91xxxxxxxxxx\"\r");

i dont want to write this. i want to write mobile number on serial monitor in arduino and on that number, i want to send message. how can i do?


body:
I want to read in the values to an arduino analog input.

The approaches I have been looking at are:

1.) A ultrasonic distance sensor; my concerns are that tehse are not usually waterproof.

2.) A pressure transducer; these tend to be very pricy.

3.) Some kind of level switch which provides digital input (Is water level here: yes/no?)

Would anyone happen to have some advice on what sort of sensor would be good for the application of reading in the tank level and using the information in a sketch?

title: What would be the best way to sense the tank level of a 1000L water tank?

Answers: 2

body:
There are some ultrasonic sensors that are specifically designed for this very application. I have used something simlar as a water level sensor, and they seem to be reliable. The sensor that I used was from MaxBotix, and had a range of up to 5m, resolution of 1mm, and both analog and serial data output. Interfacing it with an Arduino was very easy.

Have a look at [This article][1] for details

  [1]: http://www.maxbotix.com/articles/050.htm

body:
> 1.) A ultrasonic distance sensor; my concerns are that tehse are not usually waterproof.

Ultrasonic rays will ping through water till it transfer back from the bottom of tank. So it can not provide you the level of water.

> 2.) A pressure transducer; these tend to be very pricy.

Yes it will be very pricy.

> 3.) Some kind of level switch which provides digital input (Is water level here: yes/no?)

This option will be best and more reliable. You can use some water level indicator probes or magnetic float switch.

**Probes/Electrode**

When electrode is in contact with water it will pass current through it and give indication to system or controller.

**Magnetic Float Switch**

Magnetic float switch having magnet under water proof enclosure. When water level reach upto Float switch then circuit will be close and will give level signal to system.

In above to switches magnetic float switch will be best option. Because if water having High TDS then there will be erosion of electrode or element of TDS will gether around electrode and result in conductivity loss of rode.

And this is not possible in case of Magnetic Float switch as it is under water proof enclosure. It is also cheap solution.


body:
I'm a newbie in Arduino. I find out a couple of examples.

Here, below arduino simple code I just uploaded.

Here, what is functionality or working of `pinMode`, `digitalWrite` and `digitalRead` ?

    const int kPinLed = 7;
    const int kPinBtn = 8;

    void setup()
    {
      pinMode(kPinLed, OUTPUT);
      pinMode(kPinBtn, INPUT_PULLUP);
    }

    void loop()
    {
      if(digitalRead(kPinBtn) == LOW)
      {
        digitalWrite(kPinLed, HIGH);
      }
      else digitalWrite(kPinLed, LOW);
    }

title: Working or functionality of pinMode(), digitalWrite() and digitalRead()

Answers: 4

body:
    {
      pinMode(kPinLed, OUTPUT);
      pinMode(kPinBtn, INPUT_PULLUP);
    }

This block of code used to define mode of Pin i.e. making pin as Output pin or Input pin.

    if(digitalRead(kPinBtn) == LOW)
    {

    }

This block of code is used to read value from defined digital pin either High or Low. And in return will give pin state High or Low. For example if we want to make LED ON which is connected to one of digital pin of Arduino at certain condition, we will define that pin under above block of code and can read state of that pin as High or Low.

     {
       digitalWrite(kPinLed, HIGH);
     }
     else digitalWrite(kPinLed, LOW);

This block of code is used to make Pin state High or Low i.e. Under certain condition this function will make pin state either High or Low.

To learn more, visit......

**PinMode** [Click here][1]

**DigitalRead** [Click here][2]

**Digital Write** [Click here][3]

  [1]: https://www.arduino.cc/en/Reference/pinMode
  [2]: https://www.arduino.cc/en/Reference/digitalRead
  [3]: https://www.arduino.cc/en/Reference/digitalWrite

body:
PinMode sets the mode or function of the pin, like input (when you connect it to a sensor), or output (when you connect it to a LED for example). There are also some variances (like pullup/pulldown for special cases).

In practice, when you set the value to LOW, 0 V will be put on the signal, and 5 V will be put when it is HIGH (at least on an Uno).

PinModes are normally set during setup (once), and DigitalRead/Writes in the loop since you want to change it dynamically.

Btw, the last pat of the example can be better written as:

    digitalWrite(kPinLed, digitalRead(kPinBtn) == LOW ? HIGH : LOW);

The ? operator (called ternary operator) checksk if the condition (digitalRead(kPinBtwn) == LOW is true, if so it will use the value behind ? otherwise the vvalue after : is used).

body:
Welcome to the world of Arduino!

To start off, the Arduino website has excellent descriptions of its various API functions, in your case -
https://www.arduino.cc/en/Reference/pinMode

https://www.arduino.cc/en/Reference/DigitalWrite

https://www.arduino.cc/en/Reference/DigitalWrite

Now to answer your question:

**pinMode** determines whether a specified pin behaves as input or output - does it read a signal to the Arduino (read from a a sensor, for example) or does it output to another component (a led to light it, a motor to move it). It achieves this by changing the impedance on the pin- high impedance for input, low for output.

**IINPUT_PULLUP** means both setting the pin to input mode, while 'pulling up' the input to be high when it is not explicitly low by an external component (whatever is connected to the pin)

      //configure the pin somePin to behave as output
      pinMode(somePin, OUTPUT);
      //configured the pin to behave as input, and 'pullup' the input to HIGH
      pinMode(somePin, INPUT_PULLUP);

Once you have set a pins mode to be input/output, you can read or write from it, depending on its mode.

If you configured a pin to be in input mode, you can use **digitalRead**

    //read the value from someInputPin and store it in the variable 'num'
    int num = digitalRead(someInputPin);

If you configured a pin to be in output mode , you can use **digialWrite**

    //write the value from 'num' to someOutputPin, and by extension whatever connected to it
    int num = HIGH;
    digitalWrite(someOutputPin,num);

body:
Very good question for every beginner. Let me explain.

**pinMode()** : This function set the functionality of pin. Means either INPUT or OUTPUT or INPUT_PULLUP.

INPUT use when you connect your arduino to the sensor.

OUTPUT use when you connect your arduino to LED, motor etc.

INPUT_PULLUP use when we require internal pull-up. For example, if we connect a pushbutton to our arduino then we require some pull-up resistor. Then this thing can be done by this INPUT_PULLUP. So we don't require any resistor in circuitry.

Now depend upon your circuit requirement you have to use proper pinMode.

**Syntax:** pinMode(pin, mode)

Where,

pin: the number of the pin whose mode you wish to set

mode: INPUT, OUTPUT, or INPUT_PULLUP.

You can see this thing in your code.

    void setup()
    {
      pinMode(kPinLed, OUTPUT);       // LED as OUTPUT
      pinMode(kPinBtn, INPUT_PULLUP); // Push Button as INPUT with pull-up.
    }

**digitalWrite():** This function set pin states either HIGH or LOW. Here, 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

**Syntax:** digitalWrite(pin, value)

Where,

pin: the pin number

value: HIGH or LOW

Now, again in your code.

    digitalWrite(kPinLed, HIGH); // Pin set as HIGH

    digitalWrite(kPinLed, LOW);  // Pin set as LOW

**digitalRead():** This function use to read the value from a specified digital pin, either HIGH or LOW.

**Syntax:** digitalRead(pin)

Where,

pin: the number of the digital pin you want to read (int)

And this thing in your code looks like.

    if(digitalRead(kPinBtn) == LOW) // Check pin states : LOW or HIGH
    {
      //Your code...
    }


body:
I use the following code to print the currently used SRAM space:

    // this function will return the number of bytes currently free in RAM
    // written by David A. Mellis
    // based on code by Rob Faludi http://www.faludi.com

    #include "TypeDefs.h"

    int availableMemory()
    {
      extern int __heap_start, *__brkval;
      int v;
      return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
    }

    int printAvailableMemory(uint32 location)
    {
      Serial.print(F("Available Memory at "));
      Serial.print(location);
      Serial.print(F(": "));
      Serial.println(availableMemory());
    }

My main application (stripped) looks like:

    ...
    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      printAvailableMemory(1);

      printAvailableMemory(2);

      test();
      printAvailableMemory(3);
    }

    void test()
    {
      Preferences _prefs2;
      _prefs2.Set();
      printAvailableMemory(4);
    }

While preference (.h) looks like:

    #include "TypeDefs.h"

    class Preferences
    {
       private:
          uint8 _startChannel;
          uint8 _endChannel;
          uint8 _startNote;
          uint8 _endNote;
          uint8 _startCc;
          uint8 _endCc;
       ...
    };

The output is:

    Available memory at 1: 1065
    Available memory at 2: 1065
    Available memory at 4: 1065
    Available memory at 3: 1065

I would expect the numbers (1065) would change, since a local variable (_prefs2) is made so at location 4 I would expect more space to be used.

Also, if I remove the _prefs2 code like below, the numbers stay the same.

    void test()
    {
        printAvailableMemory(4);
    }

Why is the local variable not counted?

title: Local variable usage in SRAM not counted

Answers: 1

body:
> Why is the local variable not counted?

Let us start with the function `availableMemory()`, what does it do?

    int availableMemory()
    {
      extern int __heap_start, *__brkval;
      int v;
      return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
    }

It returns the amount of memory between the top of stack (address of local variable v) and the heap end.

The answer lays in how the compiler works. One strategy that is used is function *in-lining*. This forces the functions `test(), printAvailableMemory(), availableMemory()`, etc. to be unfolded into `loop()` (which actually also gets unfolded into `main()`).

A common frame with the local variables is created and the variable for the top of the stack becomes one of them. You need a tougher test case to see how the stack top changes, e.g. tell the compiler not to in-line a function.

    int availableMemory() __attribute__ ((noinline));

To check this generate the assembly listing for your sketch.

Cheers!


body:
so I'm building something using an Uno that will run on batteries - so, I've watched a couple of these low power tutorials to lessen the energy consumption so the batteries can last longer, but they're not exactly what I want - they all require some sort of circuit. I've found this tutorial (http://www.engblaze.com/hush-little-microprocessor-avr-and-arduino-sleep-mode-basics/) which only needs an LED, and it's ideal, but I would like to know if you know of any other methods which would reduce consumption to less than 5mA without using any complicated circuits (other than unplugging the Uno)

Thank you!

title: Deep sleep mode for the Uno without complicated circuits?

Answers: 1

body:
> Deep sleep mode for the Uno without complicated circuits?

Forget using an Arduino Uno if you want to do low power (less than 10 mA standby). There is too much extra circuits (LEDs, Voltage Regulators, etc) to allow that.

See for instance, https://www.gammon.com.au/forum/?id=11497

With an Arduino Pro Mini it is possible to achieve low power after removing the Power LED and cutting the Voltage Regulator.

The hardware/software support for low power cannot really be used before the board is design for that.

Cheers!


body:
How many sensors can be used by a arduino uno and mega separately.?
Does each sensor can use the ADC of arduino simultaneously? If not how to use all the sensors simultaneously if possible?

title: Arduino analog pins

Answers: 3

body: All AVR- and ARM-based Arduinos have a single ADC, connected to multiple input channels. If you *require* simultaneous sampling of multiple sources then you will need to use one or more external ADCs.

body:
> How many sensors can be used by a arduino uno and mega separately?

Assuming you mean analog signals. As many as the number of analog pins on those boards. This can be extended by using an analog multiplexer and additional digital pins. The total number of channels is number of analog pins minus one plus log2 of the number of digital pins used to select the input channel, e.g. 8 additional analog channels through a multiplexer will require 3 digital pins for channel selection.

> Does each sensor can use the ADC of arduino simultaneously?

There is a single ADC module which takes approx. 112 us to convert an analog signal to 10-bit digital number. There is no simultaneous conversion of multiple channels.

> If not how to use all the sensors simultaneously if possible?

All sensor can be connected but only one at a time is sampled and conversion to digital number.

Cheers!

body:
> If not how to use all the sensors simultaneously if possible?

a few ways:

1) use external adc;

2) use a sample-and-hold circuitry on the sensors;

3) find a mcu that has more than one adc modules; some pic24/dspics have that. some atxmegas have that. and some arm chips have that as well, to list a few.

4) use multiple avrs, each for a sensor;

...


body:
My Arduino nano make weired thing...
The TX LED is on when i define a Variable and a digital Pin as output. Do you now if it is a error in the code? If I upload a clear new sketch the LED is off.

*~Nico*

Code:

>     int ok = 1;
>     int err = 0;
>     int x1 = 2;
>     int x2 = 3;
>     int x3 = 4;
>     int x4 = 5;
>     int x5 = 6;
>     int x6 = 7;
>     int y1 = 8;
>     int y2 = 9;
>     int y3 = 10;
>     int y4 = 11;
>     int y5 = 12;
>     int y6 = 13;
>     int value1 = digitalRead(14);
>     int value2 = digitalRead(15);
>     int value3 = digitalRead(16);
>     int test = digitalRead(17);
>
>     void setup() {
>       pinMode(0, OUTPUT);
>       pinMode(1, OUTPUT);
>       pinMode(2, OUTPUT);
>       pinMode(3, OUTPUT);
>       pinMode(4, OUTPUT);
>       pinMode(5, OUTPUT);
>       pinMode(6, OUTPUT);
>       pinMode(7, OUTPUT);
>       pinMode(8, OUTPUT);
>       pinMode(9, OUTPUT);
>       pinMode(10, OUTPUT);
>       pinMode(11, OUTPUT);
>       pinMode(12, OUTPUT);
>       pinMode(13, OUTPUT);
>       pinMode(14, INPUT);
>       pinMode(15, INPUT);
>       pinMode(16, INPUT);
>       pinMode(17, INPUT);
>     }
>
>     void loop() {
>       // put your main code here, to run repeatedly:
>
>     }

title: Arduino Nano TX LED is on

Answers: 1

body:
You configure serial pins as output, this may be your issue.

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

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

also, you're calling some digitalRead() before setup call, you would have to do that in the loop.


body:
I am moving a project from breadboard and jumper cables.
It light a bunch of LEDs with different sets running of many almost every pin.
I need a few meters of cables.
I will a resistor on each led.
I have no idea what kinda cable/wire to use and googling cable gets me nowhere.
What kinda wire do people use?

title: wiring a arduino led project

Answers: 1

body:
When choosing wire for your project the main consideration is the amount of current. Second would be the distance.

For LEDs the current is generally low (milliamps) so something like a 20 or 22 gauge wire would be fine. You should be able to get it at a local hobby electronics shop or [Amazon](https://www.amazon.com/s/ref=nb_sb_ss_c_1_13?url=search-alias=aps&field-keywords=22+guage+wire+electronic&sprefix=22+guage+wire,aps,202&crid=1ANPJ8T93086Y) of course.

FYI, Wire gauge numbering is such that the lower the number the thicker wire. Thus 20 is thicker than 22.

You may find this AWG (American Wire Gauge) table helpful: http://www.powerstream.com/Wire_Size.htm


body:
I have an Arduino micro, uno, and mega and none of them will connect to the com port on the Arduino IDE. I went to the device manager aand it is recognized but when I try to update the driver I get this:
[![][1]][1]

Any help of how to fix this problem?

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

title: Arduino IDE COM Port error on Windows 10

Answers: 2

body:
An easy thing to try but might not help: Use another USB port of your computer and see if the driver is reinstalled.

Otherwise, go to control panel and find the drivers (Device Manager), search for the Ports (COM & LPT) drivers and remove the driver for the Arduino manually, reconnect the Arduino and check if it is installed correctly. Possibly a wrong version of an Arduino driver is installed. If another driver is installed at COM3 (where is my Arduino), remove that driver and try again.

body:
Option 1: Try to update or reinstall com port driver in control panel/device manager...

Option 2: There might be problem while installing Arduino IDE or problem occur during Arduino gets board and library updates over air itself. Try to reinstall IDE.


body:
I am trying to test simple communication between a Xbee on my Arduino Due and a Xbee linked to XTCU. I attached jumper wires from RX and TX to RX1 and TX1 (Serial 1 hardware port) but I cannot send or receive data between the Xbees. I tested the Xbees previously with an Arduino Zero talking to the XTCU and it worked flawlessly.

Extra information: I am using a Xbee Shield on my Arduino Due (as shown in the picture)

    char c,d;

    void setup()
    {
    // put your setup code here, to run once:
    Serial.begin(9600);
    Serial1.begin(9600);

    }

    void loop()
    {
    // put your main code here, to run repeatedly:
    if (Serial1.available())
    {
     c = Serial1.read();
     Serial.print(c);
    }
    else if (Serial.available())
    {
     d = Serial.read();
     Serial1.print(d);
    }

    }

My wiring is attached. What am I doing wrong?[![enter image description here][1]][1]

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

title: Serial1 is not reading the Xbee on a Arduino Due

Answers: 2

body:
I fixed my problem. I stupidly left the Xbee Shield on DLINE instead of UART. Now there is communication between the radio modules. I have another question. When I type a character into XTCU, it "receives" the exact character from the Arduino Due. I have used this basic code with other Arduinos before and this has never happened.

Extra information: The serial monitor solely prints out received data.

I attached an example. [![enter image description here][1]][1]

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

body:
Has there been any update on this problem?  Your post has been incredibly helpful as I've been looking for ways to use a Due and an Xbee (specifically with the Sparkfun Xbee shield).

I haven't been able to solve this entirely, but I've noticed a few things;
First of all if you delete the second Serial.available, it does not change the functionality of the code at all, still works the same way.  I believe this has to do with the hardware Tx and Rx pins on the Due.

What seems to be happening is that if you use XCTU to send information to the Due, XCTU sends the data out, in which the Due receives it.  Then it bounces back and seemingly resends it from the Due to XCTU again, without displaying in the serial monitor.  I'm probably wrong in my observations but very curious if there's an answer to this.  Hope to hear back from someone soon.  Thanks!

*EDIT*

Upon thinking about it, I figured out a work around.  As stated in one of the comments earlier, you still have the shield's Rx and Tx pins connected to the Due.  This is what's giving you double values on XCTU.  The Due receives the input from XCTU and immediately sends it back out to XCTU.  A simple fix is bending the Rx and Tx pins out slightly so they are not connected to the Due but all of the other pins remain in place.  I hope this ends up being helpful!


body: My project is based on controlling a moving fan using different hand gestures. I am using image processing toolbox from matlab to detect and identify various hand movements.I want to link my matlab codes to arduino for hardware implementation. How to link these two?

title: Linking Arduino and Matlab

Answers: 1

body:
This block of code can give you some idea...

    % create an arduino object

    a = arduino('com3', 'uno');

    % start the loop to blink led for 10 seconds

    for i = 1:10

        writeDigitalPin(a, 'D11', 1);

        pause(0.5);

        writeDigitalPin(a, 'D11', 0);

        pause(0.5);

    end

    % end communication with arduino

    clear a

For more details on this code and working of it you can visit....
[Here][1]

  [1]: https://www.allaboutcircuits.com/projects/arduino-interface-with-matlab/


body:
I have written this code to read x-acceleration from ADXL335.

1. Why is the value toggling between 342, 343, 344 even at rest? Is there anything I need to do to get a smooth curve? [![reference here][1]][1]

2. How to increase resolution? (I'm using a Mega 2560)

----

    int Xcurr,Ycurr,Zcurr;
    int Xpre=0,Ypre=0,Zpre=0;
    int res=0;
    // these constants describe the pins. They won't change:
    const int groundpin = A1;
    // analog input pin 4 -- ground
    const int powerpin = A0;
    // analog input pin 5 -- voltage
    const int xpin = A3;
    // x-axis of the accelerometer
    const int ypin = A2;
    // y-axis
    const int zpin = A4;
    // z-axis (only on 3-axis models)
    const int stpin = A5;

    void setup() {
      Serial.begin(9600);
      pinMode(groundpin, OUTPUT);
      pinMode(powerpin, OUTPUT);
      digitalWrite(groundpin, LOW);
      digitalWrite(powerpin, HIGH);
      pinMode(stpin, OUTPUT);
      digitalWrite(stpin, LOW);
    }

    void loop() {
      Xcurr=analogRead(xpin);
      Serial.print(Xcurr);Serial.print("\n");
      delay(100);
    }

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

title: Why is there no smooth value from ADXL335?

Answers: 1

body:
It is called moving average, the calculations you can use to prevent such problems can be found at [wikipedia][1]

In principle, what you do is take the average over the last x measurements to take away the peaks.

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


body: I have with me an Arduino UNO and an ESP8266 (12E) WiFi Module. I need to make a webserver using the two. I read that the default baud rate for ESP8266 is 115200, and that the software serial pins can't handle such high speeds. I dont have an USB-UART converter at hand. Is there a way to use my Arduino as one to change the baud rate, so that I can interface with the chip using the software serial pins of the Arduino later.

title: How to change the baud rate of ESP8266 (12E) using an Arduino Uno?

Answers: 3

body:
You can use this block of code in Arduino to set baud rate...

    void setup()
    {
      Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
    }

    void loop() {}

Change value in serial.begin() as per your value.

body:
Use SoftwareSerial library for your module and define your own tx and rx pins like this and then you can define baud rate for your specified serial pins.

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(8,9); // RX, TX for your module
    void setup(){
       mySerial.begin(115200);
    }

for more details visit https://www.arduino.cc/en/Reference/SoftwareSerialBegin

body:
You can use the SoftwareSerial library and define your own tx and rx pin and set baud rate according to your requirement.

    #include <SoftwareSerial.h>   // SoftwareSerial library
    SoftwareSerial mySerial(2,3); // RX, TX for your module

    void setup()
    {
       mySerial.begin(9600);      // Set your buad rate
    }

And you can also do without this library.

    void setup()
    {
      Serial.begin(9600);        // Set your baud rate
    }


body: can anyone give me an advice on connecting an 10W led + 12 volt drive to an Arduino Uno? it works without the board but when i tried to connect to Uno it doesn't work anymore. Thankyou

title: Problem connecting 10W led + Led driver Directly Arduino Uno

Answers: 2

body: You'll need a switch such as a transistor, and capable of handling 10W, to be driven by the Arduino and connect/disconnect the LED to an external 12v supply. There are many examples on the web. Remember to connect the 12v and 5v grounds together.

body:
To operate LED using Arduino you will need a switch that can be operated using electronic switch like transistor, Mosfet or Relay board.
More easy and reliable option would be using Relay Board.

You can visit this link and can get more idea....

http://www.electroschematics.com/8975/arduino-control-relay/


body: I would like to ask if I can stack directly Adafruit PN532 RFID Shield onto my breadboard. Or do I need something for that? Thank you.

title: Arduino Shield on Breadboard

Answers: 3

body:
Chances are the offset headers won't allow the shield to directly plug into a breadboard.

As @Majenko noted, shields have a header that is offset by 0.16" from the other headers. Since a breadboard is a strict 0.1" grid that header won't fit into the holes.

body:
@Mazaryk is right.

Shields have a header that is offset by 0.16" from the other headers. Since a breadboard is a strict 0.1" grid that header won't fit into the holes.

body:
There was a [Kickstarter project][1] a few years ago to make just such an adapter. You might get in touch with the developer to find out whether he's made (or is planning) another run.

  [1]: https://www.kickstarter.com/projects/818225433/breadboard-shield-adapter-for-microcontrollers-or


body:
in this code i want to pass value of variable char array 'pass' in object "MyObject". But i am getting this error.

        Arduino: 1.6.11 (Windows 8.1), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

    C:\Users\XXX\Desktop\EEPROM_put\EEPROM_put.ino: In function 'void setup()':

    EEPROM_put:17: error: array must be initialized with a brace-enclosed initializer

    };

    ^

    exit status 1
    array must be initialized with a brace-enclosed initializer

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

when i change pass to *pass, result of EEPROM.get() is 1 and 6, instead of 1, 62345, 7539514682.

    #include <EEPROM.h>
    struct MyObject {
    boolean stat;
    char password[6];
    char mobile[11];
    };

    char pass[6]="62345";
    void setup() {
    Serial.begin(9600);
    while (!Serial);
    MyObject customVar = {
      1,
      pass,
      "7539514682"
     };
    EEPROM.put(1, customVar);
    Serial.print("Written custom data type!");
    }

    void loop() {

    }

title: Passing variable value in structure object

Answers: 2

body:
Use `class` and `constructor`

    #include <EEPROM.h>
    class MyObject {
        boolean stat;
        char password[6];
        char mobile[11];
      public:
        MyObject(bool tempStat, char tempPassword[], char tempMobile[])
        {
          stat = tempStat;
          strcpy(password, tempPassword);//As suggested by mikael
          strcpy(mobile, tempMobile);
        }
    };

    char pass[6] = "62345";
    void setup() {
      Serial.begin(9600);
      while (!Serial);
      MyObject customVar(true, pass, "7539514682");
      EEPROM.put(1, customVar);
      Serial.print("Written custom data type!");
    }

body:
While the method from Sniper's answer works, it involves copying the
data, which is something you often want to avoid on an Arduino. The
simplest fix to your problem is probably to initialize your `password`
field with a literal string, just like you did with the `mobile` field:

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

    MyObject customVar = {
        1,
        "62345",
        "7539514682"
    };

or maybe, if you want the password to be written near the top of the
program,

    #define PASS "62345"

    MyObject customVar = {
        1,
        PASS,
        "7539514682"
    };

Another option is to not store the strings in the object. Instead, store
them elsewhere and have the object only hold _pointers_ to them:

    struct MyObject {
        boolean stat;
        const char *password;
        const char *mobile;
    };

    char pass[6] = "62345";

    [...]

    MyObject customVar = {
        1,
        pass,
        "7539514682"
    };

Note that, in this case, the mobile number is stored by the compiler as
an unnamed string constant. Because it is constant, the `mobile` field
has been typed as `const char *`. I typed the `password` field
identically for symmetry, but in this use case it need not be `const`.


body:
I need to write a program that takes a user inputted HEX value and converts it to binary, then an LED blinks according to the number of 1's in the binary. For instance, if the value is 0xABC then there are number of 1's are 7 so LED will blink 7 times.

I only just started Arduino so not sure how to let user input a value nor do I know how to convert HEX to BIN but I'm assuming that once I convert the HEX to BIN I can just use a loop to count the number of 1's yet I'm unsure as to actually how to do that. This is what I've written so far.

      byte val=0xABC;
    int ledPin=13;

    int countSetBits(unsigned int n)
    {
     unsigned int c;
     for (c=0;n>0;n=n&(n-1))
      c++;
     return c;
    }

    void blink(int n)
    {
     for (int i = 0; i < n; i++)
     {
      digitalWrite(ledPin,HIGH);
      delay(500);
      digitalWrite(ledPin, LOW);
      delay(500);
     }
    }

    void setup()
    {
     Serial.begin(9600);
     pinMode(ledPin,OUTPUT);
     blink(countSetBits(val));
    }

    void loop()
    { }

Any help would be appreciated.
EDIT: If I want to take a number from a user and then make the LED blink according to the number of 1's in its binary form, how would I implement that?

title: Hex to binary, LED blinking

Answers: 4

body:
You might do it much simpler... Create a fixed array that for each hex character possible (0..F) has the number of 1's counted.

Than iterate through the string, sum up the values of 1's from the array and make a LED blink that many times.

Something in pseudo code:

    // Number of 1's: 0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
    boolean ones[] = {0, 1, 1, 2, 1, 2, 2, 3, 1, ...                };
    string str = "ABC";
    int total = 0;
    for (index = 0; index < str.length; index++)
    {
       if string[index] <= '9'
           total += ones[string[index] - '0'];
       else
           total += ones[string[index] - 'A' + 10];
    }

body:
> Any help would be appreciated.

your code is in pretty good shape - there are some minor issues that need to be taken care of. the countSetBits() is a fairly standard implementation and in this case returns the right value:

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

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

I sped up the blinky rate for convenience.

a good starting out place.

body:
You are almost there. Now you just have to read and parse the hex
numbers supplied by the user.

The simplest way to accept numeric user input is with
`Serial.parseInt()`. This is not always ideal since it involves blocking
the program until it either receives an invalid character or the reading
times out. It is also not applicable to your situation because it only
works with decimal numbers.

The better standard way to get the input is to put the incoming bytes
into a buffer until you catch a specific character designated as an end
of message marker. This is typically a CR (`'\r'` in C++) or an LF
(`'\n'`). This technique is more involved than just calling `parseInt()`
but it is often preferred because it can be done in a non-blocking way.
See for example this simple [command line interpreter][].

In your case, however, you do not need to buffer the incoming bytes. You
can instead parse the hex number while you read it, like this:

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

    void loop()
    {
        if (Serial.available()) {
            static unsigned int val;
            int c = Serial.read();
            if (c >= '0' && c <= '9') {
                val = 16 * val + (c - '0');
            } else if (c >= 'a' && c <= 'f') {
                val = 16 * val + (c - 'a' + 10);
            } else if (c >= 'A' && c <= 'F') {
                val = 16 * val + (c - 'A' + 10);
            } else {  // End of number.
                blink(countSetBits(val));
                val = 0;  // reset for next round
            }
        }
    }

[command line interpreter]: https://gist.github.com/edgar-bonet/607b387260388be77e96

body:
You could use *BIT SHIFTING* looks flash, but is actually really useful.

    const unsigned char value = 0x55;  // Input
    int blinks = 0;                    // Times to blink.

    for (int i = 0; i < 8; ++i)
    {
        blinks += ((value >> i) & 0x01); // Could just blink the light if its true.
    }

`(value >> i)` takes value and moves the number right `i` places.  So if value is Hex 55 (0x55) that is 01010101 in binary.  On the first time around the loop when `i` is 0 `(value >> 0)` will be 0x55 (unchanged).   `0x55 & 0x01` is a logical and between the two numbers, so any bits that are set in both will be set in the result.  Since 0x01 only has the least significant bit set (LSB) then we only need to look at the LSB of 0x55, which we know is set.  therefore blinks is incremented by one.
On the second time around the loop `value >> i` is 0x2A (00101010) because value has been shifted right one place.  So `0x2A & 0x01` = 0, so blink isn't altered.

etc.

The answer at the end of the loop is `blinks == 4`.


body:
I'm currently looking to buy an Arduino, but never touched robotics before. Would anyone be able to give me an idea how many pins a sensor such a magnetometer would use? This is for Arduino Uno.

Sorry if this is stupid, just really have no idea how to approach Arduino design without having one here and can't get one for a few weeks at the least.

Thanks!

title: How many pins are needed for a sensor?

Answers: 5

body:
One, maybe two. It's impossible to say for sure without a concrete example.

I would recommend looking up the type of sensor(s) you want to use, and read the data sheet(s). Things you'll want to consider are things like operating voltage (3.3v or 5v), current draw (>40mA?), are any additional passive components required (capacitors, resistors, ...), etc.

Data sheets will describe in great detail, how to use a specific device.

body:
> Would anyone be able to give me an idea how many pins a sensor such a
> magnetometer would use?

Here below image provides the connection and pin requirements for magnetometer...

[![Magnetometer][1]][1]

According to image magnetometer will require 4 pins of Arduino 2 pins of supply i.e +3 volt and Ground and other two pins will be any two Analog pins of Arduino.

And to connect other sensors with Arduino, you can find datasheet of desired sensor and can find how many pins that sensor is going to use.

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

body:
Below image is the answer to your question.

[![Connection][1]][1]

According to this image, magnetometer required four pins of arduino.

GND of magnetometer ----> Arduino GND

Vcc of magnetometer ----> Arduino 3.3 Volt

SDA of magnetometer ----> Arduino Analog Pin 4

SCL of magnetometer ----> Arduino Analog Pin 5

I hope it will help you.

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

body:
> How many pins are needed for a sensor?

As many pins as are needed for that sensor.

*Every* sensor is different. The datasheet or manual for the sensor or the chip or other device that the sensor is based around will tell you how the interface to it works - what each pin does, how you use it, etc.

It is up to *you* to read that documentation and learn how the sensor works to then be able to plan how best to connect it to your Arduino.

Some sensors require specific connections, such as the two I2C pins in your example sensor. Others may need the SPI pins. Then there are sensors that use analog inputs. That may be one pin for, say, an LDR, or three pins in the case of a 3-axis accelerometer.

In short: RTFM.

body:
Broadly speaking, look for sensors/outputs that use I2C or SPI interfaces. If you use I2c, you can wire all your sensors with two digital pins. This is especially important with multi-axis sensors that would otherwise chew up 3-6 pins each.

I2C is probably easier because SPI need one extra pin per device, in addition to the 2 base pins. Still, that's about 10 devices on one UNO, IF you spend the extra $1 or $2 on the SPI/I2C sensors/LCDs/etc instead of going for what at first seems like a cheaper part.


body:
I am using an ATmega328P with internal clock (8 MHz) with a SIM800L module. The default baud rate of the SIM800L is 115,200 baud and I can't make them talk to each other correctly. Although I was able to make them talk very easily at a baud rate of 9600 baud. But now, with a new SIM800L I can't.

Question:

How to change the default baud rate of a SIM800L?
Is it possible to run an ATmega328P at a baud rate of 115,200 baud?

Thanks in advance!

EDIT:

I know that I can run atmega328p at baud rate of 115200 with different crystal, but is it possible to it using internal crystal.

title: SIM800L change default baud rate

Answers: 5

body:
As you say, SIM800L default baud rate is 115200. So, you have to set that baud rate on arduino side. And yes, it is possible to run an ATmega328P at a baud rate of 115200 baud.

You can use the SoftwareSerial library and define your own tx and rx pin and set baud rate according to your requirement.

    #include <SoftwareSerial.h>   // SoftwareSerial library
    SoftwareSerial mySerial(2,3); // RX, TX for your module

    void setup()
    {
       mySerial.begin(115200);      // Set your buad rate
    }

And you can also do without this library.

    void setup()
    {
      Serial.begin(115200);        // Set your baud rate
    }

body:
According to [Adafruit's pdf specsheet *SIM800+Series_Serial+Port_Application+Note_V1.01.pdf*](https://cdn-shop.adafruit.com/product-files/2637/SIM800+Series_Serial+Port_Application+Note_V1.01.pdf), the SIM800 is set up to auto-baud when it starts out:

>SIM800 series is designed in autobauding mode by default. Autobauding allows SIM800 series to automatically detect the baud rate of the host device. In application, host device must to synchronize the baud rate with SIM800 series. Host device must firstly send characters "AT" or "at" to synchronize the baud rate. It is recommended to send "AT" until host device receives the "OK" response, which means host device and SIM800 series are correctly synchronized. Once the baud rate is synchronized, it is suggested to use AT command "AT+IPR" to set SIM800 series baud rate according the host baud rate. ...

So, you might arrange your software to keep trying at 9600 bps.  If you get an ok connection at that rate, you can either keep using it or shift to a higher frequency via "AT+IPR".  [I haven't read the spec sheet enough to know whether that default autobauding is always on, or might be turned off somehow.]

As serial-data bps goes up, required clock accuracy becomes tighter.  Where a couple of percent error may be ok at 9600 bps, under a percent probably is needed at 115200 bps.

On several boards I've measured RC oscillator frequency errors of about 2%, which according to question [How critical are UART frequencies?](https://electronics.stackexchange.com/q/5850) might or might not be good enough to allow high-speed serial communications.

If you can measure your ATmega328P's RC oscillator frequency, you can then apply a correction factor at startup.  In the spec sheet (eg Atmel-8271J-AVR-ATmega-Datasheet_11/2015), see §9.12.1, *OSCCAL – Oscillator Calibration Register*.

Your program can start out with the RC oscillator using the factory-set value, and then can load your own calibration value into the Oscillator Calibration Register to shift RC frequency as needed to make the board work ok for 115200 bps serial data.  Or, you can overwrite (in EEPROM fuse or signature area) the factory-set value with your own number.

Figure 32-37, *ATmega48PA: Calibrated 8MHz RC Oscillator Frequency vs. OSCCAL Value*, shows typical frequencies for various Oscillator Calibration Register values.  It is possible to tune clock frequency close enough that serial communications should work ok.

High-range byte values 144 through 160 typically move frequency from around 7.4 MHz to 8 MHz (at 85℃).  In this range, each count shifts clock frequency by about 0.5%.  See the figure for details.  For example, if value 158 gives an RC frequency of about 7820 KHz, then value 159 might raise the RC frequency to about 7860 KHz.

Low-range entries 96 through 112 move frequency from around 7.5 MHz to 8.5 MHz.  This overlap makes it necessary to try both low-range and high-range values when looking for the best Calibration Register value.

Note, there are inexpensive cymometers (frequency counters) on ebay, which can measure oscillator frequencies accurately enough to enable the calibration suggested above.

body:
From what I have read so far, the problem is that there is no good divisor from an 8 MHz oscillator to get a within-spec baud rate above 57,600. Using the internal oscillator is also susceptible to variation with temperature, so that appears to be bad solution as well in many applications. The problem being that it may work on one MPU, but not with the next one.

As far as I can tell, the best solution is to use a 7.372800 MHz oscillator. This results in the processor running a bit slower, but it also results in the baud rate divisors being spot-on for almost all the standard and popular baud rates, meaning you should be able to run to at least 921,000 baud.

If anyone has a better solution, I would love to hear it, as I am dealing with a similar issue in something I intend to take into production that will be in a variety of environments.

body:
Well I do not think that the default baud rate is 115200. The default setting is autobaud which does not support 115200 baudrate. From the [datasheet][1].

[![serial port properties][2]][2]

You can change it with the already mentioned `AT+IPR` command. From the [AT manual][3] you can also check that the default setting is autobaud, and also the selectable baud rates.

> Note:  User  can  use  AT  command  “AT+IPR=x”  to  set  a  fixed  baud  rate  and  the  setting  will  be  saved  to  non-volatile  flash  memory  automatically.

[![AT+IPR command][4]][4]

If you use 57600 you will probably alright and you do not even have to change the baud rate settings as this value is supported.

  [1]: http://wiki.seeedstudio.com/images/4/46/SIM800L_Hardware_Design_V1.00.pdf
  [2]: https://i.stack.imgur.com/rE3ez.png
  [3]: https://www.elecrow.com/download/SIM800 Series_AT Command Manual_V1.09.pdf
  [4]: https://i.stack.imgur.com/zYtNb.png

body:
You can change the baud rate to 9600 on the SIM800L with the command:

    AT+IPR=9600

Then to save this (to last between boot cycles), give the command:

    AT&W

To see the saved settings, give the following command:

    AT&V


body:
I've been told 2 by a friend but this looks to only use one?

https://www.adafruit.com/product/1746

title: How many pins does this circuit (HMC5883L) use?

Answers: 4

body:
It is I2C so 2 pins.

Optionally it can use a third pin to indicate data ready.

body:
Below image is the answer to your question.

[![Conncetion][1]][1]

According to this image, magnetometer required four pins of arduino.

GND of magnetometer ----> Arduino GND

Vcc of magnetometer ----> Arduino 3.3 Volt

SDA of magnetometer ----> Arduino Analog Pin 4

SCL of magnetometer ----> Arduino Analog Pin 5

A4, A5 on Uno are SDA, SCL, required for hardware-based I2C.

I hope it will help you.

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

body:
It depends what you think of as a pin.

You have VIn and Gnd, SCL and SDA are the 4 main pins you will need to connect.  The 3.3V and RDY pin don't seem to be connected in any of the pics I can see.

So the answer is 2 pins plus 2 power.

Oh from the page on how to use it, https://learn.adafruit.com/adafruit-hmc5883l-breakout-triple-axis-magnetometer-compass-sensor/wiring-and-test:
"This 3-axis magnetometer breakout is thankfully very easy to use. It only requires 2 power pins and 2 data pins."

Interestingly it doesn't appear to use pull up resistors, which most I2C device require, so the might be built into the board.

body:
Here below image provides the connection and pin requirements for magnetometer...

[![Sensor Pins][1]][1]

According to image magnetometer will require 4 pins of Arduino 2 pins of supply i.e +3 volt and Ground and other two pins will be A4 & A5 pins of Arduino.

And to connect other sensors with Arduino, you can find datasheet of desired sensor and can find how many pins that sensor is going to use.

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


body: In tutorial - https://www.arduino.cc/en/Main/Standalone , they have used voltage regulator. Can we able to do without Voltage regulator ?(to compact the circuit), If so what should the voltage & current value in Atmega328?

title: Arduino Standalone construction

Answers: 1

body:
That's actually quite an involved question to answer. The short answer is "Yes, you can do without the regulator as long as you get the voltage right".

And that is where it gets tricky.

The datasheet states:

> * Operating Voltage:
>   * 1.8 - 5.5V

So you can power it from two or three AA batteries, for instance (3V - 4.5V). However, that is not the whole story.

The voltage you provide it with dictates what frequency the chip can reliably run at. Later in the datasheet is this nice little graph:

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

Since the normal Uno-like arrangement runs at 16MHz you're looking at a minimum voltage of around 3.8V - 4V (it's actually quite hard to work out from that graph).

But if you are willing to reduce your clock speed to 8MHz (which is what the 3.3V Arduino "Pro" boards run at) then you can drop right down to about 2.5V.

At a 2.5V lower limit with 3 AA batteries it would equate to a minimum voltage of 0.83V per cell, which is below the normal minimum accepted "flat" voltage of 0.9V per cell.

So powering from 3 AA batteries with a clock speed of no more than 8MHz would give you probably the best run-time.  Note, also, that a decrease in clock frequency decreases the current consumption as well - the slower you run the chip the less current it needs. You can see that in this graph in the datasheet:

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

And yes, as you can see, the lower the supply voltage the lower the current as well. So as the batteries run down and the voltage drops so does the current, reducing the speed at which the batteries will run down.

As you can see, if you don't mind the supply voltage changing (which of course will affect everything else in the circuit, so you need to check those out first), running directly from batteries without a regulator can actually have advantages. But as I say, you need to check what else you are running in the circuit to make sure it doesn't mind if the power supply voltage drifts.

And don't forget, also, that the supply voltage affects the ADC readings, since they are referenced to that voltage as well.

  [1]: https://i.stack.imgur.com/AWJJe.png
  [2]: https://i.stack.imgur.com/7PrDR.png