title: GPS is not detected on SIM808 module!

text:
# Question
Title: GPS is not detected on SIM808 module!
I'm trying to get GPS coordinates using my SIM808 module by connecting it with Arduino. When I use this code,

```
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "gps.h"

//To change pins for Software Serial, use the two lines in GSM.cpp.

//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.

//Simple sketch to start a connection as client.

GPSGSM gps;

char lon[15];
char lat[15];
char alt[15];
char time[20];
char vel[15];
char msg1[5];
char msg2[5];

char stat;
char inSerial[20];
int i = 0;
boolean started = false;

void setup() {
  //Serial connection.
  Serial.begin(9600);
  Serial.println("GSM Shield testing.");
  //Start configuration of shield with baudrate.
  //For http uses it is recommended to use 4800 or slower.
  if (gsm.begin(2400)) {
    Serial.println("\nstatus=READY");
    gsm.forceON(); //To ensure that SIM908 is not only in charge mode
    started = true;
  } else Serial.println("\nstatus=IDLE");
  if (started) {
    //GPS attach
    if (gps.attachGPS())
      Serial.println("status=GPSREADY");
    else Serial.println("status=ERROR");
    delay(20000); //Time for fixing
    stat = gps.getStat();
    if (stat == 1)
      Serial.println("NOT FIXED");
    else if (stat == 0)
      Serial.println("GPS OFF");
    else if (stat == 2)
      Serial.println("2D FIXED");
    else if (stat == 3)
      Serial.println("3D FIXED");
    delay(5000);
    //Get data from GPS
    gps.getPar(lon, lat, alt, time, vel);
    Serial.println(lon);
    Serial.println(lat);
    Serial.println(alt);
    Serial.println(time);
    Serial.println(vel);
  }
};

void loop() {
  //Read for new byte on serial hardware, and write them on NewSoftSerial.
  serialhwread();
  //Read for new byte on NewSoftSerial.
  serialswread();
};

void serialhwread() {
  i = 0;
  if (Serial.available() > 0) {
    while (Serial.available() > 0) {
      inSerial[i] = (Serial.read());
      delay(10);
      i++;
    }
    inSerial[i] = '\0';
    if (!strcmp(inSerial, "/END")) {
      Serial.println("_");
      inSerial[0] = 0x1a;
      inSerial[1] = '\0';
      gsm.SimpleWriteln(inSerial);
    }
    //Send a saved AT command using serial port.
    if (!strcmp(inSerial, "TEST")) {
      stat = gps.getStat();
      if (stat == 1)
        Serial.println("NOT FIXED");
      else if (stat == 0)
        Serial.println("GPS OFF");
      else if (stat == 2)
        Serial.println("2D FIXED");
      else if (stat == 3)
        Serial.println("3D FIXED");
    }
    //Read last message saved.
    if (!strcmp(inSerial, "MSG")) {
      Serial.println(msg1);
    } else {
      Serial.println(inSerial);
      gsm.SimpleWriteln(inSerial);
    }
    inSerial[0] = '\0';
  }
}

void serialswread() {
  gsm.SimpleRead();
}

```

After some time, I get this error on the Serial Monitor of Arduino:

```
status=ERROR

```

The connections are as follows:

* TX of Module = Pin 2 of Arduino
* RX of Module = Pin 3 of Arduino
* GND of Module = GND of Arduino
* 5V of Module = 5V of Arduino

The Arduino is powered by USB connected to my PC.

# Answer
> 1 votes
Your problem looks similar to mine. It is possible that your module is a GNSS module and therefore doesn't work with standard AT commands, which are used in "gps.h".

First check that the GPS Module receives enough current, at least 5V -- 2A from an external source like a battery.

Then try sending AT commands in the serial monitor to check if your GPS module works properly:

```
#include <SoftwareSerial.h>
SoftwareSerial SIM808(2,3); //(RX-Pin,TX-Pin)

void setup() {
  Serial.begin(19200);
  SIM808.begin(19200);
}

void loop() {
  if (SIM808.available())
    Serial.write(SIM808.read());
  if (Serial.available())
    SIM808.write(Serial.read());
}

```

Upload this to the board an then open the serial monitor and send these commands:

```
AT+CGNSPWR=1

```

This should return OK.

After that input:

```
 AT+CGNSINF

```

This should return OK and your GPS Location in this format:

```
1,0,<time>,<your latitude>,<your longitude>,..........

```

If you get the following output:

```
1,0,19800106001337.000,,,,0.00,0.0,0,,,,,,0,0,,,,,

```

It means your GPS is not set. Try to put GPS antenna outside your room, on open space.

For more information about GNSS modules go to http://www.elecrow.com/wiki/images/0/05/SIM800\_Series\_GNSS\_Application\_Note\_V1.00.pdf

---
Tags: arduino-uno, gps
---


title: Battery Status notifier

text:
# Question
Title: Battery Status notifier
I am new to Arduino, and I am aware that unlike Raspberry Pi you do not have a full blown OS with many custom applications running concurrently. I plan to start an Arduino project with an Arduino NANO that will need to be portable, and include batteries. How may I get the battery status information without disrupting the rest of the functionality?

# Answer
Use analogRead to measure the voltage on the battery. You might have to use the internal 1.1V reference to get a good reading.

Don't write any blocking code and the processes won't interfere with each other. That means no long for or while loops waiting for something to complete and absolutely no delay.
> 2 votes

---
Tags: arduino-nano, battery
---


title: Don't Print After decimal point in

text:
# Question
Title: Don't Print After decimal point in
In my code, I have `float Hz = 0.00;` I want to display values to my user in RPM as

```
Serial.print("Speed = ");
Serial.print(round(Hz*60);
Serial.println(" RPM);

```

The only hangup is that this displays as `Speed = XX.00 RPM` is there an easy way to get the Arduino to only print out `Speed = XX RPM`?

# Answer
From the documentation:

```
Serial.print(round(Hz*60), 0);

```
> 2 votes

---
Tags: serial, arduino-mega, c++, display
---


# Question
Title: Marlin Firmware troubles: <time.h> error
I am trying to upload the Marlin Firmware to my 3D printer's Arduino Mega 2560 and I am experiencing a problem. It keeps saying:

```
qr_solve.cpp:7:18: fatal error: time.h: No such file or directory
 #include <time.h>
                  ^
compilation terminated.
Error compiling.

```

Please help as I'm lost as how to fix it, because I try to scroll up to see what is highlighted in red and I can't find anything.

# Answer
> 1 votes
From Gerben's link to the googlegroups's thread, Delta robot 3D printers › compiling jcrocholl's Marlin (Ubuntu), as Francis Mallet points out, at the bottom of the thread, it is necessary to change `<time.h>` to `"Time.h"`:

> I copied the content of the Time library right in the Marlin folder, then changed line 7 of qr\_solve.cpp from #include to #include "Time.h"
>
> The code compiled and everything seems to be working ok.

So, to iterate, the line in `qr_solve.cpp`:

```
#include <time.h>

```

becomes

```
#include "Time.h"

```

Now, `Marlin.ino` should compile as expected.

Note that the latest version of Marlin, from github.com/MarlinFirmware/Marlin no longer suffers from this issue, but older versions of the software, such as github.com/gpfwestie/kossel\_2020\_sintron will do, due to line 7, in `qr_solve.cpp`.

# Answer
> -1 votes
interestingly changing to Time.h didn't work for me (arduino sdk 1.6.9) however commenting out the include line did...

---
Tags: arduino-mega, firmware
---


# Question
Title: Reducing lag between the arduino and a processing sketch on my computer
I'm currently on project #14 of the Arduino project book.

I'm trying to control a processing sketch on my laptop using my Arduino. This is accomplished by using a potentiometer to control the background of an image.

Arduino code:

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

void loop(){
  Serial.write(analogRead(A0)/4);
}

```

Processing:

```
//imports serial library
import processing.serial.*;
//setups the serial object
Serial myPort;
//creates an object for the image
PImage logo;
//variable to store background color
int bgcolor = 0;

void setup(){
  colorMode(HSB,255);
  logo = loadImage("http://arduino.cc/logo.png");
  size(logo.width,logo.height);
  println("Available serial ports");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
}
//equivalent of arduino's loop function
void draw(){
  if(myPort.available() > 0)
  {
    bgcolor = myPort.read();
    println(bgcolor);
  }

  background(bgcolor,255,255);
  image(logo,0,0);
}

```

Now, while the code works, and the background color changes as i turn the potentiometer, there is a **huge** lag between turning the potentiometer and seeing the background change color, and the values from the Arduino/potentiometer change on the processing's serial monitor.

What I've tried:

* Changing the speed of Serial communication

I've noticed that when I decrease the speed of Serial communication, e.g. around 100, the delay between turning the potentiometer and seeing it change on my laptop decreases to about 1 second. However, when I decrease the speed of Serial communication even further, e.g. a value of 1, the delay increases again.

On the flip side, at the standard speed of 9600, the delay is huge, roughly 5sec ++ before the changes in the potentiometer show up on the laptop/processing.

Why does decreasing the communication speed (up to a certain point) decrease the time lag, and increasing it increase the time lag? Also, is there anyway I can make it near instantaneous?

# Answer
You're outputting a reading every time round the Arduino `loop()`, so it seems likely that your Processing program isn't running fast enough to keep up with it. Try putting a delay into the `loop()` in your Arduino code to slow it down, e.g.:

```
void loop(){
    Serial.write(analogRead(A0)/4);
    delay(50);
}

```

As far as I know, Processing aims to run at a consistent framerate, which you can modify using the `frameRate()` function. By default, it's 60 frames per second, although it may run slower on older systems (or where you're running an intensive program). You can check how fast it's running by reading the `frameRate` variable.

Introducing a 50 millisecond delay into the Arduino loop means it will be updating a little under 20 times per second. That means it should be fast enough for user interface purposes, but should also be well within the capabilities of your Processing program.

As far as the baud rate (communication speed) is concerned, adjusting it by arbitrary amounts is likely to have unpredictable results. That's because the hardware will only support specific speeds, and trying to use anything else can result in the data appearing garbled on the other end. The `Serial.begin()` documentation has some more information about supported baud rates.
> 11 votes

# Answer
As already pointed out, your Arduino is saying too much too fast. Adding `delay()` will slow it down, but still it keeps yelling at Processing. Ideally, you want Processing to ask for the value when it's convenient, and then receive one answer from your Arduino.

Enter `SerialEvent()`.

As opposed to `loop()` on your Arduino and `draw()` in Processing, everything inside `serialEvent()` only excutes when there is something new in the serial buffer. So instead of Processing asking questions as fast as possible and your Arduino yelling back even faster, they can have a nice, polite (asynchronous) conversation.

Both Processing and Arduino have a serialEvent. This is serialEvent() on the Arduino and this is serialEvent() in Processing. Using serialEvent on both sides, this is what would happen:

1. Processing sends a character to the serial connection. This could be any character, but if we predetermine one we can filter out any unwanted requests caused by e.g. a noisy signal. For this example, let's send a `V` every time we want a new reading of your potmeter. After the character is sent, we continue our business as usual. Not waiting around for an answer here!
2. On the Arduino side nothing is happening, until it receives data in the serial buffer. It checks whether the incoming character is a `V`, and lucky us, it is. The Arduino reads the potmeter's value once, outputs that value to serial once, and goes back to chilling out, maxing relaxing all cool. Protip: terminate the value with a character (`*` in our case). This will help you in the next step.
3. Processing is doing its regular interfacey pixel business when all of a sudden there's a disturbance in the force new data in the serial buffer. It switches to `serialEvent()`, and starts reading the serial data, until our terminating `*` is encountered. Knowing for sure this was the last character worth reading, we can now store the incoming value in a variable that stores the Arduino's reading.
4. That's it. Processing now knows the new sensor value and carries on with whatever we tell it to do. Meanwhile, your Arduino is enjoying the weather or contemplating its existence until there is incoming serial data.
> 14 votes

# Answer
Your polling loop runs at full speed of your processor, and writes to the serial port in each round.

This way, you're writing way more often to the serial port than it can handle.

The port writes out data as fast as you configured it, and **buffer data** that is comming in from your program **too fast**, to write it out as soon as possible. It the buffer is full, it just drops new data.

What's important here is that it will keep the order of the values: It is a **FIFO buffer**, working in First In/First Out order.

What happens is:
**The loop fills the port buffer, and keeps it 100% full.**
If you turn the potentiometer, the changed value **get's written to the end of the buffer**, the port works as fast as it can to write out all elements in the buffer, that have still the old value.

And finally the value you are interested in. The most current value we wanted to see immediately was at the end of the FIFO, and first in/ first out also means last in/last out. The opposite of what we want.

The maximum frequency it makes sense to read your data, is the frequency you can write it out, so you should use at least a delay that is long enough to write out the bytes at the current port speed.

---

As another, independent measure to prevent this kind of delay in general,
you could additionally set the write buffer of the port to a minimum.

That would cause data to be dropped much earlier, instead of buffering a lot first.

Of course, in many applications that is not what you need; With bad luck, it could work anyway in the beginning, and get unstable in some situations when the timing changes based on things like processor load, and there are only **some random data samples** that get dropped. A large buffer generally behaves much more deterministic, so do **use a large buffer by default**.
> 7 votes

# Answer
Instead of constantly sending serial data, only send data when the value of the potentiometer has changed over a certain threshold.

```
int oldValue = 0;
const int threshold = 5;

void setup()
{
  Serial.begin(9600);
  pinMode(A0, INPUT)
}

void loop()
{
  if(oldValue >= analogRead(A0)+threshold || oldValue <= analogRead(A0)-threshold)
  {
    Serial.println(analogRead(A0));
    oldValue = analogRead(A0);
  }
}

```
> 6 votes

# Answer
Two simple solutions that are guaranteed to work for anyone who is still looking:-

1. Increase the delay to 50 to 100 milliseconds.
2. Add this after the `Serial.begin(9600)` in `setup()`;

```
Serial.setTimeout(50);

```

Step two is the most important. It worked for me only after I added the above code. This is not mentioned very often in many other forums that I have looked when I had the exact same problem.
> 0 votes

---
Tags: arduino-uno, programming, serial
---


# Question
Title: Nick Gammon "Camera shutter speed timer"
I am reading the period of pulses from a 600ppturn shaft encoder, using the FreqPeriod library, by Martin Nawrath.

This works using counter1 and the comparator on pin6 and pin7 on the Arduino Uno.

The period duration for 1-2500Hz is being used in a midi musical instrument to give a speed to volume and a note change at a fixed speed. This has worked well on the Uno but now I want to use a Mega (which does not have both comparator pins).

So I have tried using the Nick Gammon interrupt sketch. This has produced very erratic results returning both positive and many negative numbers (shown by using "volatile long period;" in the monitor.

Can you tell me what is happening and would it be better to use a counter instead of interrupts?

Hope I have given enough information to be getting on with, many thanks.

```
// Camera shutter speed timer
// Author: Nick Gammon
// Date: 15th January 2012

volatile boolean started;
volatile unsigned long startTime;
volatile unsigned long endTime;
volatile unsigned long period;
volatile unsigned long lfrq;

// interrupt service routine
void isr () {
    if (started)
        endTime = micros ();
    else
        startTime = micros ();
    started = !started;
} // end of Pulse Width

void setup () {
    digitalWrite (2, HIGH); // pull-up
    Serial.begin (9600);
    Serial.println (" Pulse Width test = ");
    attachInterrupt (digitalPinToInterrupt (2), isr, CHANGE); //CHANGE RISING
} // end of setup

void loop () {
    if (endTime) {
        period = (endTime - startTime) * 32 ; // pulse width?
        Serial.print (" \n  ");
        Serial.print ( " period =  ") ;
        Serial.print (period) ;
        lfrq = 16000000.0 / period;
        Serial.print(" Hz = "); // one rev per sec = 26666 micros period
        Serial.print( lfrq );
        endTime = 0;
    }
} // end of loop

```

# Answer
> Can you tell me what is happening \[...\]?

Not really, but here is a wild guess: your input signal is bouncy, the ISR fires too often, your loop cannot keep up with the rate, and you end up accessing `endTime` in the ISR and loop simultaneously.

If you have a scope, look at your encoder signal. Is it clean?

> would it be better to use a counter instead of interrupts?

Using the input capture feature of a timer will give you the best possible accuracy, as you will have single-cycle resolution. In contrast, `micros()` has only 4 µs resolution (64 times worse) and the ISR may be delayed by up to ≈ 16 µs by the `TIMER0_OVF` ISR.

You can use the FreqPeriod library you linked to as an inspiration for writing your own timer-based code, but it will require some changes:

* As pointed out by Nick Gammon in a comment, you don't need the analog comparator, nor the conditioning RC network, as the encoder's outputs are already digital. Or you may use a low-pass filter if the encoder is bouncy.
* You will use the input capture pins of either timer 4 (digital pin 49) or timer 5 (digital pin 48). The other input capture pins are not available on the Mega's pin headers.
* You will replace `ISR(ANALOG_COMP_vect)` by either `ISR(TIMER4_CAPT)` or `ISR(TIMER5_CAPT)` (the relevant “capture event” ISR). No need to adjust a comparator threshold in the ISR.
* In the `begin()` method, you will leave the analog comparator alone, and you will enable the capture event interrupt.

Obviously you will have to study the datasheet before start coding.
> 1 votes

# Answer
> Could this be so?

because the code is faulty: there is no assurance of atomicity between startTime and endTime. ie. the interrupts could have arrived, multiple times, while the if loop is executing.

two ways to fix it:

1. calculate period in the isr; or
2. clear endTime once the clock starts in the isr.
> 1 votes

# Answer
While you are doing all those things with those volatile variables in the loop function, the interrupt can still be firing. If it fires in the middle of a read of startTime or endTime then you get might get part of the variable holding old value and part holding new value and when you put it together it makes garbage.

You need to do a cli() at the beginning of loop to turn off interrupts and quickly make local copies of all those variables and then sei() to turn interrupts back on. Now you can safely work with the copies you made.
> 1 votes

---
Tags: arduino-mega
---


title: Sending information via USB/Serialport

text:
# Question
Title: Sending information via USB/Serialport
Am I able to send instruction from my computer, from another compiler, via the Arduino USB port?

To put this in context, I'm doing some vision processing on my computer, with Visual Studio, and I want to send some motor output via USB for the Arduino to execute.

# Answer
I imagine Code Gorilla's given you the proper, specific answer you needed. I simply wanted to address your first (more general) ask,

> Am I able to send instruction from my computer, from another compiler, via the Arduino USB port?

... and mention some other ways I've done this before. As long the Arduino's listening to the serial port for some specific (or any) input coming in, you can use whatever you'd like to send a message to the COM port your Arduino's using.

You absolutely are *not* hemmed into using solely the Arduino IDE (or it's serial monitor) for serial communication.

For instance, I wrote a Python script that communicated with an Arduino R3 (Rx/Tx) via the COM port it was assigned via the `PySerial` library - before coming to Python, I'd been doing this through a MS Visual C# WPF that was connected to the COM port and communicating with the Arduino (Rx/Tx) (you might need to adjust baud rates here or there, if I recall). Just to give you some ideas.
> 1 votes

# Answer
You can do it in a number of ways, but essentially your PC is going to open a serial connection to the Arduino and send data to it which will be interpreted into state changes of the digital ports of the Arduino. The content of the messages is up to you, as long as both ends know what it means.

Step 1 would be to learn how to drive the motors on the Arduino by writing a program that drives the correct ports.

Step 2 is to modify that program so that when you type 1180 in to the serial monitor the Arduino turns motor 1 180 degrees, etc.

Step 3 Start Visual Studio, press F1 and search MSDN for a Serial console program that you can 'borrow'.

Step 4 Check your new serial program can replace the serial monitor and you can still turn motor 1 to 180 degrees.

Step 5 Put a flowery GUI over you serial console and polish your turd. :)

It doesn't matter what the GUI does, its still just a serial client talking to the Arduino. You could offer Bluetooth or Wi-Fi connections, but its essentially the same beast.
> 0 votes

# Answer
Assuming your project is along the lines of "finding something and pointing at it".

This youtube video shows an eye mounted on a stalk apparently controlled by servo motors (a type of positioning motor). The title infers an Arduino controls the motors and is in turned controlled by desktop computer running a program making use of OpenCV libraries. However no details are given.

An Arduino Uno is perfect for controlling servo motors as it contains a dedicated Atmel embedded processor. And there are Arduino servo libraries which make use of the Arduino processor's PWM hardware. This means controlling a servo can be as simple as several line of Arduino sketch code.

```
myservo.attach(2);  // attaches the servo on pin 2 to the servo object
myservo.write(0);   // sets the servo position to 0
delay(1000);        // waits for a second
myservo.write(90);  // sets the servo position to 90
delay(1000);        // waits for a second
myservo.write(180); // sets the servo position to 180

```

The USB port of an Arduino Uno normally implements serial port protocol layer inside the USB layer. Many computers can deal with this easily. So sending messages to an Arduino Uno is possible. Here is a project (Arduino Playground - Simple Servo Control tutorial) where a (desktop) computer is controlling servo motors connected to an Arduino over the Arduino's USB port.
> -2 votes

---
Tags: motor, usb, visualstudio
---


# Question
Title: Is it possible to use Serial window for debug statements while using the hardware serial port for GPS module?
I am using the hardware serial ports of Atmega 328 to connect to a GPS module . A GSM SIM900 module is connected via Software serial . Is it possible to print the debug statements in the Serial window while the GPS module is connected to the hardware serial ports? Both my module and the Serial window is set to 9600 bps baud rate . Also I want to read the GSM responses from the Software serial and print the same in the Serial window for debugging. Is this possible?

# Answer
> Is it possible to print the debug statements in the Serial window while the GPS module is connected to the hardware serial ports?

Yes, that works. If you connect the Arduino TX pin 1 to the GPS RX, then everything you print to Serial goes to *both* the Serial Monitor window and the GPS device.

This works, because:

* It's ok if you see the GPS configuration commands (if any) on the Serial Monitor window. Your debug prints will appear after them.
* The GPS device ignores anything that doesn't start with a '$' character; it ignores all your debug prints.
> 3 votes

# Answer
While I agree with slash-dev, I feel unless you're really struggling with pin real state, you don't really need to have both the GPS serial and UART on the same pins (unless I'm missing some point or convention, in which case please do correct me).

When I was using a GPS module (GTOP013) with an Atmega328p, I just used the SoftwareSerial library to configure some unused pins (12 and 13 I think? it's been a while) as a dedicated RX/TX lines to the GPS, whilst the atmega's RX/TX remained reserved for a USB connection. Any time I needed anything sent to or from the GPS, I had a function to handle that. Also allowed me to keep polling the lines for data from the GPS to be printed onto the Serial.Console as desired for debugging.
> 0 votes

---
Tags: software, serial-data
---


title: GSM SIM900A SMS content not displaying

text:
# Question
Title: GSM SIM900A SMS content not displaying
I am trying to read messages sent from my mobile to a GSM SIM900A module on my Arduino Serial monitor. Neither does the AT+CMGR command nor does the AT+CMGL command display SMS content. I also tried increasing the receiver buffer size in the SoftwareSerial Library but to no avail. I am simply trying to read 'check123'. I want to further store the SMS received as a string for further processing. But I am stuck with no display of SMS content on the serial monitor.

My code is:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10);
String content = "";
char character;
int i;

void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);
  delay(100);
}

void loop() {
  ReceiveSMS();
  delay(2000);
}

void ReceiveSMS() {
  mySerial.println("AT+CMGF=1");
  delay(2000);
  toSerial();
  mySerial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
  delay(2000);
  toSerial();
  mySerial.println("AT+CMGL=\"ALL\"\r");
  delay(5000);
  toSerial();
  mySerial.println("AT+CMGD=1,4");
  delay(2000);
  toSerial();
}

void toSerial() {
  while (mySerial.available() != 0) {
    Serial.write(mySerial.read());
  }
}

```

Output is:

**Edit:**

SoftwareSerial.cpp file. I have marked the area where I have changed the value from 64 to 256 according to some previous help post.

# Answer
Your code is absolutely correct. As I tested it with my Mega with Serial3 connected to GSM SIM900. I think there is something fishy about SoftwareSerial. Double-check the location of SoftwareSerial.

> C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial\src

Maybe you can see if RAM usage is exceeding the safe limit. Here is my output:
> 1 votes

---
Tags: arduino-uno, serial, gsm, softwareserial
---


# Question
Title: ESP8266 + Arduino Uno: Can't send AT Commands
I'm trying to get the ESP8266 up and running without a FTDI chip, just my Arduino Uno. But it seems really difficult. What I did:

* attach the ESPs VCC directly to Arduino Uno 3.3V; RX-\>TX; TX-\>RX

Result: surprisingly worked for 2 mins, however the AT commands returned ERROR sometimes. (baud rate: 9600)

* attach the ESPs VCC to 3.3V 500mA power supply; RX-\>TX; TX-\>RX

Result: AT commands don't work anymore, nothing is displayed in the serial monitor, not even my input; red LED constantly on.

* attach the ESPs VCC to 3.3V 500mA power supply; TX-\>TX; RX-\>RX

Result: blue LED constantly on, no response, same as before

* change back RX/TX connection, experimenting with baud rate (300 - 115200)

Result: blue LED flashes on start, flashes when something is sent (no matter what the baud rate is), however still no output at all.

Suddenly, I was also getting this error while uploading:

> ser\_recv(): programmer is not responding

Detaching the TX connection solved the problem. Btw, I am also using a voltage divider between TX of the Arduino and RX of the ESP.

Afterwards, the blue LED was on constantly again, even though I haven't changed the wiring... (really weird)

To me it looks like the Arduino Serial monitor isn't sending anything, because I don't even see my input. However, the Arduino can output stuff, therefore I assume a connection between Arduino and PC is existing. Maybe it has to do with the connection between TX -\> RX, but I see no shorts, just an ordinary voltage divider (100 Ohm and 200 Ohm resistors).

As you might see, I spent a lot of time trying to figure this out. I'm kind of stuck now, as I'm not sure what else to try. If you have any ideas, tips or advice please leave an answer.

Sorry for my English, it's not my native language. If you don't understand something, feel free to ask.

Hope you can help me!

# Answer
> 4 votes
Tx and Rx should be crossed; meaning connect Arduino Tx to ESP Rx and vice versa.

Your second (and first) attempts are correct. Use 1uF capacitor between Vcc and Gnd. This will provide a more robust connection since the ESP can draw too much current which might cause it to reset.

When using external power supply, hook together the Arduino Gnd to the PS Gnd.

If you get "Programmer is not responding" - disconnect and reconnect the Arduino USB. Also, you shouldn't get this at all since you are not trying to program the Arduino, just use its FTDI as proxy to the ESP. Any serial terminal application can do it (you don't have to use the built-in terminal in Arduino IDE).

# Answer
> 2 votes
When the 8266 is powered from the Arduino there is barely power enough for sending. So there will be power glitches that makes the USB port inactive. Even a short voltage drop seems to disable the USB port until it is pulled and reconnected.

I struggled with this. One solution is external power for the WiFi chip. One other solution is to put a 1000 uF capacitor on the 3V power line and ground. That has worked for me.

# Answer
> 1 votes
I have powered the ESP module with 3.3V of Arduino itself.

I too used to get the error always until I changed my settings to "no line ending" at the bottom of the serial monitor.

I had kept it to "NL & CR" from other answers that I read here, and that was the reason for errors I suppose. Anyway changing it gave me the AT OK.

You should try that first.

# Answer
> 0 votes
Put CH\_PD HIGH for AT mode COM.

Note if you upgrade firmware you need to take CH\_PD LOW to write new firmware. Also note if you upgrade your firmware for the LUA com speed will probably default to 115200 and then SoftSerial wont work. I found it best to test on Arduino Mega as has extra serial ports.

---
Tags: arduino-uno, serial, wifi, esp8266
---


title: Writing your own Arduino flashing tool

text:
# Question
Title: Writing your own Arduino flashing tool
I want to make Arduino flashing tool only for a `nano`, a simple flashing application which could run on windows taking input as a `.hex` file.

I know how to do this in Linux environment using `Makefiles` and writing script to automate it but have no idea what all are the things which I need to know and consider before I proceed with any windows application for such cases (implementing light GUI).

Any initial guide or read through would be a great help!

# Answer
This application already exists. It's called `AVRDUDE`:

http://www.nongnu.org/avrdude/

You can download it compiled for Windows at the link above. This is the very flashing tool that the Arduino IDE uses for the AVR boards such as Nano. You can get the AVRDUDE command the Arduino IDE uses to upload to the Nano by following these steps:

1. Start the Arduino IDE
2. File \> Preferences \> Show verbose output during: \> upload (check) \> OK
3. Tools \> Arduino Nano
4. Sketch \> Upload
5. After the process completes scroll the black console window at the bottom of the Arduino IDE window up to the start of the upload output and you will see the command generated by the Arduino IDE, which you can adapt to your needs.

If you want to use Makefiles you can get `make` compiled for Windows from this package:

http://winavr.sourceforge.net/

Note that it's incorrect to call what you're trying to do an IDE. IDE stands for Integrated Development Environment, which this is certainly not.
> 4 votes

---
Tags: arduino-ide, ide, flash, software
---


title: Help needed to add and extra sensor

text:
# Question
Title: Help needed to add and extra sensor
I am new to Arduino, and already tried to edit this many time. But I cant figure out whats wrong.

The following code has a PIR sensor, 1 LED and 1 buzzer. I want to add one more PIR sensor, but it should trigger a separate LED , and the same buzzer. In serial monitor. I have searched many sketches, but all of them seems to have a different method , cant figure out the basics!

```
int ledPin = 13;                // choose the pin for the LED
int inputPin = 2;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status
int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11)

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
  pinMode(pinSpeaker, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
      digitalWrite(ledPin, LOW); // turn LED OFF
      playTone(0, 0);
      delay(300);
      if (pirState == HIGH){
      // we have just turned off
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(pinSpeaker,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(pinSpeaker, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}

```

# Answer
> 2 votes
Well, after playing with the code for some time, I just did it!! pasting the updated code here, may be useful for someone else like me..

```
int ledPin = 13;                // choose the pin for the LED
int ledPinB = 12;               // choose the pin for the LED 2
int inputPin = 2;               // choose the input pin (for PIR sensor)
int inputPinB = 4;              // choose the input pin (for PIR sensor 2)
int pirState = LOW;             // we start, assuming no motion detected
int val1 = 0;                  // variable for reading the pin status
int val2 = 0;                  // variable for reading the pin status
int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11)

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(ledPinB, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
  pinMode(inputPinB, INPUT);     // declare sensor as input
  pinMode(pinSpeaker, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  val1 = digitalRead(inputPin);  // read input value
  val2 = digitalRead(inputPinB);  // read input value
  if (val1 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  }
  else if (val2 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPinB, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  }

  else {
      digitalWrite(ledPin, LOW); // turn LED OFF
      digitalWrite(ledPinB, LOW); // turn LED OFF
      playTone(0, 0);
      delay(300);
      if (pirState == HIGH){
      // we have just turned off
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(pinSpeaker,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(pinSpeaker, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}

```

Link to circuit and virtual demo

---
Tags: arduino-uno
---


title: How do I load an image using fopen()?

text:
# Question
Title: How do I load an image using fopen()?
I am trying to write a program that `fopen()`s an image so I can use it later.

I've wired my SD card adapter exactly the way shown here: \[!\[enter image description here\]\[1\]\]\[1\]

And I'm using the following code to `fopen()`:

```
FILE *streamIn;
streamIn = fopen("pic.bmp", "r");

```

When I compile, I get the following error:

> In function main:
>
> ccA5H011.ltrans0.o:(.text.startup+0x29a): undefined reference to \`fopen'

* I have the most up-to-date Arduino software.
* I am using the Arduino MEGA.
* The image "pic.bmp" is 100x100 and is not in any folder of the SD card, it is located right in it instead (If I click on the SD Card in "My Files" when it is plugged into my computer, pic.bmp is there).

# Answer
Simple answer: use the SD library provided by the IDE.

Long answer: `fopen` etc are designed for use with an operating system. While it is possible to 'bend' them to work without a kernel or filesystem abstraction layer, it's not easy. The AVR compiler and libraries don't provide the facilities for doing it.

So you need to use the method that is specific to the Arduino, which is contained in a library supplied with the IDE called SD.h. It has examples with it to show you how to use it.

There are other alternatives, as well, such as the much better written FatFS that has been ported to many platforms, Arduino included.
> 1 votes

---
Tags: sd
---


# Question
Title: Why we can wake Arduino Uno from sleep using only pin 2?
Can we use other pin as an interrupt to wake Arduino Uno from sleep ?

# Answer
It's not just Pin 2 that can wake from sleep. Depending on which sleep mode you are in different interrupts (both internal and external) can wake the chip up.

The datasheet contains this helpful table:

The external interrupts (pins 2 and 3 on the Uno, and only "Level" trigger mode), pin change interrupts, I2C address matching, and the watchdog are the only interrupts that can wake the chip from *any* sleep mode. Other interrupts only work in certain sleep modes since they require parts of the chip to still be running in order for the interrupt to fire.

So that means that yes you can use any pin you like (using the "Pin Change" Interrupts) to wake the chip.
> 5 votes

# Answer
I think you also can use pin 3 (INT1), see link

There are two interrupts:

* INT0, pin 2
* INT1, pin 3

According to the link (among other techniques), an external interrupt can be used, so both INT0 and INT1 should be valid.
> 0 votes

---
Tags: arduino-uno, atmega328, avr
---


# Question
Title: Two PIR sensors not working properly, help needed
I a just beginning with Arduino, I need some hellp here!! I have added two PIR sensors to this circuit with an LCD. Both PIR sensors are working fine and LCD is showing the correct PIR - only if a single PIR is active. Problem-1. If the PIR1 and PIR2 gets active at the same time, and PIR1 goes off - it will still work as both PIRs are on, both LED will be on and buzzer will sound!! In short when both sensors are active, Arduino cant sense which one went off later!!

Problem-2. second issue is the LCD is not displaying some text correctly.

If possible, it will be great if the system can display PIR1 status on line 1 and PIR2 status on line 2.

Can anyone help please to fix the two problems and add the extra feature ?

Here is a Link of virtual circuit to see the sketch and connections.

Here is the code

```
#include <LiquidCrystal.h>

int ledPin = 13;                // choose the pin for the LED
int ledPinB = 12;               // choose the pin for the LED 2
int inputPin = 6;               // choose the input pin (for PIR sensor)
int inputPinB = 7;              // choose the input pin (for PIR sensor 2)
int pirState = LOW;             // we start, assuming no motion detected
int pirStateB = LOW;            // we start, assuming no motion detected PIR2
int val1 = 0;                  // variable for reading the pin status
int val2 = 0;                  // variable for reading the pin status
int pinSpeaker = 10;           // Set up a speaker on a PWM pin (digital 9, 10, or 11)

LiquidCrystal lcd(9, 8, 5, 4, 3, 2);

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(ledPinB, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
  pinMode(inputPinB, INPUT);     // declare sensor as input
  pinMode(pinSpeaker, OUTPUT);
  Serial.begin(9600);

  lcd.setCursor(0, 0);           // Set LCD cursor position (column, row)
  lcd.print("Security");         // Print text to LCD
  lcd.setCursor(0, 1);           // Set LCD cursor position (column,row)
  lcd.print("System");           // Print text to LCD
  delay(1000);                   // wait 1s  Delay to read text
  lcd.clear();                   // clear LCD display
  lcd.setCursor(0, 0);           // Set LCD cursor position (column, row)
  lcd.print("System Booting");
  delay(1000);                   // Delay to read text
  lcd.clear();                   // Clear LCD
  lcd.setCursor(0, 0);
  lcd.print("Processing...");
  delay(1000);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Waiting For");
  lcd.setCursor(0, 1);
  lcd.print("Motion");
}

void loop(){
  val1 = digitalRead(inputPin);  // read input value
  val2 = digitalRead(inputPinB);  // read input value
  if (val1 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // just turned on
      Serial.println("Motion detected!");
      lcd.clear() ;
      lcd.setCursor(0, 0);   // Set LCD cursor position (column 0, row 0)
      lcd.print("PIR 1 Active!!");
      // only want to print on the output change, not state
      pirState = HIGH;
    }
  }
  else if (val2 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPinB, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirStateB == LOW) {
      // just turned on
      Serial.println("Motion detected!");
      lcd.clear() ;
      lcd.setCursor(0, 1);      // Set LCD cursor position (column 0, row 0)
      lcd.print("PIR 2 Active!!");
      // only want to print on the output change, not state
      pirStateB = HIGH;
    }
  }

  else {
      digitalWrite(ledPin, LOW); // turn LED OFF
      digitalWrite(ledPinB, LOW); // turn LED OFF
      playTone(0, 0);
      delay(300);
      if (pirState == HIGH){
      // just turned off
      Serial.println("Motion ended!");
      lcd.clear() ;
      lcd.setCursor(3, 0);
      lcd.print("Waiting For");
      lcd.setCursor(3, 1);
      lcd.print("Motion.");      // only want to print on the output change, not state
      // only want to print on the output change, not state
      pirState = LOW;
    }
  }
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(pinSpeaker,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(pinSpeaker, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}

```

# Answer
> 1 votes
Your problem is with the entire structure of your program. Pretty much everything is dependent on something else not having happened. Instead you need to make things more independent.

You should separate out your PIR sensor code into discrete chunks. One sensor isn't dependent on the other one having triggered or not, so there is no call to "link" them with an "else if". Also naming variables better will help understand the flow of code easier.

```
uint8_t savedStatePIR1 = LOW;
uint8_t savedStatePIR2 = LOW;

bool motionDetectedPIR1 = false;
bool motionDetectedPIR2 = false;

void loop() {
    uint8_t currentStatePIR1 = digitalRead(inputPinPIR1);
    uint8_t currentStatePIR2 = digitalRead(inputPinPIR2);
    bool haveChanged = false;

    if (currentStatePIR1 != savedStatePIR1) {
        savedStatePIR1 = currentStatePIR1);
        haveChaged = true;
        if (currentStatePIR1 == HIGH) { // Activated
            motionDetectedPIR1 = true;
        } else { // Deactivated
            motionDetectedPIR1 = false;
        }
    }

    // Exact duplicate with PIR1 changed to PIR2
    if (currentStatePIR2 != savedStatePIR2) {
        savedStatePIR2 = currentStatePIR2);
        haveChanged = true;
        if (currentStatePIR2 == HIGH) { // Activated
            motionDetectedPIR2 = true;
        } else { // Deactivated
            motionDetectedPIR2 = false;
        }
    }

    // Now, if either state changed this iteration through loop()
    // update the LEDs and the display, and play a tone if you
    // need to. Note that there is already a tone() function so
    // you really don't need to write your own.
    if (haveChanged) { // Something changed, so update things.
            digitalWrite(ledPin, motionDetectedPIR1);
            digitalWrite(ledPinB, motionDetectedPIR2);
            lcd.clear();

            if (motionDetectedPIR1 || motionDetectedPIR2) {
                tone(pinSpeaker, 300, 160);
                if (motionDetectedPIR1) {
                    lcd.setCursor(0, 0);
                    lcd.print("PIR 1 Active!!");
                }
                if (motionDetectedPIR2) {
                    lcd.setCursor(0, 1);
                    lcd.print("PIR 2 Active!!");
                }
            } else {
                lcd.setCursor(3, 0);
                lcd.print("Waiting For");
                lcd.setCursor(3, 1);
                lcd.print("Motion.");
            }
        }
    }
}

```

Note: this code isn't tested at all (it'll be full of errors). The basic principle, though, is:

1. First look for motion in PIR 1 and record if there is or not.
2. Repeat for the second PIR.
3. If there has been any change in state then (and only then) update the outputs.

# Answer
> 0 votes
Thanks for the reply @Majenko, But as I said in the question, I am just a beginner. I couldn't figure out how to use it. I did change the pin number, but I dont know what is "haveChanged". So I did changed the code I already have and it seems to be working virtually. But it does take time to respond sometimes, may be in real world conditions, it will be better ? Here is the link to virtual demo, please check and tell me if it is going to work.https://circuits.io/circuits/5142920-two-pir-project-1-0

Did spend some time, and made this code.

```
#include <LiquidCrystal.h>
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 5;

int NpirPin = 2;    //the digital pin connected to the PIR sensor's output
int SpirPin = 3;
int NledPin = 13;
int SledPin = 12;
int buzzerPin = 10;

LiquidCrystal lcd(9, 8, 7, 6, 5, 4);                          // initialize the library with the numbers of the interface pins

//SETUP
void setup(){
  Serial.begin(9600);
  pinMode(NpirPin, INPUT);
  pinMode(SpirPin, INPUT);
  pinMode(NledPin, OUTPUT);
  pinMode(SledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  digitalWrite(NpirPin, LOW);
  digitalWrite(SpirPin, LOW);
  digitalWrite(buzzerPin, LOW);
  lcd.begin(16, 2);
  lcd.setCursor(3, 0);
  lcd.print("Waiting For");
  lcd.setCursor(3, 1);
  lcd.print("Motion....");

  //give the sensor some time to calibrate
  Serial.print("calibrating sensors ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(500);
      }
    Serial.println(" done");
    Serial.println("SENSORS ACTIVE");
    delay(50);
  }
 ////////////////////////////
//LOOP
void loop(){

     if(digitalRead(NpirPin) == HIGH){
       digitalWrite(NledPin, HIGH);   //the led visualizes the sensors output pin state
       playTone(300, 300);
       delay(150);
         Serial.println("---");
         Serial.print("motion at NORTH");
        lcd.clear() ;
      lcd.setCursor(0, 0);                                           // Set LCD cursor position (column 0, row 0)
      lcd.print("PIR1 Active!");
         delay(500);
       }

     else if(digitalRead(NpirPin) == LOW){
       delay (300);
       digitalWrite(NledPin, LOW);
       digitalWrite(buzzerPin,LOW);}

     if(digitalRead(SpirPin) == HIGH){
       digitalWrite(SledPin, HIGH);   //the led visualizes the sensors output pin state
       playTone(300, 300);
       delay(150);
         Serial.println("---");
         Serial.print("motion at SOUTH");
        lcd.clear() ;
      lcd.setCursor(0, 0);                                           // Set LCD cursor position (column 0, row 0)
      lcd.print("PIR2 Active!");
         delay(150);
       }

     else if(digitalRead(SpirPin) == LOW){
       delay (300);
       digitalWrite(SledPin, LOW);
       digitalWrite(buzzerPin,LOW);}

}

// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(buzzerPin,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(buzzerPin, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}

```

---
Tags: arduino-uno
---


title: My Arduino Uno buzzer isn't working

text:
# Question
Title: My Arduino Uno buzzer isn't working
```
/*

*/

void setup() // Built in initialization block
{
    Serial.begin(9600);
    Serial.println("Beep!");
}

void loop() // Main loop auto-repeats

{

//   Serial.println("Beep!");

   tone(4, 3000, 1000); // Play tone for 1 second

   delay(1000); // Delay to finish tone
}

```

# Answer
> 0 votes
First, take a look at the two links provided in the comments to your question and explain why your question is different from them. Start by describing your "buzzer." If your question is not significantly different then it will attract downvotes instead of answers, or it may be marked as duplicate or just simply closed.

Here is one solution, making the assumption you are writing about a piezo beeper:

```
void setup() {
  pinMode(4,OUTPUT);
}
void loop() {
  digitalWrite(4,HIGH);
  delay(1000);
  digitalWrite(4,LOW);
  delay(1000);
}

```

Alternatively, take the first example program from your IDE, called blink, and hook your beeper to pin 13 (positive) and GND (negative) while that runs. It does basically the same thing.

---
Tags: arduino-uno, piezo
---


# Question
Title: Using a lot of interrupts on a single Arduino
I'm doing a little project that requires a lot of sensors. Right now I'm using 4, but i want to reach up to 60 sensors, and a minimum of 16 (for me that's a lot). So, I have an Arduino MEGA 2560, and I'm new to Arduino (Had a little experience with PIC before).

I've started my project with buttons and leds to simulate the sensor, but my sensors work normally HIGH, and when something pass in front of it, it goes quickly to LOW and back. English is not my first language so I don't recall the name of this sensor, kind of like movement sensor(?).

A lot of stuff pass normally, up to 50/s, in front of it, so it should keep "bouncing" between HIGH and LOW. But when I changed the buttons for the sensors, sometimes my processor won't react, and I think it's because the signal goes back to HIGH before the code reads it. Maybe it's not a problem when it's sensing lot of things, but I can't test it right now with a lot of sensors, and it's not something that can keep getting errors.

So I got to interrupts, reading the awesome gammon review. I understood a lot of new things that i didn't know and I searched for a interrupt Library, but the one I found can't use too many sensors.

I forgot to tell, but I'm using a touch 2,4" shield too, so a lot of interrupts pins can't be used.

Will I be able to use all the sensors I want? If not, could I do it with 2 Arduinos and 1 screen? Am i missing something about the interrupts? Where can I find something to help me?

Edit 1: All the sensor are the same

# Answer
On a *Uno*, all of the digital and analog pins can trigger a pin-change interrupt. That gives you 20 inputs straight away. The Mega also has pin change interrupts but not on all its pins. The pins that the Mega supports for pin-change interrupts are documented on the Software Serial page.

> Not all pins on the Arduino Mega and Arduino Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

(Note that the Atmega2560 chip itself supports more pin change interrupts, however those extra ones are not brought out to header pins on the Arduino board).

That's still quite a few (18 if I counted correctly). Plus the *hardware* interrupt pins: 2, 3, 18, 19, 20, 21.

> Right now I'm using 4, but i want to reach up to 60 sensors, and a minimum of 16

To reach 60 you probably want an input shift register such as the 74HC165 \- you can daisy-chain them together to get lots of inputs. However you would have to *poll* to see if pins changed.

Otherwise you could use something like the MCP23017 chip, which has 16 input/output pins, and supports interrupts. You can use 4 of them (interfacing with I2C) and thus get 64 inputs. There is a shield that has 4 of those chips on it:

With suitable software (see my page about I2C) you could configure for interrupts and read any of those 64 inputs when they change.

---

> Do I have to keep checking all the time for every sensor one by one?

No, because you can configure the interrupts as open-drain, which means you can connect them all together (if you want to). Or, you could bring out the interrupts for the 4 x MCP23017 chips to four interrupt inputs on the Mega (that narrows down for you which chip caused the interrupt). Then you can read the chip's register(s) to find the state of the pins - either at the time of the interrupt, or right now.

However you might find that it is actually faster to just poll the chips (say) 100 times a second. There is *some* overhead to using I2C, you can also get SPI versions of that chip (MCP23S17) which would operate a bit faster.

Alternatively, the 74HC165, whilst simpler, could also turn out to be overall faster if you just poll rapidly.

---

> And the sensor sense a lot of movement per second, won't that cause trouble for the Arduino?

You need to define "a lot" and "trouble". You won't do billions of read a second. You can probably do thousands. What would you do with thousands of readings anyway? The time taken to process them would probably be the limiting factor.

---

> At the same time I'm using a GPS, no problem for the usage of Serial and I2C together right?

No problem, because serial input is interrupt-driven. Within reason, you can do both at once.
> 6 votes

# Answer
For that many sensors (way more than the number of interrupts available on the chip), your interrupt service routine (ISR) will need to be able to poll the sensors to discover which one(s) caused the interrupt.

That might mean connecting each motion-sensor's output to both a latch and a many-input OR-gate to one of the interrupt pins. Your ISR would have to read the latches; set a flag for each LOW latch; clear the latches (to HIGH) and exit. The main routine would then take whatever action was needed for each sensor that had been LOW.
> 3 votes

# Answer
When you have implemented the solution given above, by Nick Gammon, it is recommendable that you try both of the solutions he provides, and use the timer circuit to time each version of the algorithm.

That is: You need to try out if the polled reading he mentions of lets say 100 times per second, or the interrupted method is the best, given your circumstances.

Reason being that if your system pulls the interrupts from time to time, lets say, each of the 64 inputs pulls its interrupt pin maybe once in 30 seconds, then you have just above 2 pulls per second to the board. That is not a lot, and checking the registers like 100 times per second (if you need time wise accuracy for instance), may prove very time consuming, as you would otherwise only run 2 interrupted algorithms per second.

Use the diode on the Arduino Mega circuit board if you have no display or output unit on the Arduino, to display the results. (If you need help communicating from the Arduino to yourself (human) via 1 diode, such that you can be told how much different a particular setup is, then let me know - that would be outside of the scope of this answer, I guess). I short, you can communicate to yourself by creating a little algorithm which starts with ie. 3 rapid blinks, then a pause, then it can create countable blinks for each figure, counting 0 with 10 blinks, and then you can count the blinks by putting breaks in between the figures. Thereby you can communicate the figure 1874 by 1 blink, pause, 8 blinks, pause, 7 blinks, pause, 4 blinks - then long pause, then 3 short blinks, pause, then it repeats.
> 1 votes

---
Tags: arduino-mega, sensors, interrupt
---


# Question
Title: How many WS2811 LED strips can I control with Arduino?
Is there any limitation to connecting more strips?

I plan to create for my temple Ganpati Street Lighting LED Decoration - Full HD Ahmednagar Mh India

Watch this video and give me some ideas and suggestions.

# Answer
There are three factors to consider when driving strings of these LEDs from an Arduino:

1. How much memory the Arduino has - each LED takes at least 3 bytes of RAM (possibly more depending on the library implementation). (An Uno could probably just manage 500 at most)
2. How long it takes to send the data over the wire - the more LEDs you have in a chain the longer each update takes and the slower your animations run.
3. How you power such a huge number of LEDs efficiently. You won't just plug them into the 5V pin of the Arduino that's for sure.

Note that the arrangement you link to most likely isn't a single small microcontroller controlling the whole lot. Instead it is much more likely each individual strip has a single controller and those controllers are all networked together (probably through RS-485 or CAN) to a master controller (probably a PC) to send instructions to them all.
> 3 votes

# Answer
Majenko is totally right (as always).

But as an alternative solution, you could opt for SPI-based LEDstrips. They're not bound to specific timings and thus:

1. You can "generate"/stream colors. You can let your Arduino calculate the next color and send it directly. In this way, you'll only need RAM for one pixel at the time. For the length, you're now only limited to the time it takes to update a strip.
2. Sending of data in SPI is done in hardware and can thus be done by hardware, while your software focusses on the next job/pixel. (So you also don't need to calculate the whole strip at once, before sending)
3. Often, you can send "pixels" much faster, by simply increasing your SPI clock. I'm not sure what the limit will be here, check the ledstrip datasheets.

Also, if you're going to push the limit of Arduino, why not use better hardware? The Teensy 3.2 is often used for ledstrip projects, since it has 64K ram and 256K flash and can run at 96Mhz (not sure about the SPI speed). Have a look at fastled and octows as well.

You should split up this project, to make it scalable. Try to make one "row" of it and start adding more rows (with individual controllers and power).

I agree with Majenko on using RS485 or CAN to connect/command/sync these different rows.
> 1 votes

# Answer
I have worked with setups similar to this. Arduino is limited as mentioned by Majenko.

If you like the Arduino platform I recommend you look into the Teensy based controllers. They are 32 bit based and have more memory and are optimized to handle LED projects like this. Best of all, it uses the Arduino IDE with numerous libraries. The Teensy would need to be paired with a Network adapter, so you could use sACN E1.31 and use software like Jinx to create the effects you're wanting to do.
> 1 votes

---
Tags: arduino-uno, arduino-mega, rgb-led
---


title: How to use AtMega328P-PN

text:
# Question
Title: How to use AtMega328P-PN
I am making an AC (the summer kind) control circuit with an AtMega328P chip. I bought the AtMega328P-PN instead of the P-PU. I followed the instructions on how to burn the bootloader, but nothing seems to work on the P-PN. I searched on Google for it and could find nothing anywhere.

Thanks in advance,

Iain

# Answer
> 2 votes
The ATmega328P-PN differs from the ATmega328P-PU essentially only in being rated over a wider temperature range.

It is for all ordinary purposes a direct substitute for where an ATmega328P-PU could be used, and has the same signature word.

Whatever your actual problem is, it is elsewhere.

(The chips that *do* require some special accommodation if ordered are the ATmega328 *without* a "P" before the dash and the ATmega328PB)

---
Tags: atmega328, bootloader
---


# Question
Title: How does one set attributes for SD files?
How does one set file attributes, e.g., creation date, for a file being created on an SD?

# Answer
> 8 votes
The Arduino SD library, is based on Github: greiman/SdFat, by William Greiman.

From SD Created File Attributes:

> The basic SD.h library doesn't set the attributes. You notice everything has the same creation date? The library doesn't have any way of knowing what the date is.

However, you need to use a callback function. The following information is from file creation date and time in sd card ?:

> Install the SdFat library - there is an example called Timestamp.ino describing in detail how to do it...
>
> ```
> // after your rtc is set up and working you code just needs:
>
> void dateTime(uint16_t* date, uint16_t* time) {
>   DateTime now = rtc.now();
>
>   // return date using FAT_DATE macro to format fields
>   *date = FAT_DATE(now.year(), now.month(), now.day());
>
>   // return time using FAT_TIME macro to format fields
>   *time = FAT_TIME(now.hour(), now.minute(), now.second());
> }
>
> //put that outside of any functions, before your 'setup'
>
> //Then inside your 'loop' or 'setup'
>
> void loop(void)
> {
>
>   //Other code that does stuff
>
>   //put this next line *Right Before* any file open line:
>   SdFile::dateTimeCallback(dateTime);
>   dataFile = SD.open(datafilename, FILE_WRITE);
>
>   //other code that does stuff
>
> }
>
> ```

There is another way of achieving this, in a sketch without having to convert to SDFat:

> @donald0000 wants the Date Modified field to show an actual time stamp when you look at the files present on the card using Windows Explorer. As Billy Ho says, the callback function is the way to do it. You can indeed use this function with `SD.h` if you don't want to convert to SDFat. Here is an example of the function in a sketch. Notice the timing of when the date modified time stamp is written, it is when `file.close()` writes the actual data to the card.
>
> ```
> #include <SPI.h>
> #include <SD.h>
> #include <Wire.h>
> #include <RTClib.h>
>
> File file;  // test file
> const uint8_t SD_CS = 10; // SD chip select
> RTC_DS1307 RTC;  // define the Real Time Clock object
>
>  char timestamp[30];
>
> //------------------------------------------------------------------------------
> // call back for file timestamps
> void dateTime(uint16_t* date, uint16_t* time) {
>  DateTime now = RTC.now();
>  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(),now.minute(),now.second(),now.month(),now.day(),now.year()-2000);
>  Serial.println("yy");
>  Serial.println(timestamp);
>  // return date using FAT_DATE macro to format fields
>  *date = FAT_DATE(now.year(), now.month(), now.day());
>
>  // return time using FAT_TIME macro to format fields
>  *time = FAT_TIME(now.hour(), now.minute(), now.second());
> }
> //------------------------------------------------------------------------------
> void setup() {
>
>  Serial.begin(9600);
>  Wire.begin();
>  if (!RTC.begin()) {
>    Serial.println("RTC failed");
>    while(1);
>  };
>  // set date time callback function
>  SdFile::dateTimeCallback(dateTime);
>
>   DateTime now = RTC.now();
>   sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(),now.minute(),now.second(),now.month(),now.day(),now.year()-2000);
>   Serial.println("xx");
>   Serial.println(timestamp);
>
>
>  if (!SD.begin(SD_CS)) {
>    Serial.println("SD.begin failed");
>    while(1);
>  }
>  file = SD.open("TEST_SD.TXT", FILE_WRITE);
>  file.println("Testing 1,2,3...");
>
>  delay(5000);
>  file.close();
>  Serial.println("Done");
> }
> //------------------------------------------------------------------------------
> void loop() {}
>
> ```

# Answer
> 3 votes
Quite simply `FAT16` only supports 1 date, normally Modified Date. `FAT32` has (limited) support for 3 dates (but AFAIK there is no Arduino library which supports `FAT32`).

Even then not all OS even support Creation Date. Windows has 2 different interpretations depending on application, Linux natively only supports Change Date, although extensions provide support for more dates.

---
Tags: sd
---


title: Need help with calculator logic

text:
# Question
Title: Need help with calculator logic
I am trying to build a calculator with an Arduino, an LCD display, and a keypad. Getting inputs from the keypad is not the issue. Before I can add, subtract, multiply, or divide any two numbers, I want to make sure the calculator registered the given number. I am trying to program it (so far) so that I type in a number and press enter (the @ sign I assigned to my keypad) and the LCD prints out that number. As you will see, I attempted to devise a logic mechanism for the Arduino to recognize the typed number.

I thought since as you type more numbers the value of the first number typed increases by 10 fold each time (if you start by pressing 4 then if you press another number such as 5 following it, that 4 will become 40, and 400 if another number is pressed, etc...) I could multiply that number (and every following number) by 10, 100, 100, etc...

But it doesn't work and I need help so that the number can be collected by the Arduino.

Here's my attempt at it:

```
    #include <LiquidCrystal.h>
    #include "Arduino.h"
    #include "Keypad.h"

    int count = 0;
    int row = 0;
    int column = 0;

    //const int buzzer = 0;

    int value1;
    int value2 = 0;

    int spot1 = 0;
    int spot2 = 0;
    int spot3 = 0;
    int spot4 = 0;
    int spot5 = 0;
    int spot6 = 0;
    int spot7 = 0;
    int spot8 = 0;

    LiquidCrystal lcd(1, 2, 3, 4, 5, 6 );

    const byte ROWS = 4; //four rows
    const byte COLS = 3; //three columns
    char keys[ROWS][COLS] = {
      {'1','2','3'},
      {'4','5','6'},
      {'7','8','9'},
      {'%','0','@'}
    };
    byte rowPins[ROWS] = {10, 9, 8, 7}; //connect to the row pinouts of the
    keypad
    byte colPins[COLS] = {13, 12, 11}; //connect to the column pinouts of
    the keypad
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS
    );

    void setup() {
      //pinMode(buzzer, OUTPUT);
      lcd.begin(16,2);
      lcd.print("---Calculator---");
      delay(2000);
      lcd.clear();
      lcd.print("Value1: ");
      lcd.blink();

    }

    void loop() {
char key = keypad.getKey();

if(key != NO_KEY){
  lcd.print(key);
  if(key != '%' && key != '@'){
    count++;
  }
  else if(count == 1){
    spot1 = key;
  }
  else if(count == 2){
    spot2 = key;
  }
  else if(count == 3){
    spot3 = key;
  }
  else if(count == 4){
    spot4 = key;
  }
  else if(count == 5){
    spot5=key;
  }
  else if(count == 6){
    spot6=key;
  }
  else if(count == 7){
    spot7=key;
  }
  else if(count == 8){
    spot8=key;
  }

  if(key=='@'){
    if(count == 1){
      value1 = spot1;
    }
    else if(count == 2){
      value1 = (spot1*10)+(spot2);
    }
    else if(count == 3){
      value1 = (spot1*100)+(spot2*10)+spot3;
    }
    if(count == 4){
      value1 = (spot1*1000)+(spot2*100)+(spot3*10)+spot4;
    }
    if(count == 5){
      value1 = (spot1*10000)+(spot2*1000)+(spot3*100)+(spot4*10)+spot5;
    }
    if(count == 6){
      value1 = (spot1*100000)+(spot2*10000)+(spot3*1000)+(spot4*100)+(spot5*10)+spot6;
    }
    if(count == 7){
    }
    if(count == 8){
    }
    lcd.print(value1);
  }

  if(key  == '%'){
    count = 0;
    lcd.clear();
    lcd.print("Value1: ");
    lcd.blink();
  }
}

}

```

PS: If you know any better way to accomplish this goal, I would love to hear it.

# Answer
If your keypad setup results in '%' and '@' arriving correctly, then it probably also results in the characters '0', '1', ... '9' arriving when number keys are pressed, rather than digit values 0, 1, ... 9 arriving.

Be that as it may, there's a far simpler approach to building `value1` which does not use a big set of spot values like your method does. Here is an illustration of it.

```
// ... Before number input, zero out a number-accumulator variable
long int nin = 0;

do {
  key = keypad.getKey();
  if (key != NO_KEY) {
    lcd.print(key);
    // As number keys are pressed, add them to tail of number
    if (key >= '0' && '9' >= key) {
      nin = 10*nin + (key & 0xF);   // Get low 4 bits of key
    }
  }
  if (key == '@') {
    lcd.print("Value = ");
    lcd.print(nin);
    // ... do whatever else with value
    // ... then get ready for next value
    nin = 0;
  }
} while (1);

```
> 2 votes

# Answer
```
if(key != '%' && key != '@'){
  count++;
}
else if(count == 1){
  spot1 = key;
}
else if(count == 2){
  spot2 = key;
}

```

You've got a problem here. If key isn't '%' and isn't '@' then you increase count but since all the rest are else if to that then it skips over all of them and never actually puts the digit int the spot.
> 1 votes

---
Tags: arduino-uno, programming, lcd
---


# Question
Title: Arduino unstable analog reading when using power supply
As soon as I unplug my Arduino from USB and only use the VIN pin with my 9 V power supply, the analog readings from my Arduino start to get unstable, which means the value fluctuates much more than with USB connected. When I reconnect USB again, the readings are stable again.

I'm trying to build a load scale using a load cell, an INA125P and the Arduino, using this setup here: Instrument Amplifier Calibration.

Therefore I need stable readings. For example, I wrote some code to convert the `analogRead()` value to grams. While USB and VIN (9 V) connected, I get a stable reading of about 8.3 to 8.7 grams when I put a weight of 8.5 grams on the scale. As soon as I unplug USB, the LCD shows values from 7.8 grams up to 9 grams.

Unfortunately, I don't have any other power supply which I could use to test. I've already tried to use a 9 V battery with the same results. Do I maybe need some additional de-coupling capacitors?

# Answer
I solved a similar issue by adding a pin from supply to AREF and it's now stable. This fixed a frustrating pH meter issue on my Mega that every time I plugged USB in it would be right, but as soon as I dropped the USB cable it changed the readings.
> 5 votes

# Answer
Does your arduino have a switch-mode regulator when converting 9V to 5V? If that's the case, then you must have some voltage ripple on your 5V power line. I'm guessing you are probably using analogRead which uses that 5V reference. If there is a ripple in your reference voltage, you will get a ripple in your readings.

Can you use the internal 1.1V reference of Atmega328p chip? That reference voltage is (as far as I know) the most stable you can provide for ADC.

If that doesn't work, then you need to find a very stable 5V adapter for your 9V sources.
> 3 votes

# Answer
Load cell signals are very small and without proper shielding are be susceptible to noise. The USB power connector is likely earth grounded (the clue was battery operation is noisy, exact opposite of expectations!) I suggest testing this hypothesis:

1. Check with ohm meter if exposed metal on USB connector is connected to earth (chassis on your PC is usually earth connected).
2. Touch an earth grounded conductor to the signal ground of the load cell amplifier and see of the readings become more accurate.

The final solution is to use properly shielded signal wires between the load cell and the amplifier. Also the signal wires between load cell and amplifier should be a 'twisted pair' to further reduce noise.
> 3 votes

# Answer
I would say that this may be related to the analog reference. Try AnalogReference and see if it helps.
> 2 votes

# Answer
Without much information (software, schematic, hardware, measurements ...) It is hard to tell.

My guess would be that you used vcc as a dc reference and the circuit draws too much current from the battery than it can deliver so bcc dips, leading to a rise and instability in the reading.

Good luck debugging it.
> 0 votes

---
Tags: power, analogread
---


# Question
Title: How to flash hex files from a micro SD card to an Arduino Nano using an SD card module?
I want to flash a hex file stored in a micro SD card into an Arduino \[Uno/Nano\]. So far I can read and write to the SD card using Arduino.

Without modifying the bootloader, is it possible to flash the Arduino using micro SD card module?

# Answer
> 1 votes
No. Only the bootloader is allowed to write to the program flash.

# Answer
> 0 votes
Yes, but I am not sure it can work from the smaller Arduino models. Have a look at the Phoenard project. The platform, based on a 2560, flashes .hex files on demand, which are stored on the SD card.

It's an open-source project, so it should be possible to go through the code and see how they do it.

---
Tags: arduino-uno, arduino-nano, spi, sd-card, flash
---


# Question
Title: Getting the "Device has problem: 0x0a: CM_PROB_FAILED_START." error code 10 while installing device driver for Arduino Uno
After uninstalling and reinstalling Arduino IDE, my Arduino Uno is not recognized by my PC. When I connect it to my PC all lights are glowing in my board but my PC is not showing anything connected to USB.

When I tried to install drivers manually I'm getting the error device cannot start code 10. I have used the default drivers for Arduino, which I downloaded with the IDE. I tried installing them manually. I don't have any idea about chipset interface whether it is CH or FTDI. I have looked at all the possible solutions but my problem wasn't solved.

# Answer
Error code 10 mean Bad Environment. I would guess that you are using the wrong driver, probably 64 bit on a 32 bit OS, etc.

This does not look like a Arduino fault, it looks like a windows Driver fault, so unlplug the board, reboot the PC logon as admin and download the latest drivers for you device and see if that fixes it. You might be able to get better help on a Windows admin forum I think.
> 1 votes

---
Tags: arduino-uno, usb
---


title: Speed of reading I2C

text:
# Question
Title: Speed of reading I2C
How long does it take to read I2C?

I'm reading data from I2C sensor through a 20Hz timer interrupt. The interrupt handler only set the readSensorFlag, and I double checked that it happens at 20Hz through putting a Serial print there.

```
void TIMER2_Interrupt(void) {
  if (NRF_TIMER2->EVENTS_COMPARE[0] != 0) {
        readSensorFlag = true;
        NRF_TIMER2->EVENTS_COMPARE[0] = 0;
      }
    }

```

Now in the main loop I perform the reading of sensors.

```
void loop() {
  // Reading data from sensors to a buffer
  if (readSensorFlag) {
    readSensorFlag = false;

    if (bufferCounter < BUFLEN - 2*SAMPLESIZEINCHAR - 1) {
      epoch = millis();
      proximity = vcnl.readProximity();
      ambientLight = vcnl.readAmbient();

```

The strange this is that: if I set proximity and ambient light to be some constant and not reading from I2C, then the recorded sampling frequency is 20Hz:

```
  1988,    7,   10
  2038,    8,   10
  2088,    9,   10
  2188,    1,   10
  2238,    2,   10
  2288,    3,   10

```

If I revert back reading I2C code (second column is data from sensor), then frequency is only 8Hz!!!

```
 17637,    8,   33
 17763,    9,   33
 17937,    1,   34
 18067,    2,   35
 18194,    3,   34
 18320,    4,   34

```

How could reading I2C block the timer interrupt? And how could it be so slow? (I've tried a similar sensor before, and could reach 100Hz with that).

# Answer
> 2 votes
Let's take a look at a typical function for reading this sensor. This is from the Adafruit\_VCNL4010 library and is for reading the proximity:

```
uint16_t  Adafruit_VCNL4010::readProximity(void) {
  uint8_t i = read8(VCNL4010_INTSTAT);
  i &= ~0x80;
  write8(VCNL4010_INTSTAT, i);

  write8(VCNL4010_COMMAND, VCNL4010_MEASUREPROXIMITY);
  while (1) {
    //Serial.println(read8(VCNL4010_INTSTAT), HEX);
    uint8_t result = read8(VCNL4010_COMMAND);
    //Serial.print("Ready = 0x"); Serial.println(result, HEX);
    if (result & VCNL4010_PROXIMITYREADY) {
      return read16(VCNL4010_PROXIMITYDATA);
    }
    delay(1);
  }
}

```

So let's tot up all the I2C transactions in that one function:

```
read8
write8
write8
{repeated
    read8
    [read16]
    delay(1)
}

```

So in a best case scenario, assuming it's in a "ready" state, that's the minimum number of transactions, and the delay doesn't occur. So what is in each of those transactions?

* read8:

Begin the transaction, write the address, end transaction, delay 170µs, begin request, read 1 byte, end transaction. Total 4 bytes plus 170µs

* write8:

Begin transaction, write address, write data. Total 3 bytes.

* read16:

Begin the transaction, write the address, end transaction, begin request, read 2 bytes, end transaction. Total 5 bytes (I notice this one has no delay...?)

So now we can see a best case scenario total of bytes transferred:

```
4 read8 *
3 write8
3 write8
{repeated
    4 read8 *
    5 [read16]
    delay(1)
}

4+3+3+4+5 = 19 bytes, plus 2x170µs delay.

```

The default clock speed for I2C on the Arduino is 100kHz. We have 19 bytes, plus start/stop/ack bits. So 19 * 8 for the data bytes (152 bits) plus 19 ACK bits (171 bits) and 5 * start + 5 * stop. That's 181 bits in total.

181 bits, at 100kHz, takes 1.81ms to transfer. Add to that the 2\*170µs delay, and we are up to a *best case* scenario of 2.15ms transfer.

Double that up for reading the ambient light as well, and we're up to 4.3ms transfer. That's a theoretical absolute maximum of about 230Hz readings.

Remember: that's a **best case scenario**. If the sensor isn't ready to return a reading at the time that there will immediately be a 1ms delay imposed and the number of transactions will increase.

So why would it not be ready to send a reading? The simplest explanation is that it's not set to a suitable sampling rate.

The library doesn't appear to change the sampling rate for the proximity from the default 1.95 samples per second, nor the ambient light sampling rate from the default of 2 samples per second - so unless you are using a different library, or manually changing these settings through your own Wire calls, even at a reduced triggering speed you'll not be getting anywhere near the kind of information you are after.

The fastest you can get for ambient light sampling is 10 samples per second. Proximity caps out at a more respectable 250 samples per second. But only if you tell it to...

---
Tags: interrupt, analog-sampling
---


# Question
Title: Write char array containing new line to SD card
How do I a buffer (char array) containing new line character to SD card using SdFat?

I tried:

```
File myFile = SD.open("test.txt", FILE_WRITE)
myFile.write(buffer, BUFLEN)

```

but I get this instead:

```
0000 0000 0000 0000 0000 0000 0000 3337
3837 3838 3937 3035 2c20 2020 2031 2c20
2020 3531 0a33 3738 3738 3839 3730 352c
2020 2020 322c 2020 2035 310a 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000

```

If I use the normal method, then it seems that SdFat stop printing at the newline character:

myFile.print(buffer);

Note: the buffer containing data samples in fixed width csv format

```
3787889751,    1,   49
3787889752,   10,   49
3787889753,    1,   49

```

# Answer
`File.print()` stops printing at a NULL character (ASCII 0) not a new line. You can stick as many new lines as you like in a string and it will print. Try this example

```
void loop ()
{
  Serial.print ("Hello\nMultiline\nPrint\n");
  Serial.print ("Hello\0Multiline\0Print\n");
}

```

`File.write()` writes binary data to a file, it will write BUFLEN bytes, even if you don't give it that many bytes.

Looking at the output from you hex editor your string ends with ... 2020 2035 310a which would be 3 spaces (20), 51 (35 and 31) and a new line (0A). There is also a null (00) after that, but I can't tell how many because you have 0s to pad the output (or fill the file).

If you look further back in the output (3rd col, 3rd row) you can see another newline (0a33) so that proves its not new lines that is stopping your output.

Without your code we can't say whats wrong, but I agree with Mark that its not what you think it is.

To write data to a CSV file I would write each row of data into a struct and then hold those structs within a list. Then have a function that iterated through the list and printed each record to the file. That way you wouldn't need a buffer. If it didn't have to be a CSV then you could just call

```
myFile.write (currentRecord. sizeof(StructRecord));

```
> 1 votes

---
Tags: sd
---


# Question
Title: Thought Dropbox was gone, but Arduino IDE kept it running. Search led to Temboo & Arduino Yun. Will it cripple my IDE to cut it out?
Just discovered that long after uninstalling Dropbox the service was still running. I disabled it in the normal Services control panel. It turned out to be hiding in /winndows/system32 as dbxsvc.exe

Then went a step further and did this in an Administrator CMD window:

```
cd /windows/system32
attrib -h -s dbxsv*.*
del dbxsvc.exe
copy con dbxsvc.exe
Nyah^Z
attrib +r dbxsvc.exe

```

So that should take care of that.

Upon further system searching (using Everything) discovered that Dropbox is used by software called Temboo, which is some kind of cloud-share package for coordinating Arduino Yun applications.

**It turned out that it was the Arduino IDE that kept it running.**

More searching led me here:

Arduino & Temboo: How It Works

Excerpt:

> ON YOUR YÚN Your Arduino Yún includes two lightweight software components that make it easy to connect with hundreds of APIs and cloud services from any sketch.
>
> First, there's a small C++ library called Temboo.cpp that comes bundled with the Arduino IDE. When you include this library in a sketch, it provides a streamlined syntax for configuring and invoking calls to run Temboo Choreos.
>
> Behind the scenes, calls to Temboo are routed to a client program that comes packaged with your Linino base image. This client is a Python program that formats the Choreo execution request and uses HTTPS to forward the request to Temboo via the cURL utility.
>
> THE TEMBOO PLATFORM Temboo is a scalable, fault-tolerant environment for running and managing smart code snippets that we call Choreos. Choreos can call APIs, simplify the OAuth process, send email messages, perform encoding, update databases, and lots more. You can even create your own custom Choreos. Temboo automatically generates the sketch code you needed to call these processes, making it simple to get up and running with any service from your Yún.
>
> The request from the Yún's temboo client causes the Choreo specified in your sketch code to be executed on the Temboo platform. In many cases, this means assembling your inputs into the format expected by a third-party API, performing the API interaction, handling errors, and dispatching filtered results back to the Yún via HTTPS. The results are made available to your Arduino sketch by way of Process’s Stream methods.

I only use the standard Arduino IDE and regular Arduino Unos and Nanos. Sure some are Chinese-made, and some use the CH340 connection type.

## I do not want my system reaching out through the firewall to any cloud-based services, nor do I appreciate that the Arduino IDE thwarted my earlier effort to disable and remove Dropbox.

**I get that it came bundled with the standard Arduino IDE.**

**So my question is whether anyone knows if it will damage anything if I remove this junkware?**

--ADDENDUM - Why to dump Dropbox:

The Dropbox hack is real

Excerpt:

> Motherboard reported on what had been rumoured for some time, namely that Dropbox had been hacked.
>
> Not just a little bit hacked and not in that "someone has cobbled together a list of credentials that work on Dropbox" hacked either, but proper hacked to the tune of 68 million records.
>
> Very shortly after, a supporter of Have I been pwned (HIBP) sent over the data which once unzipped, looked like this:
>
> (The Dropbox data across 4 text files)
>
> What we've got here is two files with email address and bcrypt hashes then another two with email addresses and SHA1 hashes. It's a relatively even distribution of the two which appears to represent a transition from the weaker SHA variant to bcrypt's adaptive workload approach at some point in time. Only half the accounts get the "good" algorithm but here's the rub: the bcrypt accounts include the salt whilst the SHA1 accounts don't. It's just as well because it would be a far more trivial exercise to crack the older algorithm but without the salts, it's near impossible.
>
> At first glance the data looks legit and indeed the Motherboard article above quotes a Dropbox employee as confirming it.

# Answer
> 1 votes
There is **no** Dropbox software included with ANY version of the Arduino IDE, nor installed on any Linux based Arduino board.

That is **not** how Temboo and Dropbox work.

You have Temboo as a (source code) library which you can compile into your sketch, and as a user-agent that runs on the Linux portion of the Yùn. That then forwards a request to the Temboo web servers detailing what operations you want to perform on what services.

**It is then the Temboo web servers that connect to Dropbox (or whatever service you want to use) and perform operations on your behalf.**

If you have Dropbox software installed on your computer **it is not the fault of the Arduino IDE.**

---
Tags: arduino-ide, arduino-yun
---


# Question
Title: Is there any option to connect XDTouch IrTouchScreen to Arduino?
Is there any option to connect XDTouch IrTouchScreen with USB interface or RS232 to Arduino board?

At the cable of this touchscreen i have something like at the photo.
At the top of the photo pins (+, t, r, -) from touchscreen to SP232EEN, and at the bottom of photo pins (+, D-, D+, -) from CY7C63803-SXC module to USB output.

# Answer
Looks like your touch screen may talk RS-232. It uses the SP232EEN (a MAX232 clone) to interface with an MCU (Cypress CY7C63803) to get USB.

Connect wires to T1 IN and R1 OUT (I assume it's on channel 1) to your Arduino for UART communication. You would most likely need to disconnect those pins from talking to the Cypress chip, or they will interfere. Use the +5V and GND pins of the USB interface to power it direct from the Arduino.

Alternatively cut that board off and use a cheap MAX232 interface board to connect to the Arduino - that may be cheaper. T and R are TX and RX (though from which PoV is anyone's guess).
> 1 votes

---
Tags: usb, rs232
---


title: ESP8266 constantly reconnects

text:
# Question
Title: ESP8266 constantly reconnects
So, my ESP8266 now has this problem where every three seconds it goes offline for a split second and the light blinks as it comes back. It seems to be constantly resetting... I recieved this problem when I had it connected to a power brick in my pocket, and I am pretty sure it happened because of static. I would have bought a protective case for it but it appears that I csn only find 3D printed parts but I currently do not own a 3D printer. I am wondering how I can fix it. If I try to re-flash it the re-flash fails because it disconnects before the flashing finishes.

# Answer
> 2 votes
I managed to fix the problem. I have a PC with Ubuntu 16.04 and I tried to re-flash it using Ubuntu's ESPTool, which was why it was failing. I noticed it failed constantly at a certain point. To fix it, I re-flahed the firmware with this python script, and it was successful.

---
Tags: esp8266
---


title: Controlling TFT LCD with Arduino

text:
# Question
Title: Controlling TFT LCD with Arduino
I bought this LCD module. How many pins does this LCD module uses? They have written in the product description that this LCD module uses 8 bit communication, but the LCD module has 16 bit pinout (DB0-DB15). What is the right pin number?

Is there any Arduino LCD library that supports this LCD module, which uses the OTM4001A LCD driver? Usually for LCD the UTFT library works, but it does not support the OTM4001A LCD driver.

Thanks for your help!

# Answer
Trust what is on the board, not what the eBay seller says. They invariably can't tell the difference between a TFT screen and a doll, and they sell everything in between. They just regurgitate Chinglish nonsense. If the board says DB0-DB15 then DB0-DB15 is what you need to use.

Plus it says in the description:

> Support 16 bit RGB565 format , can connect any 16 bit data bus.

At least this one has told you what the driver chip is (OTM4001A) - many times they can't even do that and don't even understand what you are asking when you request that information.

Mind, it's a driver chip I have never come across before, so maybe I should get one on order to support it in DisplayCore...
> 2 votes

---
Tags: lcd
---


# Question
Title: How to read temperature from multiple DS18B20 faster?
I am writing an Arduino sketch to read temp data from multiple DS18B20 sensors and then write it to serial. The problem is, as I am connecting more sensors, the delay between my temp data is written to a serial increases (like 100ms for 1 sensor and 1s for 4 sensors). Can I somehow improve my sketch to read it faster?

Here is the sketch I am using: (I am using DallasTemperature to simplify it all)

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

#define ONE_WIRE_BUS 10
#define TEMPERATURE_PRECISION 8
#define BAUD_RATE 9600

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// arrays to hold device addresses
DeviceAddress devices[10];
int devicesFound = 0;

void setup(void)
{
  // start serial port
  Serial.begin(BAUD_RATE);
  //Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();

  // locate devices on the bus
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(sensors.getDeviceCount(), DEC);
  Serial.println(" devices.");

  devicesFound = sensors.getDeviceCount();

  // report parasite power requirements
  Serial.print("Parasite power is: ");
  if (sensors.isParasitePowerMode()) Serial.println("ON");
  else Serial.println("OFF");

  for (int i = 0; i < devicesFound; i++)
    if (!sensors.getAddress(devices[i], i))
      Serial.println("Unable to find address for Device" + i);

  // show the addresses we found on the bus
  for (int i = 0; i < devicesFound; i++)
  {
    Serial.print("Device " + (String)i + " Address: ");
    printAddress(devices[i]);
    Serial.println();
  }

  for (int i = 0; i < devicesFound; i++)
    sensors.setResolution(devices[i], TEMPERATURE_PRECISION);
}

// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

// function to print the temperature for a device
String printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC < 10)
    return "0" + (String)tempC;
  else
    return (String)tempC;
}

// function to print a device's resolution
void printResolution(DeviceAddress deviceAddress)
{
  Serial.print("Resolution: ");
  Serial.print(sensors.getResolution(deviceAddress));
  Serial.println();
}

// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
  Serial.print("Device Address: ");
  printAddress(deviceAddress);
  Serial.print(" ");
  printTemperature(deviceAddress);
  Serial.println();
}

void loop(void)
{
  if (devicesFound == 0)
  {
     Serial.println("No devices found.");
     return;
  }

  sensors.requestTemperatures();

  String sent = "";

  // print the device information
  for (int i = 0; i < devicesFound; i++)
  {
    sent += printTemperature(devices[i]);
    if (i != devicesFound - 1)
      sent += " ";
  }

  Serial.println(sent);
}

```

# Answer
> 3 votes
With 12 bits precision, DS18B20 may take up to 750 ms converting a temp.

Try using async reading, so you don't have to wait for the end of the process.

First you ask for a reading, later your read it

```
    DallasTemperature sensors(&oneWire);
    ...
    sensors.setWaitForConversion(false);  // makes it async
    sensors.requestTemperatures();
    sensors.setWaitForConversion(true);
    ...
    // Do something else while temp is been reading by the sensor
   ...
   float temp = sensors.getTempCByIndex(0);

```

# Answer
> 2 votes
I would start by changing this section:

```
String sent = "";

// print the device information
for (int i = 0; i < devicesFound; i++)
{
  sent += printTemperature(devices[i]);
  if (i != devicesFound - 1)
  sent += " ";
}

Serial.println(sent);

```

This section should read and print the temperature directly instead of creating a string. The string handling is a large overhead and it does not allow Serial (UART) to work very much in parallel if the buffer is filled. The printTemperature() function is using a lot of strings (and heap operations).

Otherwise you have done what is possible; 1) reduce the conversion resolution (9-bits is minimum), 2) use single conversion request command to all sensors.

The alternative is to use alarm triggers and only read sensors with alarms.

---
Tags: sensors, temperature-sensor
---


title: What are safe memory usage limits?

text:
# Question
Title: What are safe memory usage limits?
The Arduino IDE used to warn you when your sketch used too much memory. This warning now seems to have been removed. I compiled a sketch, and was surprised to see it use 175% of data memory...but not give me any explicit warning that this would be unstable, much less be physically unable to load onto the Arduino.

What are program and data memory usage levels that you should be concerned about? I seem to remember the best practice was to keep data memory under 80%. Is this still true? Is there any general rule for program memory?

# Answer
> 1 votes
The compiler can only report the amount of statically allocated (RAM) memory. Depending on what you are doing in your sketch the value may be important, or it may be completely meaningless.

Suffice it to say, the total of heap + stack + static must not exceed the memory of your MCU.

When it comes to the Flash memory you can go right up to 100%.

# Answer
> 0 votes
It's a tough question to answer as it depends on the rest of the sketch. You can safely use every single byte of memory as long as you're sure that's all you're using. The number that it spits out on compile doesn't tell you that. It just tells you about global and static variables really. If you've got a loop that doesn't call any functions then you only need to save a few bytes for the stack. But if you've got a function that creates a local array with 500 ints then you're not safe even if that number it spits out on compile is only 50%.

---
Tags: memory-usage, memory
---


# Question
Title: Can I control a Z84 counter timer circuit with Arduino?
Link to pin description and to the Datasheet.

I'm thinking about connecting channel outputs to LEDs and control the clock with IO-Arduino or a 555: I would program it with a 595 register.

Can someone explain me why this is a bad idea?

# Answer
I wouldn't say it was a "bad" idea - pointless maybe, but not "bad". A good learning experience if nothing else.
> 1 votes

---
Tags: arduino-uno, timers, shift-register
---