message:
Low Power Library 4 seconds ON, 10 minutes OFF

Could someone please demonstrate how to use a counter with the Arduino 'low power' library to wait for 10 minutes then digitalWrite 4000, HIGH and loop. (I don't mean the simple 'blink' sketch).

I'm trying to save as much power as possible, so any advice is appreciated.

Thanks!

body:
Your problem here is your 10 minutes mark. If you're willing to take a somewhat more complex route, you could use a low-power, programmable, external timer like [TPL5110][1]. You can set an interval of up to 120 minutes by selecting the appropriate value of the programming resistor.

This kind of timers can be used to drive the gate of a logic-level P-channel MOSFET that acts as a switch for the power line of the Arduino.

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

Then, you simply you do all your stuff on the `setup()` function and leave `loop()` empty. You can switch off the Arduino by sending back a DONE signal to the TPL5110 at the end for your `setup()`.

[![Timing][3]][3]

If, for whatever reasons, you really want your Arduino to be running for exactly 3 seconds, then you should run a timer in it (beware: not related in any way with TPL5110). Set it up so you the ISR of the timer breaks a do-while waiting loop just before the line of code that sends back the DONE signal.

  [1]: http://www.ti.com/lit/ds/symlink/tpl5110.pdf
  [2]: https://i.stack.imgur.com/3wtuv.png
  [3]: https://i.stack.imgur.com/okIDCm.png


sender: user

sender: assistant

body:
Agreed with what most others have already mentioned;
The Arduino as-is is not suitable for low power operation - it is best to turn it off completely. The circuit below should do what you want, and is based on a very simple and cheap IC, the 555 timer.

<!-- 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/AE4lY.png)

<!-- End schematic -->

A similar version of this has been working for me for about 2 years in a remote sensing setup. A few things to note to make sure that it works;

1. This needs the TLC555 chip which is a CMOS IC. The TTL version (NE555) will not work with such high value timing resistors.

2. The timing capacitor (shown as 141uF, just use 3 x 47uF in parallel) needs to be a tantalum capacitor. The normal electrolytic version has too high a leakage current.

3. As shown, this should turn off the Arduino for about 580s, and on for 120s. To turn off the Arduino sooner, drive digital pin 5 high. This will discharge C1 through R3 and Q1 quickly (about 500ms).

4. To change the delay times, alter R1, R2, and C1. The datasheet has all the equations that you need for this.

5. it would probably be wise to put a bypass capacitor between the supply rails very close to the TLC555 chip. 10uF should do.

6. This circuit should draw around 360uA while the Arduino is off.

One final thing - the task that you are using the Arduino for sounds pretty simple - driving a digital line high for 4 seconds every 10 minutes. I guess that you have more to it than that, but if not, then you could save yourself the cost and complexity, and do away with the Arduino completely. In that case, R1 should be about 6M1, and R2 about 41K, you can remove Q1, D1, R3 and R6, and whatever you are driving goes in place of the Arduino.


message:
EEPROM write time

I will implements an emergency backup feature before power off, on Arduino Mega 2650.
Arduino is powered by capacitor, for the time (I hope) of the EEPROM write.

On AVR2650 Datasheet is reported that the typical EEPROM writing time is 3.3ms.
But 3.3ms for what? a byte? a word? the whole EEPROM?

I need the data for calculate the capacitors.

body:
> On AVR2650 Datasheet is reported that the typical EEPROM writing time is 3.3ms. But 3.3ms for what? a byte? a word? the whole EEPROM?

That is per byte (erase and write 3.4 ms, only write is 1.8 ms). When writing multiple bytes there are a few clock cycles to be gained by preparing for the next byte during an ongoing EEPROM write. Or even better use an ISR for the EEPROM feed. Not faster but allows some additional processing while a block is written. The largest gain is to have the EEPROM erased before the write (1.8 ms per byte instead of 3.4 ms).

Please see http://www.nongnu.org/avr-libc/user-manual/group__avr__eeprom.html,  http://www.atmel.com/images/doc2578.pdf and table 9-1, pp. 35, http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf.

Cheers!


message:
Using Arduino as a pc remote controller

I would like to create a simple remote controller (IR) with my Arduino Nano that would control my PC. (Volume up/down, stop, play and that sort of things...)
I have no problem with creating 'hardware part' and Arduino script, that would send commands through serial as a reaction to IR signals.
I can imagine python script that would react to commands received on the serial port.

My problem is: "How can I detect on which port should I listen to?" What is the right way to do it?

body:
Since I can not commemnt due to low reputation, I'm "commenting" here.
You can search for LIRC and WinLIRC


message:
Trying to move a stepper motor back and forth

So, I am trying to move a stepper motor through a halfway revolution (1024 steps), and once that is completed, have it move back and forth by about 100 steps in either direction.

I am having some trouble with this though, because while it will move in one direction, it will not move in the other.

    void setup()
    {
        stepper1.setMaxSpeed(1000);
        stepper1.moveTo(1024);
        stepper1.setAcceleration(100);
        Serial.begin(19200);
        while(!Serial);
    }

    void loop()
    {
        stepper1.run();
        static int ctr = 0; //counter value to store how many times the back and forth motion has occured
        if(stepper1.currentPosition() == 1024){
          backMotion(stepper1.currentPosition());
          forthMotion(stepper1.currentPosition());
          ctr++;
        }
    //    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
    //      forthMotion(stepper1.currentPosition());
    //    }
    }

    void backMotion(int value){
        int current = value;
        int back_distance = current - 200; //distance to move back by
        stepper1.moveTo(back_distance);
    }

    void forthMotion(int value) {
      int current = value;
      int forth_distance = current+200;
      stepper1.moveTo(forth_distance);
    }

So, when I call the forthMotion function right after the backMotion function, it will just move forward. Which makes no sense to me. Shouldn't it be moving backwards, and then forwards in an infinite loop?
Because it will hit 1024, go back to 824, hit 1024 again, and so on and on...

Also, when I call the backMotion function, isn't the Arduino code supposed to be blocking in that, nothing else gets executed while that is running?

Edit: The code seems to work when I uncomment the if statement in the loop function.

body:
Steppers don't typically have feedback about their position (as opposed to servos). Normally you're just telling a stepper how much and how quickly to rotate. As opposed to servos, which you tell which position to rotate to.

Are you sure you're using a stepper?


body:
I guess the solution might be this:

in back motion
```
void backMotion(){

    int back_distance = - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}
```

In forward motion
```
void forthMotion() {

  int forth_distance = 200;
  stepper1.moveTo(forth_distance);
}
```

In loop
```
void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured

    stepper1.moveTo(1024);
    while(ctr < 30){

      backMotion();
      delay(500);

      forthMotion();
      delay(500);
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

```
Your main code will be like this

```
void setup()
{
    stepper1.setMaxSpeed(1000);
    stepper1.moveTo(1024);
    delay(3000); // wait till stepper gets to destination
    stepper1.setAcceleration(100);
    Serial.begin(19200);
    while(!Serial);
}

void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured

    while(ctr < 30){

      backMotion();
      delay(500);

      forthMotion();
      delay(500);
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

void backMotion(){

    int back_distance = - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion() {

  int forth_distance = 200;
  stepper1.moveTo(forth_distance);
}

```


message:
Arduino LED Dimmer Proportionate to Ambient Light

I am trying to get an LED dimming reversely proportionate to natural light level in a room.
So as the sun rises, the LED dims and vice-versa.
I am using the standard LDR+ 10k Ohm resistor divider, an LED, and an Arduino Leonardo Clone.

The issue is, regardless of the values I adjust in `map()`, it does not change the flickering rate or brightness of the LED.
What range of map shuold I be using?

The LED ought to shut off while the LDR takes a reading.
I have two variations of the code; one uses PWM, the other simulates PWM using `delay()`

Here are my sketches:

    /set pin numbers
    //const won't change
    const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
    const int ldrPin = A0;  // A0 the number of the LDR pin
    //10K ohm resistor as voltage reference.

    void setup() {

      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
      pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
    }

    void loop() {
      digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
      int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
      // KEEP LED OFF TIME BASED ON AMBIENT LIGHT LEVEL...
      int dim2 = map(ldrStatus, 0, 1023, 500, 0); //OFF FOR UP TO 0.50 seconds.
      digitalWrite(ledPin, HIGH);
      delay(dim2);

       }

Sketch two:

    //set pin numbers
    //const won't change
    const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
    const int ldrPin = A0;  // A0 the number of the LDR pin
    //10K OHM resistor as voltage reference.

    void setup() {

      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
      pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
    }

    void loop() {
      digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
      int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
      int dim = map(ldrStatus, 0, 1023, 255, 0);     // scale it to use it with the LED (value between 0 and 255)
      digitalWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.

       }

body:
For certain Arduino models, the PWM pins are different. For the iteaduino lite, a usable PWM pin is pin D5.

Here is the code updated to use D5 instead of D1, which lacks PWM abilities:

    //set pin numbers
    //const won't change
    const int ledPin = 5;   //D5 PWM the number of the LED pin (OR to MOSFET input wire for controlling high power LED
    const int ldrPin = A0;  // A0 the number of the LDR pin
    //10K OHM resistor as voltage reference.

    void setup() {

      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
      pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
    }

    void loop() {
      digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
      int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
      int dim = map(ldrStatus, 0, 1023, 0, 255);     // scale it to use it with the LED (value between 0 and 255)
      analogWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.
      Serial.println(dim);
       }

There is still flickering, but that is to be expected. `map()` ranges can be adjusted to set when the LED will be fully off or on.

It is still unclear how to allow the light sensor to take a reading while the LED is OFF, then power back on rapidly enough to not have a visible flicker.
If anyone has thoughts on that, it would be appreciated!
Thanks everyone for helping.


message:
Arduino Yun Analog Read Problem

I am having some major issues with my Arduino Yun.

When attempting to read a value from the analog pins, the Yun is giving me incorrect constant values.

I have attached everything to a common ground, and I am supplying 3.3 volts to the A0 pin on the Yun.

The weird thing is, the pins all give constant values in ascending order, no matter what is connected to them, or if nothing is connected at all.

- A0 - 18
- A1 - 19
- A2 - 20
- A3 - 21
- A4 - 22
- A5 - 23

The code I am running is a very simple script.

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

    float i;

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

    void loop() {
      i = A0;
      Serial.println(i);
      delay(1000);
    }

body:
You are not reading from any analog pins. You are just printing out the digital pin number of the analog pin.

Look at some [basic examples](https://github.com/arduino/Arduino/blob/1.8.1/build/shared/examples/01.Basics/AnalogReadSerial/AnalogReadSerial.ino) on how to read analog values.

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

    /*
      AnalogReadSerial
      Reads an analog input on pin 0, prints the result to the serial monitor.
      Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
      Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

      This example code is in the public domain.
    */

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(A0);
      // print out the value you read:
      Serial.println(sensorValue);
      delay(1);        // delay in between reads for stability
    }


message:
External Flash Memory File System

I'm building a weather data collector and I want to be able to dump that weather data somewhere. I've considered the options, and since I'm going to be storing a fairly small amount of data (in the megabyte range) I don't want to use SD cards (also SD cards are expensive). I've heard of use of NAND flash memory chips (like the W25Q32), and I was hoping that I could possibly interact with them in a simple way (since most ways require writing to each individual address). Is there possibly a way to build a file system within one of these small flash memory chips and interact with them as simply as interacting with an SD card?

TLDR: I want to interact with a flash memory chip easily to store basic ASCII data

body:
This lib offers a means of reading and writing ASCII arrays to flash devices. This would be a simple solution for such a data logger requirements. It's ASCII orientated.

https://github.com/schinken/Flash


body:
I don't think you need a file system: that is usually needed when you want to manage *many* files. Your weather data log sounds like a single file.

What you seem to need is to access EEPROM as a *stream*, exactly like you would for an open file. There are stream wrappers around some EEPROM libraries, e.g. [this one for ESP](https://github.com/lasselukkari/EepromStream). I suggest you check it out and see if you can adapt it to the EEPROM library you use.


message:
How to connect 70 analog sensor to a single Arduino (Mega or Uno) device?

I was working on a project in which I need to collect soil moisture data for a farm. For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino. But, this is not possible as there are just 6 analog pins on Arduino Uno and 16 analog pins on Arduino Mega. I have restrictions on the number Arduino that I can use that is just one due to monetary constrains.
        The data would be collected at a delay of 5 seconds. The data gathered would be stored on SD card module which would be analyzed later.
      Any suggestion on how I can collect data from 70 analog sensors on a single Arduino would be highly appreciated. Are there any alternatives that I can use in place of Arduino? I heard that we could do something with AVR  atmega Microcontroller, am I correct? I don't know how to use Microcontroller; any useful resources will be highly appreciated. Thank You.

body:
You should use some cheap chips to collect the data and use only one with big capacity to finally combine and process the data further.

>Consider using a cheap small Arduino to build a "base module" that can do some of the tasks needed, build a bunch of them and hook them up to a R485 bus, and have one master Arduino control them all. That would be a much more flexible and expandable system. The cheapes Arduinos cost around 10$. If you build your own you could probably do it even cheaper.

**Source**:

 [1] http://forum.arduino.cc/index.php?topic=73861.0
(quote)

 [2] https://arduino-info.wikispaces.com/RS485-Modules (bus)


body:
There are fairly inexpensive chips called "analog multiplexers" which let you choose one input out of a range (8 or 16 is typical). You could take the reading, then switch to a different input, and take another reading.

I have a [page about analog multiplexers](http://www.gammon.com.au/forum/?id=11976).

Example of it in operation:

[![Multiplexer][1]][1]

In this example you have 8 inputs, and by setting the A/B/C pins appropriately, one of the 8 is selected and appears at the O/I pin (output/input).

There is a 16-channel model as well. I see the 16-pin chip (74HC4067) available on eBay for $US 1.26 right now. You can get four of them (which would give you 80 inputs) for $4.88.

Also see the [Wikipedia article on multiplexers](http://en.wikipedia.org/wiki/Multiplexer).

---

>  For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino.

Yes, well how will these sections get their data into one place? That is probably the bigger problem.

You may need to use a lengthy cable using [RS485](http://www.gammon.com.au/forum/?id=11428) (balanced signals) or maybe cheap radio transceivers.

Trying to use a "single Arduino" on what might be quite a large farm is the issue. It's not the Arduino's fault. You have to have some way of sending the data from the further points to where it is to be collected.

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


body: Given that good moisture sensors are going to be an order of magnitude more expensive than the logger, I'd suggest that you are giving yourself more problems than it's worth to try to connect that many sensors to the same unit. A Pro-mini based logger rarely comes in >$25. Even though we can connect that many one-wire sensors to a single logger ( https://thecavepearlproject.org/2015/03/01/using-ds18b20-sensors-to-make-a-diy-thermistor-string-pt-1-the-build/ ) it's not a good idea from the perspective of the amount of data that is lost if you have a single point failure. Generally we only put 10-15 sensors on any one unit, and we try to deploy them in "parallel" sets so that if one multi-sensor unit does fail, we loose spatial resolution, but still have enough information to work with.


message:
How do I write and read internal EEPROM?

I am working on an Arduino Mega 2560. I want to read and write the internal EEPROM.

Can I use `EEPROM.get()/EEPROM.put()`?

I want to store 3 things in EEPROM:

1. Boolean status.

2. String password: length 5 digits.

3. String Mobile number: length 10 digits.

body:
Avoid the 'String' object, use a character array of fixed length. You might want to add one extra byte for the zero-terminator. Put everything in a 'struct' and then you can use the EEPROM.get() and EEPROM.put() to read and write the complete struct. I prefer a struct to keep the data from EEPROM together. That makes it easier to add a checksum and a version number for the data. When something is wrong with the data from EEPROM then default values could be used.

Instead of a struct, you can also read and write the seperate items. The EEPROM.get() and EEPROM.put() should be able to use a character array of fixed length.


body:
> How do I write and read internal EEPROM? Can I use EEPROM.get()/EEPROM.put()?

Yes, the Arduino Reference for EEPROM contains an example of what you are asking for. Below is a simple rewrite of the example for [EEPROMGet][1] for your info.

    struct MyObject{
      bool status;
      char password[6];
      char mobileNumber[11];
    };

    void setup()
    {

      int eeAddress = 0; //EEPROM address to start reading from

      Serial.begin( 9600 );
      while (!Serial) ;

      MyObject customVar; //Variable to store custom object read from EEPROM.
      EEPROM.get(eeAddress, customVar);

      Serial.println(F("Read custom object from EEPROM: "));
      Serial.println(customVar.status);
      Serial.println(customVar.password);
      Serial.println(customVar.mobileNumber);
    }

For more details and examples see https://www.arduino.cc/en/Reference/EEPROM.

Cheers!

  [1]: https://www.arduino.cc/en/Reference/EEPROMGet


message:
What's the difference between analogWrite and digitalWrite?

As the title states. What's the difference between the two?

`analogWrite(pin,0-255)` vs `digitalWrite(pin,LOW-HIGH)`

body:
digitalWrite sets the pin to an high or low value that remains at exactly that value until digitalWrite is called for that pin again.

analogWrite sets the pin to have an oscillating value which has a pulse length based of the duty cycle specified as the second parameter.

So:

    digitalWrite (5, HIGH);    // Pin 5 goes high
    analogWrite (6, 127);      // Pin 6 oscillates regularly between 0v and 5v (or 3.3v) at about 250Hz.


body:
digitalWrite will set the specified pin to one of two states - HIGH/LOW, which equate to 5v (3.3v on some boards) and ground respectively.

analogWrite can vary by the type of output used.

If applied to a PWM pin - it will set the pin to a periodic high/low signal, where the percentage of the signal spent high is proportional to the value written.
for example  -

        analogWrite(PWMpin,255)
Will be HIGH 100% of the time, while

        analogWrite(PWMpin,127)
Will be HIGH 50% of the time, and LOW 50% of the time

When applying analogWrite to a DAC pin (available on some boards, like the DUE <s>or MEGA</s>)
analogWrite will actually cause the specified pin to output a voltage level proportinal to the specified analog value

For example, on the Due, with maximal voltage of 3.3v and a default analog resolution of 8 bits -[0:255]

        analogWrite(DACpin,255)

Will cause the specified pin to output 3.3v, and-

        analogWrite(DACpin,127)
Will cause the specified pin to output 1.35v


body:
`digitalWrite` sets the output pin to either LOW or HIGH (where those voltages depend on the Vcc of the processor. For a Uno or Mega that would be 0V or 5V (or close to it).

Here's a screenshot of digitalWrite (LOW):

[![digitalWrite (LOW)][1]][1]

That is, the output pin is at 0V.

---

Now for digitalWrite (HIGH):

The output voltage is 5V.

[![digitalWrite (HIGH)][2]][2]

---

`analogWrite` really should have been named PWMwrite since it configures the processor timers to output PWM (pulse-width modulation).

Let's try analogWrite(1):

[![analogWrite (1)][3]][3]

You can see that the voltage level is 0V most of the time, and going to 5V for short periods. You also see that the frequency is 490 Hz which is what [the reference page for analogWrite](https://www.arduino.cc/en/Reference/AnalogWrite) says it will be.

---

Zooming in:

[![analogWrite (1) - zoomed][4]][4]

The output is high for 8 µs, which is exactly 1/256 of 2048 µs which is the period of the timer. So, we have a duty cycle of 1/256 (0.39%).

---

Let's try analogWrite(127) - half-way from 0 to 255:

[![analogWrite (127)][5]][5]

Now you can see that the output is HIGH exactly half the time, and LOW the rest of the time.

---

Let's try analogWrite(254):

[![analogWrite (254)][6]][6]

This is the opposite of analogWrite (1). The output is HIGH all the time except for a brief period. Zooming in:

[![analogWrite (254) - zoomed][7]][7]

Now the output is *off* for 8 µs - compared to the earlier image where it was on for 8 µs.

---

`analogWrite (0)` is the same as `digitalWrite (LOW)`.

`analogWrite (255)` is the same as `digitalWrite (HIGH)`.

This is proven by the relevant code in wiring_analog.c:

 if (val == 0)
 {
  digitalWrite(pin, LOW);
 }
 else if (val == 255)
 {
  digitalWrite(pin, HIGH);
 }

---

## Summary

`analogWrite` basically configures the hardware timers to output PWM. Once you do that the timer hardware outputs the requested duty cycle (from 0 to 255) where 0 is always off, 255 is always on, and some value inbetween gives you PWM (pulsed output).

---

For more information about the timers see [my page about timers](http://www.gammon.com.au/timers).

  [1]: https://i.stack.imgur.com/WvNjn.png
  [2]: https://i.stack.imgur.com/uWGLD.png
  [3]: https://i.stack.imgur.com/Ey2ij.png
  [4]: https://i.stack.imgur.com/ORIjA.png
  [5]: https://i.stack.imgur.com/hOTYO.png
  [6]: https://i.stack.imgur.com/JV9mL.png
  [7]: https://i.stack.imgur.com/OyLu6.png


body:
**analogWrite():**
Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to `analogWrite()`, the pin will generate a steady square wave of the specified duty cycle until the next call to `analogWrite()` (or a call to `digitalRead()` or `digitalWrite()` on the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.

For details visit: https://www.arduino.cc/en/Reference/analogWrite

**analogRead():**
Reads the value from the specified analog pin. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega), 10-bit analog to digital converter. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023. This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit. The input range and resolution can be changed using `analogReference()`.

For details visit: https://www.arduino.cc/en/Reference/analogRead


body:
**analogWrite():** The analogWrite() method sets the value of a PWM output pin. The analogWrite() is on a scale of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on), and analogWrite(127) is a 50% duty cycle (on half the time).

[![PWM Duty Cycle][1]][1]

**Syntax**: analogWrite(pin, val)

Where,

pin: the PWM output pin number.

val: int value of duty cycle between from 0(always off) to 255(always on)

**Example Code:**

    int outLed = 10;  //LED connected to digital pin 10
    int value = 0;    //variable to store the read value
    int analogIN = 3; //input pin

    void setup()
    {
      pinMode(outLed, OUTPUT); // set the PWM pin as OUTPUT
    }

    void loop()
    {
      value = analogRead(analogIN); // read the value of analogIN (values between from 0 to 1023)
      analogWrite(outLed, value/4); // sets the read value on outLed (values between from 0 to 255)
    }

**digitalWrite:** The digitalWrite() method sets the value of a digital pin as HIGH or LOW. Here, 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

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

Where,

pin: the pin number

val: HIGH or LOW

**Example Code:**

    int ledPin = 13;                // LED connected to digital pin 13

    void setup()
    {
      pinMode(ledPin, OUTPUT);      // sets the digital pin as output
    }

    void loop()
    {
      digitalWrite(ledPin, HIGH);   // sets the LED on
      delay(1000);                  // waits for a second
      digitalWrite(ledPin, LOW);    // sets the LED off
      delay(1000);                  // waits for a second
    }

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


body: So what's the difference between analogWrite(X, 255) and digitalWrite(X, HIGH)? Probably nothing, except perhaps the processor has to do some extra stuff to work out that it doesn't need to use PWM, and also style.


body:
**digitalWrite** set the specified pin to one of two states - HIGH/LOW

Where, HIGH = 5 V and LOW = 0 V

**analogWrite** Set the PWM value of PWM pin

(In Arduino UNO, PWM pins are 3, 5, 6, 9, 10, 11)

It will set the pin to a periodic high/low signal.

    analogWrite(PWMpin,255)

Will be HIGH 100% of the time, while

    analogWrite(PWMpin,127)

Will be HIGH 50% of the time, and LOW 50% of the time


body: Another subtle difference between `analogWrite(pin, 255)` and `digitalWrite(pin, HIGH)` is that `digitalWrite` requires you to set the pin to output using `pinMode`. `analogWrite` sets the pin to output on each call, which makes it slower and might ruin the code which uses the same pin alternatively as input and output, and relies on the fact that writing to the input pin using `digitalWrite` doesn't switch it to output.


message:
Scheduled loops using same function

I am using an Arduino due and have multiple schedules running at the same time. I am using this [Library](https://github.com/arduino-libraries/Scheduler).

I have a function that 3 different loops use. Two of the loops are driven by user interaction so timing is not possible. The function does reset global variables and I would have no issue with the variables being reset multiple times as it wouldn't cause any problems for me.

What I was wondering, on the very slim chance that two loops called the function at the same time, is it possible for the loops to modify the same variable at identical times?

My understanding of the scheduler would lead me to believe that the scheduler will only yield to another loop after it has completed a line of code and thus the to instructions to reset the global variable could not happen at the very same time, just extremely quickly one after the other.

Would this be a correct assumption?

body:
From the [Arduino Reference][1] pages:
> This is a cooperative scheduler in that the CPU switches from one task
> to another. *The library includes methods for passing control between
> tasks.*

[emphasis mine]

Which means that your code decides when it yields control to another scheduled loop (by calling `yield()`. At a quick glance, it appears that it also yields by returning. So yes, your assumption is correct.


body:
It is a simple schedular. It only changes to another task when yield() is called. The delay() function uses yield() and a lot of code and libraries use delay().
That means that if you code does not contain a delay() then you need to call delay() or yield() now and then, or other tasks will never execute.
It is probably safe to use the same function, but every time a delay() is used, an other task could run or another task will continue from there.


message:
I would like to know the ATMEGA wiring to Arduino

[![ATMEGA328 pinout][1]][1]

I would like to know which pins are connected to the output of the Arduino.

For example:

- PC6 is digital 12
- PB5 is analog 13
- etc...

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

body:
Image searching for the term ["arduino uno pinout"](https://www.google.si/search?q=arduino+uno+pinout&tbm=isch) reveals a better pinout diagram.

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

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


body:
I think this is the diagram you are seeking.
[![enter image description here][1]][1]

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


body:
I prefer this image, as it combines the arduino pin numbers and PWM capabilities, with the names and functions from the datasheet.

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

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


body:
Or you could simply look at the [Arduino Uno schematic][1], which has everything you should ever need to know.

[![Uno schematic][2]][2]

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
  [2]: https://i.stack.imgur.com/1qrSc.png


body:
I usually preferred this image. It very useful for me every time.

[![Atmega Pin Mapping][1]][1]

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


message:
HC-SR04 and LCD Circuit Problem

I was designing a circuit that measure distance using HC-SR04 and display it into a LCD.This circuit also have 4 LEDs indicator.But i have a problem.The LEDs doesn't turn on.The LCDs backlight turn on, but it didnt display anything. Btw, i'm using LCD with I2C module.Here is the code:
[![The Schematic][1]][1]

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
    #define trigPin 6
    #define echoPin 7
    int led5cm = 8;
    int led7cm = 9;
    int led10cm = 10;
    int ledoor = 11; //ledoor means LED Out of Range
    void setup() { // put your setup code here, to run once: lcd.begin(16,2); lcd.setCursor(0,0);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(led5cm, OUTPUT);
      pinMode(led7cm, OUTPUT);
      pinMode(led10cm, OUTPUT);
    }
    void loop() {
      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration / 2) / 29.1;
      if (distance <= 5)
      { lcd.println("Distance < 5 CM");
        lcd.print("Distance = ");
        lcd.print(distance);
        lcd.print(" CM");
        digitalWrite(led5cm, HIGH);
        digitalWrite(led7cm, LOW);
        digitalWrite(led10cm, LOW);
        digitalWrite(ledoor, LOW);
        lcd.clear();
        delay(200);
      } else if (distance >= 5 || distance <= 7) {
        lcd.println("Distance < 7 CM");
        lcd.print("Distance = ");
        lcd.print(distance);
        lcd.print(" CM");
        digitalWrite(led5cm, LOW);
        digitalWrite(led7cm, HIGH);
        digitalWrite(led10cm, LOW);
        digitalWrite(ledoor, LOW);
        lcd.clear();
        delay(200);
      }
      else if (distance >= 7 || distance <= 10) {
        lcd.println("Distance < 10 CM");
        lcd.print("Distance = ");
        lcd.print(distance);
        lcd.print(" CM");
        digitalWrite(led5cm, LOW);
        digitalWrite(led7cm, LOW);
        digitalWrite(led10cm, HIGH);
        digitalWrite(ledoor, LOW);
        lcd.clear();
        delay(200);
      }
      else if (distance > 10) {
        lcd.println("Out of Range");
        lcd.print("Distance = ");
        lcd.print(distance);
        lcd.print(" CM");
        digitalWrite(led5cm, LOW);
        digitalWrite(led7cm, LOW);
        digitalWrite(led10cm, LOW);
        digitalWrite(ledoor, LOW);
        lcd.clear();
        delay(200);
      }
    }

Can you please help me solve this problem? Thank you very much!!

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

body:
To make your LCD work, add code like the following in `setup()`.  (Substitute appropriate values in place of `LCDcols` and `LCDrows`, or give them appropriate values via `const int ...` or `enum { ... };` statements.)

      lcd.begin(LCDcols, LCDrows);
      lcd.setBacklightPin(3,POSITIVE); // Might not need this, since info appears to be included in lcd declaration
      lcd.setBacklight(HIGH);
      lcd.clear();          // Clear the display
      lcd.home();

To make the LEDs work better, you may need to change the `||` connectives in some of the `if` statements to `&&`.  An `if` condition with terms joined by `||`, OR, is true if *any* of its terms are true; with terms joined by `&&`, AND, *all* of its terms must be true for the condition to be true.

For example, the condition `(distance >= 5 || distance <= 7)` is true if distance is 5 or more, or 7 or less; in other words, is always true.


message:
Custom DAC for Arduino UNO

I am currently following [this][1] tutorial on building a Simple Audio Player for the Arduino. I was about to finish the circuit only to realize that the required board is an Arduino Due and I have the Uno.

Because the Uno does not have its own DAC port, I was wondering what other options are available for me to accomplish the same thing while keeping the circuit as similar to the one listed in the tutorial.

Thanks

  [1]: https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer

body:
You can probably use the same circuit and the PWM "Analog" output of the Duo (after adding a low pass filter) to play simple tones, and maybe do something on the input side to allow you to change the frequency in response to some user input.

I don't think you'll get the Duo to read from the SD Card and play the audio simultaneously.


body:
There are three basic ways of creating a DAC.

The simplest, though roughest, is to use PWM, then low-pass filter it.  Not perfect, but rough and ready. Only needs a resistor and a capacitor.

The highest quality way, though slowest for interfacing, is to use an external DAC chip. Fine for low frequency response reproduction, and the linearity is second to none. The MCP4821/2 is a popular choice (SPI connected).

The third option is to build your own DAC using an R-2R ladder. You can make an 8-bit DAC with very fast response by using all 8 pins of a single IO port (such as pins 0-7 on the Uno are bits 0-7 of port D). However the linearity of an R-2R ladder very much depends on how well matched your resistors are.

The R-2R ladder should be buffered with an amplifier of some form before driving a low impedance device like a speaker.

None of them are really great for audio work - for that you need a chip with much more processing power and memory, and a high speed digital audio interface, such as I2S, to interface a proper audio CODEC chip. Personally I use PIC32MZ chips for audio work.


body:
The major problem you have is that the Audio library functions are specifically written for the ARM based Due.
You could certainly add an I2C 10 bit (Mono or Stereo) DAC chip to an Arduino Uno capable of producing stereo signals through an LM386, but you would have to re-write the Audio library to support that functionality on the Uno.


message:
Arduino Control TV over RS232

I have a LG TV(LG 32SL800 ZB), which has a RS232-Port for Control and Service.

And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one [RS232 Board][1]?

How could I then control the TV? This is the [Manual][2] for the TV at page 124 there are the commands how to control it, but how can I send them?

My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?

  [1]: http://www.waveshare.com/rs232-board.htm
  [2]: https://drive.google.com/uc?export=download&id=0B_ayS6QBJX3VR2V1X1VxRlloZm8

body:
> And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one?

Yes, you can, though choose a board based around the MAX3232 for a 3.3V MCU board.

> How could I then control the TV? This is the Manuel for the TV at page 124 there are the commands how to control it, but how can I send them?

Exactly as they show in the manual. For example:

    Serial.print("ka 0 01\r");

That would turn on every TV connected to the serial bus.

> My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?

You can get away with no more than maybe 1 meter between the Arduino and the RS232 board. Keep that as short as possible. However between the RS232 board and the TV you can have up to 15 meters of cable.


message:
Global memory reduction when using SPI/SD

I want to use an SD card and when including the library both SPI.h and SD.h are included. Also later I want to use an external SRAM chip (probably using SPI.h as well). However, without the SRAM chip my sketch uses around 849 bytes of global memory, where I expect most of it taken by the SD.h / SPI.h combination. Without these includes only 9 bytes are used.

How can I reduce the amount of global memory (still I want to use the SD and SPI interface)?

Edit:

According to a remark below 512 bytes are used for the SD so that explains mostly of the 849 bytes. And some additional questions:

Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes ...I only need to read a file (128 KB) and copy it to an SRAM (external). And I don't mind if it will be transferred in 16 byte blocks. Actually, I could get rid of the buffer at all after the SD to SRAM copy.

My ultimate goal is to leave 1KB + some dynamic memory (for function call stacks/local variables). However, finally I need to move to the Arduina Mega anyway, but was hoping I could already start the project with my Arduino Uno.

body:
> Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes

The Arduino SD library uses an internal file block caching (512 bytes) to improve performance. It is possible to read directly from a file block on the SD but that would be very slow. Every 16 bytes read would require reading from file block, discharging all preceding bytes (as the file block is read serially), reading the 16 bytes, and then stopping the block read.

There are a few tiny SD libraries that actually use this technique. See for instance Petit FAT File System http://elm-chan.org/fsw/ff/00index_p.html

Another technique is to block copy from the SD directly to the external SRAM without going through additional buffers. This requires a refactoring of the SD library so that it uses a callback instead of the internal buffer.

Cheers!


message:
Time delay without using delay() and millis()

I am designing an industrial control panel using arduino. I have to use time delays as long as 10 seconds and since using delay() makes a halt in the controller I tried using millis(). But it is complicated and it will work only for 50 days. I want the system to work continuously without any maintenance and I need to control as many as 6 relays. So, I need a better solution (hardware or software based) to tackle this problem. How can I do this?

body:
You may have to find a library that eases the use of what you're trying to do.
I made some timer library, called **SeqTimer**.
You can find it here: [Link](https://github.com/SMFSW/SeqTimer)
or use the Arduino library manager, it's there too.

It's a simple library using millis(), without callback, so it's pretty straightforward.
If you need more advanced timer, search for 'timer' for example in the arduino library manager, there's a bunch of libs related to timers.

Yet, I'm not really sure what you mean by:
 > work only for 50 days


body:
>  it will work only for 50 days.

it overflows in 50 days but comparisons based on it can be good even if it overflows. you just need to recognize the overflow and program accordingly.

so millis() is perfectly fine for what you are trying to do. no need to reinvent the wheels.


body: You misunderstand the 50 day thing. Yes it rolls over after 50 days but that doesn't mean it stops working. As long as you program your comparisons correctly (something people often don't do in online examples) then all it means is the *maximum delay* you can have is 50 days.


message:
Pin identification for a salvaged LCD

I salvaged an SPI interface LCD from an old CDMA telephone. It seems it uses SPI to display something on the screen. The pins marks are DATA, CS, SCLK, BL, VDD, GND, LED, A0, and RES. How do I wire it up to an Arduino?

body:
They seem pretty self-explanatory. Data, sclk and cs are normal SPI MOSI, CLK and CS. A0 is probably equivalent to C/D. RES is reset - tie high to run. Power and ground are obvious. The others look related to the back light.

However... How are you going to operate it? Do you know the SPI instructions to send? They will be specific to the display, so without a datasheet you're pretty much stuffed.


message:
Liquid level sensor

We're currently working on a direct sketch to printed circuit board printer for our design project. We need a sensor for the ink level since we're using a pen. Can we use this ( https://www.dfrobot.com/wiki/index.php/Non-contact_Liquid_Level_Sensor_XKC-Y25-T12V_SKU:_SEN0204) as a sensor even if its non-conductive type ink (normal ink we use for writing)? Thanks for the response!

body:
Your link page says:

>There are no special requirements for the liquid

So, I would not concern about the conductivity of the liquid.


message:
SD card in Arduino

Im connecting an SD card module to arduino pro with 3.3v , the card is getting initialized , but im getting an error message that FAT 32 partition is not available , but it is already in FAT 32 format , is this an voltage issue ? should i connect it to a 5v line? Ive tried it two libraries SD and sdfat libraries , im getting same results, im using 8gb memory card

body:
A SD card is 3.3V.
Have you read this: [Arduino.cc forum about SD Formatter][1] ?
Perhaps it is a cheap module with bad contacts.
Perhaps your 8GB card is not compatible. Do you have another memory card ? Preferably older and less memory.
Perhaps you use long wires, or a breadboard with bad contacts.

In most cases it should work without problem. When the initialization is okay then the wiring is probably okay. Therefor I suspect that the card itself or the partition on it, is not compatible.

  [1]: https://forum.arduino.cc/index.php?topic=228201.0


message:
Laser emitter + receiver for Arduino (Arduino to Arduino communication)

I'm working on a project using 2 Arduinos connected to 2 computers to demo Serial to Serial communication.

We're using Arduino Uno connected to the computer via Serial and software serial for inter-Arduino communication. We used wires to connect software serial RX & TX lines, but we'd like to connect these pins to a laser transmitter and receiver.

We're trying to show wireless communication using an optical medium, which is why we wanted to use a Laser transmitter and receiver.

We're trying something like the setup in this YouTube video [$3 laser transmits audio over 100m (Arduino)](https://www.youtube.com/watch?v=MCTqC2-AN7o)

Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?

Receiver: [Laser Sensor Module non-modulator Tube Laser Receiver](http://www.ebay.com/itm/Laser-Sensor-Module-non-modulator-Tube-Laser-Receiver-New-Module-/401160430957)

Transmitter: [5V ... Board For Arduino AVR ... KY-008 Laser Transmitter](http://www.ebay.com/itm/5Pcs-5V-Sensor-Module-Board-For-Arduino-AVR-PIC-KY-008-Laser-Transmitter/282387608849?_trksid=p2047675.c100005.m1851&_trkparms=aid=2220072&algo=SIC.MBE&ao=2&asc=20131003132420&meid=2408f91403264ad2926b2048bf0c53c3&pid=100005&rk=1&rkt=6&sd=401160430957)

  [3]: https://www.youtube.com/watch?v=MCTqC2-AN7o

body:
> Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?

Looks like the receiver module has a [low-pass filter][1]. That could reduce the baud-rate depending on the RC-factor (10 Kohm * 10 nF gives a cut-off frequency of [1.6 kHz][2]). I would recommend checking the actual components. The above is a guesstimate.

Cheers!

  [1]: https://en.wikipedia.org/wiki/Low-pass_filter
  [2]: http://www.learningaboutelectronics.com/Articles/Low-pass-filter-calculator.php#answer1


message:
Controlling amplifier using remote control jack

Many older amplifiers support wired remote control through connector jacks or ports. My 10-year old Marantz also supports this function, using [a simple RCA connector][1].

Originally these were used with [external IR receivers][2] when the unit was not kept in plain sight.

I wonder if there is a way to control the amplifier using an Arduino, which probably means by generating the required signal over the connector instead of receiving it from an IR receiver. Any pointer to a similar project is appreciated as well.

  [1]: http://manuals.marantz.com/NA8005/NA/EN/DNTXSYlyopmtcn.php
  [2]: https://www.wehkamp.nl/Winkelen/KenmerkAdviseurArtikel.aspx?CC=C26&SC=6F1&KAC=F17&artikelNummer=582788&MaatCode=0000&BC=GOA&BAC=ALG&cm_mmc_o=7BBTkwCjC-kTwFwwECVyBpAgfkblfbETzplCjC-ggwllBbywCaeCCjCoxDonIoo&utm_source=google&utm_medium=cpc&scid=scplp865827880000&sc_intid=865827880000&cm_mmca1=12913-AGI-23705142542-ASI-168204110942-865827880000&gclid=CM_xnPTb3dICFUkQ0wodeoAHGg&gclsrc=aw.ds&dclid=COrKpfTb3dICFdGWdwodqCgDSA

body:
According to this thread on [remotecentral][1] the signal on the RCA connector is just the inverted signal that the IR-LED receives. So if you load an RC5 library and invert the output (0=1 and 1=0), you should be able to send codes to that connector with an arduino. Or even better, use an ESP8266 and control it over wifi ;)<BR>
The RC5 codes and their functions are in this  [nice excel sheet][2] or use [this information][3] if you want to send raw hex

  [1]: http://www.remotecentral.com/cgi-bin/mboard/rc-theater/thread.cgi?4877
  [2]: http://m.us.marantz.com/DocumentMaster/US/Marantz 2014 IR Command Sheet.xls
  [3]: http://www.remotecentral.com/cgi-bin/codes/marantz/


message:
Arduino eeprom_put sketch writes data in two locations?

Using precisely this code - the ***eeprom_put*** example in the Arduino IDE, and am seeing some strange results...

The sketch does write correctly to eeAddress = 0, and the corresponding ***eeprom_get*** sketch does return the data.

Please note that I've initialized the entire EEPROM with 'FF's before any test...

The weird part is this sketch writes exactly the same data starting at Address = 2048. The loop is not running; I see no jump to offset 2048... I gotta be missing something!

I'm dumping EEPROM using avrdude, and viewing results in an external hex editor.

How is this stuff stored? Apart from not being able to directly view a float - OK, I get it - should the other data be simply *viewable* in hex?

My own experiments in writing hex bytes directly also work, but also write in two locations.

Small update to this: Precisely the same behavior seen with a RobotDyn Mega. Both the 'clone' Mega and the RobotDyn report: Device signature = 0x1e9801 (probably m2560)

    #include <EEPROM.h>

    struct MyObject {
      float field1;
      byte field2;
      char name[10];
    };

    void setup() {

      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      float f = 123.456f;  //Variable to store in EEPROM.
      int eeAddress = 0;   //Location we want the data to be put.

      //One simple call, with the address first and the object second.
      EEPROM.put(eeAddress, f);

      Serial.println("Written float data type!");

      /** Put is designed for use with custom structures also. **/

      //Data to store.
      MyObject customVar = {
        3.14f,
        65,
        "Working!"
      };

      eeAddress += sizeof(float); //Move address to the next byte after float 'f'.

      EEPROM.put(eeAddress, customVar);
      Serial.print("Written custom data type! \n\nView the example sketch eeprom_get to see how you can retrieve the values!");
    }

    void loop() {
      /* Empty loop */
    }

body:
What is probably happening is [aliasing][1].  Let's say your processor has a 16 bit address bus.  16 bits can count up to 2^16 = 65536 = 64k memory addresses.  Each address is a byte (B) so your processor has 64k-Bytes of address space.  It can physically address 64kB of memory.

What happens if you only have one memory chip with 4KBytes of memory, with  only 12 address lines?  Well, if the designer was lazy (or cost-conscious), the first 12 address lines on the processor will be connected to the 12 lines on the memory chip.  The other 4 lines on the processor will be ignored.

So it doesn't matter what the processor does with address lines 13-16 -- they're not connected to the memory chip.  Therefore the contents of the memory chip appears where you expect, starting at address `0`, but also again at address 4096, and again at address 8192 and so on.

  [1]: https://en.wikipedia.org/wiki/Aliasing_(computing)


message:
code optimazation 6x6 Matrix

I planed a 6x6 matrix with a Arduino Nano as controller.
Its only possible to let one LED in the matrix lighten up.
Any idea how I get the Code smaller? (Im a C Noobie ^^)

*~Nico*

Circuit diagram:
[![enter image description here][1]][1]

Code:

>     void setup() {
>       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() {
>       int value1 = digitalRead(14);
>       int value2 = digitalRead(15);
>       int value3 = digitalRead(16);
>       int test = digitalRead(17);
>       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;
>
>
>       // put your main code here, to run repeatedly:
>
>
>       if (test == HIGH) {
>         digitalWrite(x1, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x1, LOW);
>         digitalWrite(x2, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x2, LOW);
>         digitalWrite(x3, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x3, LOW);
>         digitalWrite(x4, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x4, LOW);
>         digitalWrite(x5, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x5, LOW);
>         digitalWrite(x6, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x6, LOW);
>
>
>
>       }
>     }

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

body:
You can use arrays to hold sets of row pin numbers or column pin numbers, which then allows use of `for` loops for `pinMode()` settings and for testing LEDs one after another, as shown in code below.

Note, using `enum { ... };` for integer-constant declarations is slightly more compact than a series of `const int` statements.  When a constant name in an `enum` does not have an `=` and value after it, it is given a value one larger than the previous constant.  So, for example, the first `enum` in the following code sets `x2` to 3, `x3` to 4, etc.

    enum { x1=2, x2, x3, x4, x5, x6};
    enum { y1=8, y2, y3, y4, y5, y6};
    const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
    const byte colPins[] = { y1, y2, y3, y4, y5, y6};
    enum { nRow = sizeof rowPins / sizeof rowPins[0] };
    enum { nCol = sizeof colPins / sizeof colPins[0] };

    void setup() {
      for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
      for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
      for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
    }

    void loop() {
      byte test = digitalRead(17);
      if (test) {
        for (byte x=0; x<nRow; ++x) {
          digitalWrite(rowPins[x], HIGH);
          for (byte y=0; y<nCol; ++y) {
            digitalWrite(colPins[y], HIGH);
            delay(15);
            digitalWrite(colPins[y], LOW);
          }
          digitalWrite(rowPins[x], LOW);
        }
      }
    }

Note, subroutines and functions can be used to modularize code and (typically) reduce its volume.  See code sample below.  In the code as is, the subroutine doesn't particularly reduce volume, but definitely adds modularity.  You may find it useful to look up *refactoring*.

    enum { x1=2, x2, x3, x4, x5, x6};
    enum { y1=8, y2, y3, y4, y5, y6};
    const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
    const byte colPins[] = { y1, y2, y3, y4, y5, y6};
    enum { nRow = sizeof rowPins / sizeof rowPins[0] };
    enum { nCol = sizeof colPins / sizeof colPins[0] };

    void setup() {
      for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
      for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
      for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
    }

    void lightup(byte x, byte y, unsigned int howLong) {
      digitalWrite(rowPins[x], HIGH);
      digitalWrite(colPins[y], HIGH);
      delay(howLong);
      digitalWrite(colPins[y], LOW);
      digitalWrite(rowPins[x], LOW);
    }

    void loop() {
      byte test = digitalRead(17);
      if (test) {
        for (byte x=0; x<nRow; ++x)
          for (byte y=0; y<nCol; ++y)
            lightup(x, y, 15);
      }
    }


body:
> Any idea how I get the Code smaller?

don't try to get the code smaller -> try to get it working.

for things like this, you should think about

1) how to structure the display data: typically it is done in a matrix format. I would structure it as an array of 6 chars / columns, with the rows in the lowest 6 bits;

2) how to track the column being displayed and updated: using a static variable typically;

3) how to update the display periodically: via a timer interrupt usually.

Each update would go something like this:

      turn off all columns;
      present row information;
      update the column index and turn it on;

what's left is to implement that in a way that the code is flexible and portable to a different application.

once that's done, all your application needs to do is to stuff the right information into the display buffer and the display routine, invoked via a timer isr, will take care of the updating all by itself, without user involvement.

if you still need help, let us know.

edit: i put this together quickly to demonstrate the concept.

it is a display routine, led_display(), being invoked via a timer2 interrupt, displaying data in an 8-char buffer, 0x11, 0x22, ..., 0x88.

the scanning is done by colomn (active high), and the rows are connected to D0..D7, and the cols D8..D13, A0, A1, all user configurable.

    //global variables
    uint8_t lRAM[COL_NUM]={   //display buffer
     0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88
    };

    const uint8_t row_pins[ROW_NUM]={ //pins tied to matrix' rows
     0, 1, 2, 3, 4, 5, 6, 7,
    };

    const uint8_t col_pins[COL_NUM]={ //pins tied to columns
     8, 9, 10, 11, 12, 13, A0, A1,
    };

once the initialial set-up is done, there is nothing the user needs to do, other than filling the display buffer with information s/he wishes to be displayed.

    void setup() {
       // put your setup code here, to run once:
       //pinMode(led, OUTPUT);
       led_init();       //reset the led module

       //set up timer2
       tmr2_init(TMR2PS_32x);    //timer2 with 32:1 prescaler -> 16Mhz / 256 / 32 = 2Khz per col.
       tmr2_act(led_display);    //install user handler to update the display periodically
    }

    void loop() {
       // put your main code here, to run repeatedly:
        //digitalWrite(led, HIGH);  // turn the LED on (HIGH is the voltage level)
        //delay(100);               // wait for a second
        //digitalWrite(led, LOW);   // turn the LED off by making the voltage LOW
        //delay(100);               // wait for a second
    }

and here is the execution.[![enter image description here][1]][1]

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

ps: the code was originally written to drive 8x7-segment displays but it works with 8x8 matrix as well -> they are essentially the same thing.

the display routine, led_display(), follows the general sketch laid out earlier.

    //update the display
    void led_display(void) {
     static uint8_t col_index=0;   //current col
     //turn off current col -> the only active col now
     COL_OFF(col_pins[col_index]);

     //update the column index
     col_index=(col_index==COL_NUM-1)?0:(col_index+1);

     //present row data
     if (lRAM[col_index] & (1<<0)) ROW_ON(row_pins[0]); else ROW_OFF(row_pins[0]);
     if (lRAM[col_index] & (1<<1)) ROW_ON(row_pins[1]); else ROW_OFF(row_pins[1]);
     if (lRAM[col_index] & (1<<2)) ROW_ON(row_pins[2]); else ROW_OFF(row_pins[2]);
     if (lRAM[col_index] & (1<<3)) ROW_ON(row_pins[3]); else ROW_OFF(row_pins[3]);
     if (lRAM[col_index] & (1<<4)) ROW_ON(row_pins[4]); else ROW_OFF(row_pins[4]);
     if (lRAM[col_index] & (1<<5)) ROW_ON(row_pins[5]); else ROW_OFF(row_pins[5]);
     if (lRAM[col_index] & (1<<6)) ROW_ON(row_pins[6]); else ROW_OFF(row_pins[6]);
     if (lRAM[col_index] & (1<<7)) ROW_ON(row_pins[7]); else ROW_OFF(row_pins[7]);

     //turn on the display
     COL_ON(col_pins[col_index]);
    }


message:
Can't include files

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

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.


message:
How do I power an arduino without USB?

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?

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.


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

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?

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


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

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;
      }
    }

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?


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

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?

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.


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

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);
    }

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


message:
Local variable usage in SRAM not counted

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?

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!


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

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!

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!


message:
Arduino analog pins

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?

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;

...


message:
Arduino Nano TX LED is on

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

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.


message:
wiring a arduino led project

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?

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


message:
Arduino IDE COM Port error on Windows 10

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

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.


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

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

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!


message:
Linking Arduino and Matlab

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?

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/