title: Arduino SSCANF stop on comma delimiter

text:
# Question
Title: Arduino SSCANF stop on comma delimiter
I have the following problem, the arduino is receiving a command like

**LCD,Display line text one, Display line text two**

I use an strcmp to match the beginning of the string that works but now I would like to ignore the beginning of the string (LCD) and scan in the next 2 variables until the comma to 2 new variables.

```
                sscanf(Command, "%[^,]%[^,]%[^,]", &dummy, &lcd_display_l1, &lcd_display_l2);

```

I don't know if it's possible to ignore the first variable (which would be the LCD) but I setup a dummy variable for it anyway what I not going to use.

All I get with this is the LCD in the dummy the other 2 does not fill up. I have tried this syntax:

https://support.microsoft.com/en-us/kb/38335

Doesn't work either. Any ideas?

# Answer
> 1 votes
I would suggest using `strtok()` to chop the string up:

```
char *prefix = strtok(mystring, ",");
char *firstString = strtok(NULL, ",");
char *secondString = strtok(NULL, ",");

```

That has the effect of slicing the existing string up in memory replacing the commas with `\0` and placing three pointers at the start of the three substrings. It has the advantage that it doesn't need to copy the contents of the string anywhere, so doesn't use any extra memory (other than the few bytes for the pointers).

---
Tags: arduino-uno, string, array
---


title: Firmware update for remote situations

text:
# Question
Title: Firmware update for remote situations
We are currently deploying units with the ATMEGA328 chip. Currently, all ICs have been flashed using the Arduino IDE. Upon release, we would like to offer updating of firmware in some cases, but obviously we would not want to send them the source code and let them download the arduino IDE.

We would like to send a firmware file, and an .exe file like a firmware upgrader, as most companies do. How would I start to go about this?

# Answer
Send them avrdude (including the config file) and the hex file. Look at the commands the IDE runs to see the right command format. You can then put that into a batch file if you like.
> 1 votes

---
Tags: programming, flash, firmware
---


title: Is my Arduino possibly broken?

text:
# Question
Title: Is my Arduino possibly broken?
We work in groups on a project at school. We had to build an electric scheme with an Arduino to make a small car moving.

We got the parts from our school, except the Arduino (we had to buy it ourselves). We had to use a battery of 11.5 V. We also had electrical resistors to protect the Arduino and the stepper drivers.

The car worked for a while, but then we wanted to change the program and tried to upload new software to the Arduino. Now the Arduino is not recognized by any computer.

We tried several things, like multiple times unplugging the USB cable, hitting the reset button on a specific timed moment (some method found on the internet).

But it still doesn't work. When the Arduino is connected via USB, the 'on' LED on the Arduino is on. After that all we came also to the conclusion that some people made mistakes on building the electric scheme...

* Is it possible that the Arduino is broken, since the battery has 11.5 V?
* If the Arduino isn't broken, can the problem that it's not recognized by the computer be solved?

(Arduino Uno)

# Answer
Considering that you used resistors to lower the 11.5V to an *cough - cough* "very normal and regulated 5V", that most certainly is the problem.

The "right and cheap" way to lower such high voltage and connect them directly to your 5V (just assuming, since you said that you used resistors to protect the Arduino) is actually to use a voltage regulator. Any cheap 7805 should do the job. The Arduino actually has its own voltage regulator on it, if you connect it though the Vin pin.

The "true and efficient" way to step down some voltage is actually to use a step-down converter. The way this is better then any normal regulator is that a regulator will lower your voltage by creating heat when the step-down converter will do it in a more efficient process.

The USB of your PC might also be the problem. There is a fuse on the Arduino and one in almost all USB ports of decent PCs. If the voltage spike is high enough, it might have burned the port. That is quite a rare event, but still possible.

Need anymore help, just comment. I'll be happy to help you!
> 1 votes

# Answer
If you connect 11.5V directly to the Arduino then you *might* have killed you Arduino, *BUT* you say the LED comes up when you hook up the USB lead. So take things one step at a time.

1. Get an Arduino that you know is working and try it in the PC with the same cable. Does it work? (No -\> Cable or PC is broken - Get a new cable/PC)
2. Remove all wires, shields, etc. from your Arduino.
3. Connect the USB cable to the PC, does the Arduino power up? (No -\> Arduino is almost certainly dead)
4. Does the PC recognise the board? (Window -\> Beeps, tries to download drivers, etc.) (No-\> Manually uninstall the drivers and then repeat this step if it doesn't succeed then the Arduino is very unwell)
5. Start the Arduino IDE and open Examples-\>Basic-\>Blink. Upload the program to your board. Does it work? (No -\> You need more advanced fault finding)
6. Change Blink so it prints a message every time the loop, Serial.println("Hello"); will do.
7. Upload you modified program and open the serial monitor. Does it show the message? (No -\> You need more advanced fault finding)

I know this doesn't fix the problem, but hopefully this will help you narrow down the fault. My gut feeling is that your Arduino has executed its last lines of code, but you never know...
> 1 votes

---
Tags: arduino-uno, usb, voltage-level, battery, voltage-protection
---


# Question
Title: How to connect GPS Neo-6M module to GSM Shield SIM900 V2?
I'm doing my final year project, My project is based on **"Arduino Real Time Gprs/Gsm & GPS Tracker"**. So Now I have purchased the hardware components such as:

1. Arduino UNO R3
2. GSM Shield SIM900 V2.0
3. Ublox GPS Neo - 6M Module

I'm a begginer to this project, I have a doubt connecting these components together. I have stack the GSM Shield with the Arduino Uno but I don't know how to connect the GPS module to the GSM Shield (How to wire the components). because as you see my pic you might see on the top of the GSM shield there are no female headers except one which comes for the display.

1. So do I need to implement a female header on the GSM Shield and solder it to conncet the GPS module?
2. Can't I connect the GPS module to the GSM Shield's UART Pins?

Please Help me Guys :)

# Answer
> 1 votes
For your program, I'll highly suggest to use `softwareSerial`. It pretty much emulates the serial communication on other pins (**NOT PIN 0 & 1**). Then connect it like if you would normaly connect an UART device to your Arduino on the 2 other pins that you chose (**NOT PIN 0 & 1**). This should make it easy to prorgam your Arduino while having the GPS and GSM module connected to your Arduino.

The shield can cause problems if it uses Tx and Rx on pins 0 & 1, **WHICH ARE THE PINS NOT TO USE IF YOU USE SOFTWARE SERIAL**, so you might as well connect it with jumper wires. Take the TXs from both of your module and connected to whatever GPIO you want and do the same to the RXs, **NOT ON PIN 0 & 1**.

Once again, `softwareSerial` is **NOT ON PIN 0 & 1**.

---
Tags: arduino-uno, shields, gsm, gps
---


# Question
Title: Arduino Nano periodic reset under program control?
Is there a way to cause a periodic reset of an Arduino Nano under program control, short of some kind of external relay that signals the RST pin?

I'd like to do a full reset triggered by a digital write.

When the power is applied to the Nano it automatically pulls all the digital output pins to LOW so it appears that simply connecting a wire from a digital output to the RST pin would cause the system to continually reset and never run the program. This would apply equally to using the DS3231 RTC chip's alarm function. It would require the program to run in order to use it.

I suppose a relay would do the trick. Or maybe even just an inverter chip like the 7404 between a digital output and the RST pin. I am trying to fit this all in a small box so more hardware gets to be a problem.

So the question: Is there any way to do this without external hardware?

# Answer
> 1 votes
Why do you want to reset you board? The reason affects the answer.

Do you want to reset the board because your program crashes after n hours? If so its probably better to fix the memory leak that you have in the code.

Is it because some global variables need to resetting every now and again? If so could you place them in a class and store a pointer to them as your only global. When you want to 'reset' the board delete the instance of the class and recreate it.

What happens if the software crashes? Have you got it configured to restart on a crash? If so could you just crash the code deliberately?

Because you have size constraints then it may be worth a bit of lateral thinking to see what the code can do for you.

---
Tags: arduino-nano
---


title: Keyboard key press listener

text:
# Question
Title: Keyboard key press listener
Is there a way to make a listener for a key press to begin a loop?

Example: I press the `Tab` key on my keyboard and the programmed loop begins running.

Essentially creating a keyboard hotkey.

# Answer
> 1 votes
The answer is yes and no.

Only the Arduino and its IDE, no.

The way I found is to use Processing to wait until it detects a hotkey, then send a serial message to your Arduino. If you tune in the right COM port, this should work.

---
Tags: arduino-leonardo, keyboard
---


title: What's the problem with baudrate?

text:
# Question
Title: What's the problem with baudrate?
I was trying to evaluate the speed of communication between pc and Arduino, using this code in Arduino:

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

void loop() {
  Serial.println("Ciao Arduino");
}

```

and this in Python:

```
import time, serial

arduino = serial.Serial('/dev/cu.usbmodem1421', 250000)

time.sleep(3)
count = 0
start = time.time()
while True:
   a = arduino.readline()
   print a
   count = count+1
   time1 = time.time()
   if time1-start >1 :
      print "--" + str(count)
      print a
      count = 0
      start=time1

```

Wich print out how many readline() he managed to do to evaluate the speed in further project. And I realized two things:

1. The program is working even with different baudrate
2. and with correct baudrate(For ex. 300-300 or 250000-25000) the baudrate is irrelevant(and wrong), I mean the 300 baudrate makes 20000 readline() and the 250000 make 5000 of them.

What's the problem? thank you

# Answer
> 5 votes
On a direct USB CDC/ACM connection (as you get on the Micro) there is no such thing as baud rate.

Any baud rate setting performed by the host (the PC) is merely an instruction to the device (the Arduino) to say "I would like you to operate at this speed", not "I would like you to communicate with me at this speed".

It is used in situations where the PC may want to set the baud rate of a real UART interface within the device, such as when the ATMega16U2 is used as a USB interface on the Uno - in that case the PC tells the 16U2 that it wants to communicate at, say, 115200 baud, and the 16U2 sets its UART (the one that communicates with the ATMega328P) to 115200 baud. The actual PC to ATMega16U2 (or ATMega32U4 in the case of the Micro) is at the native USB 2 bulk packet rate.

It is also used as a "reset" instruction to the ATMega32U4 - if the CDC/ACM port is opened by the PC at 1200 baud and then immediately closed again the 32U4 resets and enters the bootloader. This makes programming (usually) easy, as long as the program on the chip hasn't crashed and left the USB interface in an unusable condition (as sometimes happens).

---
Tags: arduino-uno, arduino-micro, python
---


title: SerialUSB on Arduino Due

text:
# Question
Title: SerialUSB on Arduino Due
I'm starting fiddling with a Due but I can't seem to be able to communicate over USB with it. Here is my code:

```
int bauds = 9600;

void setup() {
    SerialUSB.begin(bauds);
}

void loop() {
    if (SerialUSB.available())
        serialUSBEvent();
}

void serialUSBEvent() {
    String str = SerialUSB.readString();
    SerialUSB.write(str.c_str());
}

```

As you can see, I try with the bare minimum but my output consoles (2 COM port for the 2 usb connections, just in case I messed up which is which) stay blanks, whatever I send them...

# Answer
Have you tried resetting the board after sending the program? Or after having opened the terminal?

A few days ago I didn't have any results using SerialUSB, and today I have. The program has been sent trough the programming port, and SerialUSB is with native port. Uploading my program trough native port, it didn't worked until I reset!
> 1 votes

---
Tags: serial, arduino-due, usb
---


# Question
Title: I need 70 or more input pins for the Arduino -how to do this?
I have some SN74HC165N, CD4021B chips. How many (minimally) such ICs would I need to get 70 inputs to an Arduino Uno? What is the exact circuit diagram and the code? Im not sure how the wring cascades into each of the chips to make it grow to over 70 inputs, or what the code is for the 70 input circuit. I do understand how to use one of those ICs though. My second easier question is -is there an development board with 70 or more inputs?

CD4021B,SN74HC165N are the chips, you know the ones, that has a parallel input pins that are listened to by latch pin, and the clock pins such outputs the parallel data into the serial data-so I am interested with solution with this pin because I know how it works.

It is for sure 70 pins that are required -not any less-I am sure of that. Because the inputs cannot be further simplified to less than 70. The reason the inputs are 70 is because the algorithm used has 70 free variables in it. Hence by definition it uses 70 or more variables. The input for each of the 70 inputs can be a digital high or a digital low but this is not known before hand. So it cant be simplified because it like saying you can simplfy the information from 70 or more sensors at runtime, and each sensor has an unpredictable value. Anyway this explanation is moving away from the point of my question. I just want to know the circuit that does 70 inputs or more using the mentioned IC-I can live with that answer even if its not the most efficient.

# Answer
> 3 votes
The best way I know to do it is by using the MCP23017, which gives you 16 extra GPIOs via I²C communication. They can be configured for both input and/or output. I've done it myself and it worked like a charm. It has 3 pins for dynamic addressing (3 bits), which allows you to use up to 8 (0..7) MCP23017 for a total of **128** extra GPIOs. This is the chip datasheet: (http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf) There's a lot of examples about its use on the internet. Just google for "MCP23017 arduino" and you'll find them. For example: http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/

# Answer
> 1 votes
> I have some 74HC595 chips. How many (minimally) 74HC595 would I need to get 70 inputs to an Arduino Uno?

None. Those chips are for output, not input.

> I do understand how to use one 74HC595 though.

Evidently not, since you don't even know what they do.

> My second easier question is -is there an development board with 70 or more inputs?

Yes, there are. None made by Arduino though, but there are plenty of other options. Myself I work with microcontrollers with hundreds of IO pins.

However, I think you need to re-think what you are trying to achieve. There are many options for reducing the number of inputs you need to use depending on what it is you are doing. Maybe if you told us a little more about what you want to do, not how you think you want to do it, we can help you a little more.

---
Tags: arduino-uno
---


title: WaveHC Library Trouble

text:
# Question
Title: WaveHC Library Trouble
I posted this on the main Arduino forum, but no one has responded in 24 hours.

I'm trying to use the `WaveHC` library from Adafruit with a custom PCB. I am having trouble getting the `SPI` com to work for some reason, I modified the `ArduinoPins.h`, `SS_PIN`, from pin 10 to 8.

Using the Arduino SD library, I can see all the files no problem.

In the `WaveHC` library, all of the examples freeze after `card.init()`, I traced it to the `spiSend(uint8_t b)` in `SdReader.cpp`. It seems to get stuck in `while(!(SPSR & (1 << SPIF))`. This looks like the `SPDR` register (the `SPI` data register) is never loaded properly.

Does anyone know what is going on?

Adafruit library : https://github.com/adafruit/WaveHC

Edit : This is the output from the SDReadTest example (Arduino SD Library)

```
Initializing SD card...Wiring is correct and a card is present.

Card type: SD2

Volume type is FAT32

Volume size (bytes): 1973350400
Volume size (Kbytes): 1927100
Volume size (Mbytes): 1881

Files found on the card (name, date and size in bytes):
SYSTEM~1/     2016-11-07 14:11:06
  INDEXE~1      2016-11-07 14:11:06 76
0.WAV         2016-11-07 11:44:14 22124
1.WAV         2016-11-07 11:44:14 18604
2.WAV         2016-11-07 11:44:14 19244
3.WAV         2016-11-07 11:44:14 19884
4.WAV         2016-11-07 11:44:14 21164
5.WAV         2016-11-07 11:44:14 23084
6.WAV         2016-11-07 11:44:14 21484
7.WAV         2016-11-07 11:44:14 29484
8.WAV         2016-11-07 11:44:14 20844
9.WAV         2016-11-07 11:44:14 25004
P.WAV         2016-11-07 11:44:14 21804

```

Notes :

* I am using an Atmega328P @ 8MHz with the pro mini bootloader (this may be the issue)
* `SPI_DEFAULT_HALF_SPEED` is set to true
* `SPI_INIT_SLOW` is set to 1

# Answer
> 0 votes
So the problem was that I did not read this comment carefully

```
/** SPI slave select pin. Warning: SS may be redefined as another pin
but the hardware SS_PIN must be set to output mode before any calls to
WaveHC functions. The SS_PIN can then be used as a general output pin */

```

"SS\_PIN must be set to output mode before any calls to WaveHC functions"

I read this and thought that meant whatever pin was being used as the SS pin needed to be an output, but it meant literally that pin 10 (the hardware SS pin) had to be set as an output regardless of whether it was being used or not.

So the solution is to add

```
pinMode(10, OUTPUT);

```

to anywhere in the code

Edit : also thanks @per1234 for pointing out the correct answer, I just didn't read your comment properly.

---
Tags: sd-card, spi, adafruit
---


# Question
Title: Error: Expected primary-expression before void
We have been working on this "disaster bot" code for days and hours. AFter all of our hard work, Arduino gives us this error code: expected primary-expression before void. Please please please assist we are so desperate to get this to work. Here is our code below. Please.

```
// HEARTBEAT SENSOR (displays heart rate on LCD screen)
int sensorPin = A0; // This is the analog sensor pin the backwards S pin is connected to
                           // you can use any of the analog pins, but would need to change this to match
double alpha = 0.75; // This code uses a rather cool way of averaging the values, using 75% of the
                               // average of the previous values and 25% of the current value.
int period = 20; // This is how long the code delays in milliseconds between readings (20 mSec)
int in = 8;
int Reset=6;
int start=7;
int count=0,i=0,k=0,rate=0;

// LCD SCREEN
#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// BIG SOUND SENSOR
int soundDetectedPin = 10;
int soundDetectedVal = HIGH;
boolean bAlarm = false;

unsigned long lastSoundDetectTime;

int soundAlarmTime = 500;

// PUSH BUTTON AND BUZZER
int buzzer = 3;
int ledPin = 13;
int inPin = 7;
int val = 0;

#define sing

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

#define melodyPin 3
//Hotline Bling Melody
int hotlineb_melody[] = {
  0, NOTE_D5, NOTE_D5, NOTE_D5,
  NOTE_F5, NOTE_E5, NOTE_D5, NOTE_C5,
  NOTE_E5, NOTE_C5, 0,  NOTE_F5,
  NOTE_E5, NOTE_D5, NOTE_C5, NOTE_E5,

  NOTE_C5, NOTE_A4, NOTE_F5, NOTE_E5,
  NOTE_D5, NOTE_C5, NOTE_E5, NOTE_C5,
  0, NOTE_F5, NOTE_E5, NOTE_D5,
  NOTE_C5, NOTE_E5, NOTE_C5, NOTE_A4,

  NOTE_F5, NOTE_C6, NOTE_C6,
  NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6,
  NOTE_D6, 0, NOTE_F5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,

  NOTE_A5, 0, NOTE_C6, NOTE_C6,
  NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6,
  NOTE_D6, 0, NOTE_F5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,

  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,

  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5,
  NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5,
  NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5,

  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_F5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,

  NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5,

  NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5,
  NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_G5
};

//HotlineBLING tempo
  int hotlineb_tempo[] = {
  12, 12, 12, 12,
  12, 12, 12, 12,
  6, 2, 3, 12,
  12, 12, 12, 3,

  3, 3, 12, 12,
  12, 12, 6, 2,
  3, 12, 12, 12,
  12, 3, 3, 4,

  12, 12, 12,
  12, 12, 12, 12,
  2, 3, 12, 12,
  12, 12, 12, 12,

  2, 3, 12, 12,
  12, 12, 12, 12,
  3, 3, 12, 12,
  12, 12, 12, 12,

  2, 12, 12, 12,
  12, 12, 12, 12,
  12, 1.5, 12, 12,
  12, 12, 12, 12,

  12, 12, 6, 2,
  12, 12, 12, 12,
  12, 12, 12, 12,
  6, 2, 12, 12,

  12, 12, 12, 12,
  12, 12, 6, 2.4,
  12, 12, 12, 12,
  12, 12, 12, 12,

  12, 1.5, 12, 12,
  12, 12, 12, 12,
  12, 12, 6, 2,
  12, 12, 12, 12,

  12, 12, 12, 12,
  6, 2, 12, 12,
  12, 12, 12, 12,
  12, 12, 8, 24, 2
};

void setup() {

{
  //lcd.createChar(1, heart);
  lcd.begin(16,2);

  lcd.print("Heart Beat");
  lcd.write(1);
  lcd.setCursor(0,1);
  lcd.print("Monitering");
  pinMode(in, INPUT);
  pinMode(Reset, INPUT);
  pinMode(start, INPUT);
  digitalWrite(Reset, HIGH);
  digitalWrite(start, HIGH);
  delay(1000);

  lcd.begin(16,2);
  lcd.print("need to talk?");
  delay(1000);

  lcd.begin(16,2);
  lcd.print("not yet satisfied with care?");
  delay(1000);
}
// This code runs on startup, it sets ledPin to output so it can blink the LED that is built into the
// Arduino (but then never does), and sets the serial port up for fast 115,200 baud communication
// of the values (make sure you change your serial monitor to match).

  Serial.begin (115200); // the baud rate of the serial data
  {
    Serial.begin(115200);
    pinMode (soundDetectedPin, INPUT);
  }
  //PUSH BUTTON AND BUZZER
  {
    pinMode(buzzer, OUTPUT);
    pinMode(13, OUTPUT);
    pinMode(inPin, INPUT);
    }
}

void loop() {
  // HEARTBEAT SENSOR
    static double oldValue = 0; // used for averaging.
    static double oldChange = 0; // not currently used
    int rawValue = analogRead (sensorPin); // This reads in the value from the analog pin.
                                                              // this is a 10 bit number, and will be between 0 and 1023
                                                              // If this value doesn't change, you've connected up
                                                              // something wrong

  unsigned long time2,time1;
  unsigned long time;

    double value = alpha * oldValue + (1 - alpha) * rawValue; // Calculate an average using 75% of the
                                                                                // previous value and 25% of the new

    Serial.print (rawValue); // Send out serially the value read in
    Serial.print (",");          // Send a comma
    Serial.println (value);   // Send out the average value and a new line
    oldValue = value;        // Save the average for next iteration
    delay (period);            // Wait 20 mSec

  if((digitalRead(start)))
  {
    k=0;
    lcd.clear();
    lcd.print("Please wait.......");
    while(k<5)
    {
     if(digitalRead(in))
     {
      if(k==0)
      time1=millis();
      k++;
      while(digitalRead(in));
     }
    }
      time2=millis();
      rate=time2-time1;
      rate=rate/5;
      rate=60000/rate;
      lcd.clear();
      lcd.print("Heart Beat Rate:");
      lcd.setCursor(0,1);
      lcd.print(rate);
      lcd.print(" ");
      lcd.write(1);
      k=0;
      rate=0;
    }

  if(!digitalRead(Reset))
  {

      rate=0;
      lcd.clear();
      lcd.print("Heart Beat Rate:");
      lcd.setCursor(0,1);
      lcd.write(1);
      lcd.print(rate);
      k=0;
  }
  // LCD SCREEN (helpful hotlines message)
  {
    lcd.setCursor(0,1);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("1-800-273-8255");
    delay(1000);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("1-877-726-4727");
    delay(1000);
  }
  // BIG SOUND SENSOR
  {
    soundDetectedVal = digitalRead(soundDetectedPin);

    if (soundDetectedVal == LOW)
    {
      lastSoundDetectTime = millis();
      if (!bAlarm){
        Serial.println("you're doing great :)");
        bAlarm = true;
      }
    }
    else
    {
      if( (millis()-lastSoundDetectTime) > soundAlarmTime && bAlarm) {
        Serial.println("keep breathing");
        bAlarm = false;
      }
    }
  }
  // LCD SCREEN (are feeling better/listen to these sick tunes buddy message)
  {
    lcd.setCursor(0,1);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("if still need comfort");
    delay(500);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("hold button");
    delay(1000);
    }
    //PUSH BUTTON AND BUZZER
    {
      val = digitalRead(inPin);
      if (val == HIGH) {
        digitalWrite(buzzer, LOW);
      } else {
        digitalWrite(buzzer, HIGH);
      }
      }
// BUZZER
{{
  sing(1);
  sing(1);
  sing(2);
  }
  int song = 0;
   void sing(int s) {
    song = s;
    if (song == 1) {
      Serial.println("recognize this?");
      int size = sizeof(hotlineb_melody) / sizeof(int);
      for (int thisNote = 0; thisNote < size; thisNote++) {
        int noteDuration = 1000 / hotlineb_tempo[thisNote];

        buzz(melodyPin, hotlineb_melody[thisNote], noteDuration);

        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);

        buzz(melodyPin, 0, noteDuration);
      }
    }
  }
  {
    void buzz(int targetPin, long frequency, long length) {
      digitalWrite(13, HIGH);
      long delayValue = 1000000 / frequency / 2;
      long numCycles = frequency * length / 1000;
      for (long i - 0; i < numCycles; i++) {
        digitalWrite(targetPin, HIGH);
        delayMicroseconds(delayValue);
        digitalWrite(targetPin, LOW);
        delayMicroseconds(delayValue);
      }
      digitalWrite(13, LOW);
          }
        }
      }
    }
  }
}

```

# Answer
> 2 votes
Here are the problems I found while trying to make your code compile:

## Opening and closing braces should match

Trying to autoformat your code gave me the error:

> Auto Format Canceled: Too many right curly braces.

I had to remove the last two braces for Auto Format to succeed.

## Functions cannot be nested

You should move the declarations of `sing()` and `buzz()` out of `loop()`. You can **call** them from `loop()` though.

## Other random errors

* `#define sing` is defining `sing` as an empty string, and you cannot give a function an empty name
* the variable `song` should be either global or local to `sing()`, not local to `loop()`
* to declare and initialize a variable to zero you should write `int i = 0`, not `int i - 0`
* `soundAlarmTime` should be unsigned
* `oldChange` and `time` should be removed (they are not used)

---
Tags: programming
---


# Question
Title: delete the memory or re-upload a program
At the moment I am following the instructions of this project https://github.com/JoernL/LimiTTer. Besides the peripheral parts like a Bluetooth module and an NFC module, the central unit is an Arduino Pro Mini. I am a bloody novice with Arduino and just taught myself how to solder stuff. So far, I successfully uploaded the program from the project above to the Arduino Mini Pro and will continue as soon as the other parts arrive.

Anyhow, since I am strictly following the instructions I have some serious knowledge gaps and hope you can help me out. So, for instance.

* How do I know, how much storage capacity is available on the Arduino board before and after I uploaded something?
* How can I delete a program from the Arduino board?
* When I upload a program, will the program that is already on the Arduino been overwritten?
* Is an Arduino generally used to execute one specific program and not to hold a set of totally different programs?

# Answer
> How do I know, how much storage capacity is available on the Arduino board before and after I uploaded something?

In yellow is how much bytes does your program take.

In purple is how much bytes are available on your board.

In green is how many bytes does your **global** variables take.

In orange is how many bytes are left for **local** variables.

In blue is how many bytes are available for **all** of your variables.

In red is the general specs of your board and to which COM port it is connected to.

---

> How can I delete a program from the Arduino board?

Once a new program is uploaded, the old one is deleted (somewhat). Still, you get all your bytes back and it is like if you start from scratch

---

> When I upload a program, will the program that is already on the Arduino been overwritten?

Yes.

---

> Is an Arduino generally used to execute one specific program and not to hold a set of totally different programs?

An Arduino can only execute 1 program at the time. It doesn't usualy hold on to any other programs, but can store 1024 bytes in it's EEPROM. This lets your write in the EEPROM with a program and access that data with an other.
> 0 votes

---
Tags: arduino-ide, arduino-pro-mini
---


title: Is there a counter library in Arduino?

text:
# Question
Title: Is there a counter library in Arduino?
I'm looking for a counter that can be incremented and will overflow with predictable behavior, preferably reset to 0 on overflow. I've tried using integers for counting but I'm getting weird overflow issues. Is there some library that provides an implementation of a counter?

# Answer
Since you dont give the largest number your counter over flows at. You may want to look at libraries that implement arbitrary size integers. This means that there the integers can be bigger than usual - You would need to implement a counter, reset to 0 if the integer gets too big (just use a if statement if what youre doin is that simple-it sounds like it). So its entirely predictable for your purpose (whatever that is you didnt state). If you google around you will find libraries for arbitrary large integers for arduino e.g.

https://forum.arduino.cc/index.php?topic=85692.0

a library by Nick Gammon.
> 1 votes

---
Tags: arduino-mega, library, core-libraries
---


title: Unexpected Delay Between For Loops

text:
# Question
Title: Unexpected Delay Between For Loops
I made some arduino code for leds that blink down a row and then back again, but when the program is run, there is an approximately 2 second delay in between the first for loop and the second. This is my code in the loop function:

```
int leds[] = {13, 12, 11};
int i;

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

  for (int i = 0; i < sizeof(leds); i ++) {
     pinMode(leds[i], OUTPUT);
  }
}

void loop() {
    for (i = 0; i < sizeof(leds); i ++) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
    for (i; i > 0; i --) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
}

```

It really makes the program look weird when the LEDs are blinking on a breadboard. Keep in mind that this only happens after the first for loop, the second is continuous back to the first. Any idea why this might be and how to fix it?

# Answer
> -1 votes
The cause it that your 3rd led (2nd element in the array) is repeated twice.

Try this instead:

```
int leds[3] = {13, 12, 11};

void setup() {
  for (int i = 0; i < 3; i++) {
    pinMode(leds[i], OUTPUT);
  }
}

void loop() {
  for (int i = 0; i < 2; i++) {
    digitalWrite(leds[i], HIGH);
    delay(250);
    digitalWrite(leds[i], LOW);
  }
  for (int i = 2; i > 0; i--) {
    digitalWrite(leds[i], HIGH);
    delay(250);
    digitalWrite(leds[i], LOW);
  }
}

```

# Answer
> 5 votes
The claim “The cause it that your 3rd led (2nd element in the array) is reapeted twice” is wrong.

Apparently that sentence is supposed to mean that the long delay is due to `i` being one too large, coming out of the first loop and entering the second one. Indeed, `i` *is* too large, but that's because each element of the array is a 2-byte `int`, so that instead of `for (int i = 0; i < sizeof(leds); i ++)` being equivalent to `for (int i = 0; i < 3; i ++)`, it is equivalent to `for (int i = 0; i < 6; i ++)`.

Thus, one second goes by with an extra 4 occurrences of `delay(250);` in the first loop, and another one second with 4 extra occurrences of `delay(250);` in the other loop.

To correct the problem, write `sizeof leds/sizeof leds[0]` instead of `sizeof(leds)`, and write for `(--i; i > 0; i--)` instead of `for (i; i > 0; i --)`.

# Answer
> 1 votes
The problem is on "for loops" condition,
Try this:

```
int leds[] = {13, 12, 11};
int i;

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

  for (int i = 0; i < (sizeof(leds)/sizeof(leds[0])); i ++) {
     pinMode(leds[i], OUTPUT);
  }
}

void loop() {
    for (i = 0; i < (sizeof(leds)/sizeof(leds[0]); i ++) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
    for (i=((sizeof(leds)/sizeof(leds[0])-1); i>=0; i --) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
}

```

---
Tags: arduino-uno, led, resistor
---


# Question
Title: Why does pulse sensor shows gaps when I move it?
I modified the serial code in this way and I don't think the gap is produced by my edit even because it made it even before:

```
//////////
/////////  All Serial Handling Code,
/////////  It's Changeable with the 'serialVisual' variable
/////////  Set it to 'true' or 'false' when it's declared at start of code.
/////////

void serialOutput(){   // Decide How To Output Serial.
 if (serialVisual == true){
     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
 } else{
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
 }
}

//  Decides How To OutPut BPM and IBI Data
void serialOutputWhenBeatHappens(){
 if (serialVisual == true){            //  Code to Make the Serial Monitor Visualizer Work
    //ASCII Art Madness
    Serial.print(BPM);
    Serial.println("");

 } else{
        sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
        sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
 }
}

//  Sends Data to Pulse Sensor Processing App, Native Mac App, or Third-party Serial Readers.
void sendDataToSerial(char symbol, int data ){
    Serial.print(symbol);

    Serial.println(data);
  }

//  Code to Make the Serial Monitor Visualizer Work
void arduinoSerialMonitorVisual(char symbol, int data ){
  const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 1024;    // sensor maximum, discovered through experiment

  int sensorReading = data;
  // map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);

  // do something different depending on the
  // range value:
  switch (range) {
  case 0:
    Serial.println("");

  }
}

63

63
63
63
63
62
62
62
62
62
62
62
63
62
63
64
63
63
64
64
65
65

65
68
74
78
86
95
105
112
123
141
167
154
136
128
123
125
123
127
132
104
93
92
92
89
83
77
73
69
65
70
70
71

```

You can find all the code here: https://github.com/WorldFamousElectronics/PulseSensor\_Amped\_Arduino

In the code I posted there is some code I don'f find useful but I can't delete it for reason linked to variables used for other functions I don't know I'm using. You can also see huge changes in the heart rate that surely don't reflect the reality.

# Answer
> 1 votes
One of the possibilities is when you move your finger, the sensor grip loosened and doesn't count a "beat". So the sensor emits `data = 0`, and it will cause

```
Serial.println("");

```

in your switch-case.

---
Tags: arduino-uno, arduino-nano
---


# Question
Title: arduino + GSM/GPRS SIM 900A cannot able to read a message
Here I am using Arduino uno and GSM sim900A, I want to read sms from sim900A. But i am trying to read message, it is showing the empty values. I tried different methods, but no use. Here I have added my script. Please help me.

```
#include <avr wdt.h="">
String phoneSMS = "+91xxxxxxxxxx";
String messageTxt;
void setup()
{
Serial.begin(9600);
delay(60000);
srl_msg();
}
String srl_msg()
{
Serial.println("AT+CMGF=1\r");
delay(1000);
Serial.println("AT+CNMI=2,2,0,0,0");
delay(1000);
Serial.println("AT+CMGL=\"ALL\"\r"); // to read ALL the SMS in text mode
delay(1000);
char txtmsg2[100]; // AT command output
String date = readSerial(txtmsg2);
String value = date.substring(1, 50);
messageTxt = "Internal - Heart Beat;";
messageTxt.concat(value);
Serial.println(value);
SendSMS(messageTxt);
}
void loop()
{
}
void SendSMS(String message)
{
Serial.print("at+cmgf=1\r");
delay(1000);
Serial.print("at+cmgs=\"");
Serial.print(phoneSMS);
Serial.println("\"");
delay(1000);
Serial.println(message);
delay(1000);
Serial.print((char)26);
delay(15000); // AAN
}
String readSerial(char result[])
{
int i = 0;
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar != '\r')
{
result[i] = inChar;
i++;
}
}
return result;
}

```

output is look like this: AT+CMGF=1

OK

AT+CNMI=2,2,0,0,0

OK
AT+CMGL="ALL"

OK

# Answer
Check you sim card inbox. I also had the same problem, and it turns out the sim card sms inbox capacity is full.
You can also try to use another library, here is one of them
> 1 votes

# Answer
wdt.h is just time handling data library, and have no methods for *send* or *receive* sms...

Your method: `SendSMS(String message)`

is just printing serial labels and counting a char that you are putting in the serial monitor.

Try this GSM example...
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to turn a LED if ultranonic HC-SR04 reading is on defined range for some interval
My objective is if ultrasonic readings ranging between 1 to 10 cm and no distance change for 10 seconds or more, a LED will turn on. Here is my current code.

```
#define trigPin 7
#define echoPin 8
#define led 13
#define led2 12

long duration, distance, interval = 4000;
int detection = 0;

void setup() {
   Serial.begin (9600);
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
   pinMode(led, OUTPUT);
   pinMode(led2, OUTPUT);
   detection = millis();
}

void loop() {

   ultraSonic();

   if (distance > 0 && distance < 10 && (millis() - detection >= interval)) {
   digitalWrite(led, HIGH);
   digitalWrite(led2, LOW);
   } else {
   digitalWrite(led, LOW);
   digitalWrite(led2, HIGH);
   }

   Serial.print(millis());
   Serial.print(" - ");
   Serial.println(distance);

   delay(250);
}

void ultraSonic() {
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration / 2) / 29.1;
}

```

Sorry for my bad english. Cheers.

# Answer
> 1 votes
Based on previous answer and your comment, maybe you can try this one
I assume if the range is ranging 1-10 cm for 10 secs or more the led will turn on:

```
void setup() {
   Serial.begin (9600);
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
   pinMode(led, OUTPUT);
   pinMode(led2, OUTPUT);
}
int togle = 0;

void loop() {

   ultraSonic();

   if ((distance >= 1) && (distance =< 10)) //dont use (distance>0)
   //there are possibility you get 0.xx distance
   {
     Serial.print("Distance on range - ");
     if (toggle == 0)
       {
        toggle=1;
        detection=millis();
        Serial.println("last detection outside range");
       } else
     if (toggle == 1)
     {
        Serial.print("last detection in range - ");
        if ((millis()-detection) >= interval)
            {
             Serial.println("objective complete");
            }
        else Serial.println("not enough interval");
     }
   } else
   {
     //turn off the led
     Serial.println("Distance out of range");
     toggle = 0;
   }

}

void ultraSonic() {
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration / 2) / 29.1;
}

```

Feel free to tell if something is not right

# Answer
> 1 votes
```
void loop() {

   ultraSonic();

   if ((distance > 0) && (distance =< 10)) {
   digitalWrite(led, HIGH);
   digitalWrite(led2, LOW); // turning LED on
   } else {
   digitalWrite(led, LOW);
   digitalWrite(led2, HIGH); // turning LED off
   }

   Serial.print(millis());
   Serial.print(" - ");
   Serial.println(distance);

   delay(250);
}

```

---
Tags: arduino-uno, led, hc-sr04
---


# Question
Title: Record Ping time using ultrasonic sensors and calculate speed
I'm trying to find the speed of remote control toy car passing by two ultrasonic sensors. I need help on my code and suggestion on max speed car should go to record time. Opposite direction not accounted for and ideally the car would pass by both sensors without stopping. I know laser reading is better for this simulation but I need it for a presentation in two weeks.

Here are the steps I was recommended to use:

1. Get the duration of pulse for sensor 1 and convert to distance
2. if the distance the object is within the desired threshold (you detected something) 2a. record the system time at which object was detected 2b. start a loop to for sensor 2
3. Within the sensor 2 loop keep getting the duration/distance until an object is detected or too much time has passed
4. If an object is detected record the system time
5. Subtract the two system times (from sensor 1 and 2) and use that to determine object speed

```
#define sensor_distance .111 //distance between two sensors in meters
const int trigPin1 = 3;
const int echoPin1 = 4;
const int trigPin2 = 5;
const int echoPin2 = 6;

double first_time = 0;
double second_time = 0;
double final_time = 0;

double vehicle_speed = 0;

void setup() {

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  Serial.begin(9600);
}

void loop() {

double ping_time(int trig1, int echo1, double first_time);
double ping_time(int trig2, int echo2, double second_time);

final_time = second_time - first_time;
vehicle_speed = sensor_distance/final_time;
}

double ping_time(int trig, int echo, double record_time) //function used to record time.
{
  long duration, distance;

   digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);

  duration = pulseIn(echo, HIGH);
  distance = duration * 0.034 / 2;

  if (distance < 35) {
    Serial.print(distance);
    Serial.println("  cm");
    record_time = millis();
    record_time = record_time/100; //Divided by 100 to get time in seconds

    return record_time;

  }
  if (distance > 35) {
    Serial.println("OUT OF RANGE");
  }
  delay(20);
}

```

# Answer
> 1 votes
You can try this, but I don't know if this gonna works or not since it is "imaginary-based"

```
const int trigPin1 = 3;
const int echoPin1 = 4;
const int trigPin2 = 5;
const int echoPin2 = 6;

void setup() {

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  Serial.begin(9600);
}

void loop()
{
    if (ultraSonicdetect())
    {
        while (ultraSonicdetect(trigPin1,echoPin1)); // wait the car pass ultrasonic 1
        first_time = millis();
        while (!ultraSonicdetect(trigPin2,echoPin2)); //wait the car approach ultrasonic 2
        second_time = millis();

        //here you can calculate the speed, time needed to travel from ultrasonic 1 to ultrasonic 2
        //can be calculated from
        //(speed = second_time - first_time) / sensor range
    }
}

bool ultraSonicdetect(int trig, int echo) {
   long duration;
   float distance;
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration * 0.034) / 2;
   if (distance<35) return true; else return false;
}

```

# Answer
> 0 votes
In **THEORY**, this code should work. If there are any mistakes, please notify me and not hate on me. I did not have the equipment at hands to test the code in real life.

Chears!

```
const int trigPins[2] = {3, 5}; //trig1 and trig2
const int echoPins[2] = {4, 6}; //echo1 and echo2

const int sensorDistance = 7;   //7 is the cm distance at which the sensors distant from eachother in CM

void setup() {
  pinMode(trigPins[0], OUTPUT); //set trig pin 1 as output
  pinMode(echoPins[0], INPUT);  //set echo pin 1 as input
  pinMode(trigPins[1], OUTPUT); //set trig pin 2 as output
  pinMode(echoPins[1], INPUT);  //set echo pin 2 as input

  Serial.begin(9600);
}

void loop() {

  if (getDistance(0) == true)                   //if the car passed the first sensor
  {
    unsigned long currentMillis = millis();               //time when the passed the first sensor

    while (getDistance(1) == false);            //wating car to pass the second sensor

    unsigned long endMillis = millis();                   //time at which the car passed the second sensor

    unsigned long timeMillis = endMillis - currentMillis; //get duration in ms
    float timeSeconds = timeMillis / 1000.0;        //because 1000ms = 1s

    float s = sensorDistance / timeSeconds;       //speed = distance / time

    Serial.print(s);
    Serial.print(" cm/s");
    Serial.println();
  }
}

bool getDistance(int sensor)
{
  //max range is 200cm, if further, it will go a little wild

  digitalWrite(trigPins[sensor], LOW); //set the trigger pin to low
  delayMicroseconds(2); //wait for 2 microseconds
  digitalWrite(trigPins[sensor], HIGH); //set the trigger pin to high
  delayMicroseconds(10); //wait for 10 microseconds
  digitalWrite(trigPins[sensor], LOW); //set the trigger pin to low

  long duration = pulseIn(echoPins[sensor], HIGH); //read the echo pin and calculate the duration in microseconds

  long distance = duration * 0.034 / 2;

  if (distance < 50) //50 is a reasonable distance other wise it might be innacurate
  {
    return true;
  }

  else
  {
    return false;
  }

}

```

---
Tags: sensors
---


title: Blank.txt at the End of Transmission

text:
# Question
Title: Blank.txt at the End of Transmission
I'm using my HC-05 (Master) to receive strings from a sensor (Slave), each string is suppose to have 7 items divided by ',' like so "a,b,c,d,e,f,g". I also have to write these strings in a .txt file in the SD card, being that I receive the strings and save them in a string array to later be written to a file. For some reason I can't receive it and write it to a file simultaneously, it alters the string. So the best way would be an array but when i open the file it's blank and when I print it on screen it starts correctly then prints only the first char of what would be the string. I tried it with 80 strings and it works correctly, so I can only guess it would be insufficient memory, But wouldn't it still write to the file since there is something in the strings.

PS:I'm using Arduino Mega

```
#include <SD.h>

const int tam=480;
char aux;
File myFile;

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

void openSD()
{
  SD.begin(4);
  if( SD.exists("test.txt") )
  {
    Serial.println("O arquivo de amostras sera removido");
    SD.remove("test.txt");
      if( !SD.exists("test.txt") )
        Serial.println("Arquivo removido com sucesso!");
  }
  myFile = SD.open("test.txt", FILE_WRITE);
}

void Capture()
{
  String test[tam];
  openSD();
  Serial.println("BEGIN");
  for(int i=0;i<tam;i++)
  {
    test[i]="";
    do
    {
      while(!Serial1.available());
      aux=Serial1.read();
      test[i]+=aux;
      Serial.print(aux);
    }while(aux!='\n');
  }
  Serial.println("END");
  for(int i=0;i<tam;i++)
    myFile.print(test[i]);
  myFile.close();
}

void loop() {

}

```

# Answer
Rules of sequential file is : **It's saved when its closed,** which mean if the file not closed properly, anything written before will not saved, and you'll get blank file.

so, if you get a blank file while you are sure that the data is received, the only possibility is your program doesn't reach

```
myFile.close();

```

one of the possibility is the received data not fit into your memory, so the '\n' is undetected.
> 1 votes

---
Tags: arduino-mega, sd-card, string
---


# Question
Title: Entering integers as bytes in serial monitor
I am doing some byte manipulation in Arduino, but when I enter an integer into the serial monitor, such as `1`, and my program stores it as `byte incomingByte`, the value stored in `incomingByte` is 49 and not `1`. How do I enter the ASCII equivalent of an integer?

# Answer
> 3 votes
Using the Arduino IDE Serial Monitor, there's not much you can do. But you can use a different serial-port terminal such as RealTerm (for Windows, if that's your thing) which allows for a wide array of serial port nitty-gritty details.

# Answer
> 2 votes
Check out the ASCII table.

When you enter `1` into the Serial Monitor you are telling it to send the (ASCII) *character* `1` \- which is represented by the decimal value 49, so the `byte` that is sent is `49`.

I don't believe it is possible to enter the decimal value `1` into the Serial Monitor (you'd have to find some way of entering `SOH` via the keyboard), so the only option is to recognize and accommodate that on the Arduino end.

The usual way to do this is to subtract 48 from the received value. However this is typically written as `- '0'` which is actually *subtract the ASCII value of 0* (this helps indicate that you converting from ASCII)

So...

`int intVal = incomingByte -'0';`

... should work fine for you if you are receiving single digit integers. However, if you also want to accommodate multi digit integers (e.g. 123) then it becomes more complex requiring converting each byte to it's integer equivalent and then multiplying it by 10 to the power of it's position/column...

`123 = (1 * 10^2) + (2 * 10^1) + (3 * 10^0)`

This is a fun little coding task in itself, but if you're not into that kind of thing then `parseInt('123');` will get you going faster...

# Answer
> 1 votes
You can do this little trick:

```
void loop()
{
while (Serial.available() == 0); //waiting for input
int val = Serial.parseInt(); //read as integer
}

```

---
Tags: arduino-mega
---


title: Host name is unvalid

text:
# Question
Title: Host name is unvalid
I am trying to call a web service from a server but didn't get the correct response on Serial Monitor arduino, i get the error "hostname is invalid". Below is the code along with the result:

Thanks @Edgar Bonet, i have tried as you suggested. Following is the correction and the result, now the error is "The request verb is invalid" {

```
EthernetClient client1;

//second
int inChar;
char outBuf[64];
char params[65];

Serial.print(F("Method 2 connecting..."));

if(client1.connect("198.38.93.76",807) == 1)
{
Serial.println(F("connected"));

// send the header
client1.println(F("POST /JMS_Auth_WebService.asmx HTTP/1.1"));
client1.println(F("Host: 198.38.93.76"));
client1.println(F("Content-Type: text/xml; charset=utf-8"));
client1.println(F("Content-Length: 315"));
client1.println(F("Connection: keep-alive"));
client1.println(F("SOAPAction: \"http://jbscrms.com/GetThresholdOfDeviceForSaud\""));
client1.println();

client1.println(F("<?xml version=\"1.0\" encoding=\"utf-8\"?>"));
client1.println(F("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"));
client1.println(F("<soap:Body>"));
client1.println(F("<GetThresholdOfDeviceForSaud xmlns=\"http://jbscrms.com\">"));
client1.println(F("<Device_id>2</Device_id>"));
client1.println(F("</GetThresholdOfDeviceForSaud>"));
client1.println(F("</soap:Body>"));
client1.println(F("</soap:Envelope>"));

Serial.println(F("Done Calling New Web Service"));

}
else
{
Serial.println(F("failed"));

}

int connectLoop = 0;

while(client1.connected())
{

if(client1.available())
{
inChar = client1.read();

Serial.write(inChar);
connectLoop = 0;
}

delay(1);
connectLoop++;
if(connectLoop > 30000)
{
Serial.println();
Serial.println(F("Timeout"));
client1.stop();
}
}

Serial.println();
Serial.println(F("disconnecting."));
client1.stop();
}

```

Following is the result on Serial monitor arduino

```
Ready
Entered<R_TempData>29</R_TempData>
<R_smokeData>226</R_TempData>
<R_humidityData>36</R_TempData>
Method 2 connecting...connected
Done Calling New Web Service
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/xml; charset=utf

-8
    Server: Microsoft-IIS/8.5
    X-AspNet-Version: 4.0.30319
    X-Powered-By: ASP.NET
    Date: Fri, 11 Nov 2016 07:23:28 GMT

Content-Length: 0

HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 11 Nov 2016 07:23:28 GMT
Connection: close
Content-Length: 326

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Verb</h2>
<hr><p>HTTP Error 400. The request verb is invalid.</p>
</BODY></HTML>

disconnecting.

```

# Answer
1. I think you need a \r\n between the Post statement and the HTTP statement.
2. Why are you including the Port number in the Host name?
3. Your SOAPAction line is wrong, but I guess that's a typo in the post.
> 0 votes

---
Tags: arduino-uno
---


title: RH_RF24_MAX_MESSAGE_LEN in RH_RF24.h

text:
# Question
Title: RH_RF24_MAX_MESSAGE_LEN in RH_RF24.h
I use `RH_RF24.h` to control Si4463, and realize some simple communication between two Si4463 . But I don't know the mean of `RH_RF24_MAX_MESSAGE_LEN` in this example.

`RH_RF24_MAX_MESSAGE_LEN` is a constant ? If so , what decides it ? And if I need to sent and receive a long char string , how to do it ?

# Answer
> 1 votes
`RH_RF24_MAX_MESSAGE_LEN` is probably defined in the header file RH\_RF24.h.

It doesn't matter what size it is, you should always use `RH_RF24_MAX_MESSAGE_LEN` rather than the number because the value might change in the library and this will break your code if you have used the number.

If you want to send a message that is larger than `RH_RF24_MAX_MESSAGE_LEN` then you will need to 'fragment' the message (unless the library supports that). I would use the first byte of the message as the type of message and define one of those types as a multi part string. Then send a number of these message and reassemble the data on the receiver. When the receiver sees a message that contains a character with the ASCII value 0 then that is the end of the string.

---
Tags: library, communication, wireless
---


# Question
Title: Arduino Pro Mini automatically resetting
I have an Arduino Pro Mini 3.3v in a robot. The problem is, the Mini would automatically randomly overwrite the uploaded sketch with the default blink sketch... And this is becoming quite a problem.

I have connected the Arduino to a L293D Motor Driver and the Arduino gets its power from the motor driver only. It will work just fine, but randomly will reset to the blink sketch...

Please help

P.S- It automatically corrected after a while

# Answer
The most obvious cause for a reset is pulling to much current from the Arduino. I have never heard of an Arduino downloading a new sketch to itself. Is it possible you are seeing the board booting up and flashing the LED as its doing so?

If you are getting the power from the motor driver its possible you are either giving the board noisy/dirty power or the motor is pulling to much current and depriving the board of power. I would run them on separate supplies (with a common ground) to avoid this.
> 2 votes

---
Tags: arduino-ide, uploading, arduino-pro-mini
---


# Question
Title: Wiring and Connecting WS2801 to NodeMCU ESP8266
After hours of searching for a solution and try many ways of wiring, I must asking here for Help:

I'm using a ESP8266 (ESP-12E) with a WS2801 - 4 Wire LED Strip and using this Pinout-Diagram to connect WS2801 wires to NodeMCU.

https://alexbloggt.com/wp-content/uploads/2015/10/nodemcu\_pinout\_700.png

Here is my Wiring:

```
LED     ESP
====   =====
5V --> Vin
GND --> GND
CK --> GPIO2 (D4)
SI --> GPIO3 (RX)

```

I have found this sample Program which should turn on and off all LEDs one after each other for 100ms. But it happens nothing after compiling and uploading it to NodeMCU board using Arduino IDE. Any help is highly appreciated.

```
//This program was taken from the FirstLight.ino supplies with the FastLED library
// It has been modified for use with a NodeMCU for use in a tutorial by NQMakerSupplies.com.au
// Hosted at theMakers.org.
//
// Special thanks to the people behind FastLED.io and all the contributors :)

#define FASTLED_ESP8266_NODEMCU_PIN_ORDER   // map output pins to what they are called on the NodeMCU
#include "FastLED.h"

///////////////////////////////////////////////////////////////////////////////////////////
//
// Move a white dot along the strip of leds.  This program simply shows how to configure the leds,
// and then how to turn a single pixel white and then off, moving down the line of pixels.
//

// How many leds are in the strip?
#define NUM_LEDS 10

// Data pin that led data will be written out over
#define DATA_PIN 3

// Clock pin only needed for SPI based chipsets when not using hardware SPI
#define CLOCK_PIN 2

// This is an array of leds.  One item for each led in your strip.
CRGB leds[NUM_LEDS];

// This function sets up the ledsand tells the controller about them
void setup() {
    // sanity check delay - allows reprogramming if accidently blowing power w/leds
   delay(2000);
   FastLED.addLeds<WS2801, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

// This function runs over and over, and is where you do the magic to light
// your leds.
void loop() {
   // Move a single white led
   for(int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed = whiteLed + 1) {
      // Turn our current led on to white, then show the leds
      leds[whiteLed] = CRGB::White;
      // Show the leds (only one of which is set to white, from above)
      FastLED.show();
      // Wait a little bit
      delay(100);
      // Turn our current led back to black for the next loop around
      leds[whiteLed] = CRGB::Black;
   }
}

```

# Answer
> 2 votes
Changing the first line from

```
 #define FASTLED_ESP8266_NODEMCU_PIN_ORDER

```

to

```
 #define FASTLED_ESP8266_RAW_PIN_ORDER

```

has solved the Problem.

---
Tags: esp8266
---


# Question
Title: Serial Communication Between 3 Arduinos Doesn't Work (Daisy-Chain)
In my project, I have to send a string from one arduino to a second arduino, and make it send the same string to a third arduino. I used UART and SoftwareSerial library, and connected the arduinos like that:

**In all the arduinos:** Pin 10 - RX port, pin 11 - TX port  Arduino 1 pin 11 ----\> Arduino 2 pin 10 Arduino 2 pin 11 ----\> Arduino 3 pin 10 Arduino 3 ----\> PC (by hardware Serial)

**By theory**, Arduino 1 sends string "CA" to arduino 2, which resends that same string to arduino 3, that prints it back on Serial.

**The problem** is that I get the string "C�" instead of "CA" (that weird "C�" is equal to "067 255" on ASCII). Does anyone knows why it happens? Maybe there's something wrong with my code?

Here's the code for all the three Arduinos:

*Arduino No. 1:*

```
#include <SoftwareSerial.h>

#define ADDR "CA"
SoftwareSerial tiny(10, 11); //TBD

void setup() {
  Serial.begin(9600); //debug only
  tiny.begin(9600);
  delay(2000);

  tiny.write(ADDR);
}

void loop() {
  //nothing here
}

```

*Arduino No. 2:*

```
#include <SoftwareSerial.h>
SoftwareSerial tiny(10, 11); //TBD
void setup() {
  Serial.begin(9600); //debug only
  tiny.begin(9600);
}
void loop() {
  if(tiny.available() > 0) {
    tiny.write(tiny.read());
  }
}

```

*Arduino No. 3:*

```
#include <SoftwareSerial.h>
SoftwareSerial tiny(10, 11); //TBD
void setup() {
  Serial.begin(9600); //debug only
  tiny.begin(9600);
}
void loop() {
  if(tiny.available() > 0) {
    Serial.write(tiny.read());
  }
}

```

Any idea on what went wrong?

# Answer
Arduino #2 should have two SoftwareSerial instances, one to listen to Arduino #1 and another one to talk to Arduino #3:

```
// In Arduino #2
SoftwareSerial tiny1(10, 11); // Listen to Arduino #1 on pin 10
SoftwareSerial tiny2(8, 9);   // Talk to Arduino #3 on pin 9

```

You may not need to wire unused signals (11 and 8).

There is an example here : https://www.arduino.cc/en/Tutorial/TwoPortReceive

Note that what you are trying to do is a bus. Serial in Arduino is RS232 based and that is not a bus but a point to point protocol. You should consider using I²C or SPI.
> 2 votes

---
Tags: arduino-uno, serial, uart
---


title: Arduino creating delay function

text:
# Question
Title: Arduino creating delay function
I am trying to make my own delay function. Briefly `mydelay` function is calling `toggled` function every `secs` seconds. The code is not well written, i know (this is the first version). But i am just trying to get it work properly. Then i will refactor it. But i have some unexpected bugs. First time the loop in `x` function is working properly. It is printing "I am in while" for 1 second and then it prints "Im ending mydelay" which is the behaviour i want. But after finishing the loop in `x`. The second time when it loops. It enters the `mydelay` function (that is ok). But then it is not printing "I am in while" at all. It just prints "Im ending mydelay" which is not good.

Here is the code:

```
#include <Arduino.h>
int led = 7;
void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  x();
  Serial.println("Im ending main loop");
}

void x() {
  for (int i = 0; i <= 10; i++) {
    mydelay(led, 0, 1);
    mydelay(led, 1, 1);
  }
}

void mydelay(int pin, int hol, int secs) {
  int starttime = millis();
  while ((millis() - starttime) <= (secs * 1000)) Serial.println("I am in while");
  toggled(pin, hol);
  Serial.println("Im ending mydelay");
}

void toggled(int pin, int hol) {
  digitalWrite(led, hol);
}

```

# Answer
As mentioned in the comments, your main problem is you declare `starttime` as an `int`. This is a signed value with a range of -32,768 to 32,767. You will quickly overflow - in about 32 seconds.

The solution is to use an `unsigned long` which has a range of 0 to 4,294,967,295.
> 2 votes

# Answer
You can try something along these lines:

```
void verboseDelay(unsigned long ms)
{
    unsigned long now = millis();
    Serial.print(F("delaying"));
    unsigned long start = now, lastPrintTime = now;
    do {
        now = millis();
        if (now - lastPrintTime >= 20) {
            Serial.write('.');
            lastPrintTime += 20;
        }
    } while (now - start < ms);
    Serial.println();
}

```

The trick is to used `unsigned long` for all the time-related variables, and also to avoid printing too fast.
> 3 votes

---
Tags: c, time
---


title: Arduino Unreliable Serial communication

text:
# Question
Title: Arduino Unreliable Serial communication
After reading the following 2 articles:

https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

I have get rid of the complete String class from my main program and went back to using character arrays. This seems to work reliably until some extent but once I start stress testing it, quickly turns out that it is not reliable at all!

Here is the complete code, you can load it into the mega and it will produce the same results (I have removed all other unnecessary parts from the code):

```
#define DEBUG

char Command_PC[64], Command_Xbee[64], Command[64];
int count=0;
bool Complete_PC=false;
bool Complete_Xbee=false;

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

} // END void setup

void comm() {

/* COMM FROM PC */
if (Serial.available()){

  #ifdef DEBUG
    Serial.println("PC: New command, collecting...");
  #endif
    count = 0;
    memset(Command_PC, 0, sizeof(Command_PC));
    while (Serial.available()){
      char character = Serial.read();
      if (character=='\n')
         {
          Complete_PC =true;
          break;
         }
      Command_PC[count] = character;
      count++;
    }
  }

/* COMM FROM Xbee */
if (Serial1.available()){
  #ifdef DEBUG
    Serial.println("Xbee: New command, collecting...");
  #endif
    count = 0;
    memset(Command_Xbee, 0, sizeof(Command_Xbee));
    while (Serial1.available()){
      char character = Serial1.read();
      if (character=='\n')
         {
          Complete_Xbee =true;
          break;
         }
      Command_Xbee[count] = character;
      count++;
    }
  }

   delay(500);

 if (Complete_Xbee || Complete_PC) {

  if(Complete_Xbee)
    strcpy(Command, Command_Xbee);
  else
    strcpy(Command, Command_PC);

  #ifdef DEBUG
    Serial.print("Command received: >");
    Serial.print(Command);
    Serial.println("<");
  #endif
           Complete_Xbee=false;
           Complete_PC=false;
 }

}

void loop()
{
    comm();

} // END void loop

```

The code is simple, all it is intended to do that whether there is a command coming from the PC (USB) or Xbee (attached to hardware uart) process it and do further things. As long as you typing in commands manually it goes reliably for a while but even then after 10-15 commands it might screws up. The automated testing with:

**`for ((;;)); do echo HELLOWORLD > /dev/ttyACM0; done`**

```
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORL<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLDELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWOD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWOLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWOLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWLD<
ERR_INVALIDCMD
PC: New command, collecting...

```

Brings out the bug right away. Is there any problem with this code? Any ideas how to make this 100% reliable even if it takes slowing the main program down?

I have noticed that by adding: `delay(500);` it makes it more stable. If this is not there it will even fail on the first manually entered command like:

```
PC: New command, collecting...
PC: New command, collecting...
PC: New command, collecting...
Command received: >lloworld<

```

By adding a delay to my test script:

**`for ((;;)); do echo HELLOWORLD > /dev/ttyACM0 && sleep 1; done`**

It runs stable for a while but after 15 mins testing it start misbehaving again:

```
Command received: >HELLOWORLD<
PC: New command, collecting...
Command received: >HELLOWORLD<
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><

```

# Answer
> 3 votes
To me, your problem is because the program is reading the characters faster than they are sent by the computer. Then, some situations occur where all the characters of the buffer have been read (`Serial.available() = 0`) but the `'\n'` character has not been sent by the computer yet. The program will then exit the loop without setting the `Complete_PC` variable to true.

In that case, the program will write several times "PC: New command, collecting..." without writing any result (Complete\_PC not set to true). It can also drop the first letters, as they were read during the previous loop and the `Command_PC` array and count were reset in between.

The `delay(500)` command improve the stability because it increase the chances that the whole line is received when the program is not reading it at the same time.

Try something like this:

```
while ((!Complete_PC)&&(count<60))
{
    int character = Serial.read();
    if (character=='\n')
    {
        Complete_PC =true;
    }
    else if (character!=-1)
    {
        Command_PC[count] = (char) character;
        count++;
    }
}

```

# Answer
> 1 votes
As @Edesign has mentioned your reception methodology is slightly flawed. A better arrangement would be:

```
static int Count_PC = 0;
static bool Complete_PC = false;

if (Serial.available()) {
  char character = Serial.read();
  if (character=='\n') {
    Complete_PC =true;
    Count_PC = 0;
  } else {
    if (Count_PC < 62) { // Don't overflow the array...!
      Command_PC[Count_PC++] = character;
      Command_PC[Count_PC] = 0;
    }
  }
}

```

The count and complete flags are now static - that is, they retain their values between iterations of the loop. You only look at one character per iteration of the loop (you could enhance it by changing the first `if` to a `while` if you like, but this way plays better with handling multiple data sources), and add that to the string. Only when the `\n` is received do you flag it as complete. There is no clearing of the whole array, it's not needed - just ensure that you always add a `\0` to the end of the string each time you add a character.

The current character position (`Count_PC`) is reset when you receive the `\n` so that it is ready to receive the next command - be sure that you process the command that same loop (which you do anyway).

# Answer
> 1 votes
@Edesign, @Majenko: thank you for your help, it turns out that the hardware DOES matter as well. It was partially a **hardware issue**. Regarding my initial code, you can get that code remove the delay(500); from it and load it into an Arduino Leonardo and it will pass my first initial stress test without any delays and it works stable even after an hour testing.

I believe that both the Mega and the Leonardo have USB2 connections:

Bus 001 Device 003: ID 2341:0042 Arduino SA Mega 2560 R3 (CDC ACM) Bus 003 Device 013: ID 2341:8036 Arduino SA

Although this is was a *Keyestudio MEGA*, a cheap chinese counterfeit which would explain why did it have this issue. My initial code was not wrong but as you have pointed out it could have been improved, what I did.

Code1:

```
static int Count_PC = 0;
static bool Complete_PC = false;

if (Serial.available()) {
  char character = Serial.read();
  if (character=='\n') {
    Complete_PC =true;
    Count_PC = 0;
  } else {
    if (Count_PC < 62) { // Don't overflow the array...!
      Command_PC[Count_PC++] = character;
      Command_PC[Count_PC] = 0;
    }
  }
}

```

Code2:

```
/* COMM FROM PC */
if (Serial.available()){

  #ifdef DEBUG
    Serial.println("PC: New command, collecting...");
  #endif
    memset(Command_PC, 0, sizeof(Command_PC));
    while (Serial.available()){
      char character = Serial.read();
      if (character=='\n')
         {
          Complete_PC =true;
          Count_PC = 0;
          //break;
         } else {
             if (Count_PC < 62) { // Don't overflow the array...!
                 Command_PC[Count_PC++] = character;
                 Command_PC[Count_PC] = 0;
             }
         }
  }
}

```

The difference between his code and my last code is that I do the while looping inside the function while his relies on the main loop cycles to complete the string.

Both are working but if the main program have a lot to do, his version will noticeably make the responses more sluggish. Which can be easily tested with:

```
 for ((;;)); do date > /dev/ttyACM0; done

```

---
Tags: serial, communication
---


title: Capacitors in DC circuits

text:
# Question
Title: Capacitors in DC circuits
I have a question about capacitors in DC (digital) circuits. The picture below is an edited schematic of the Arduino Uno R3.

The DTR line is connected to the reset input of the Atmega328 by a 0.1uF capacitor.

The capacitor is needed to initiate a load to the atmega flash memory through the USB -\> UART. Why is this the case, everything I have been taught says "Capacitors block DC and let AC through"

All I see is something that can let AC noise through to the Arduino reset? I know its needed, I tested it. But why its needed, how it fulfils that function I have no idea.

Please help

# Answer
> 2 votes
The Atmel datasheet, page 305, Section 29.5 "System and Reset Characteristics" provides some useful information for the reset pulse. It says that the worst-case minimum pulse width is \\$2.5\\:\mu\textrm{s}\\$. It then goes on to say that the ramp rate has to be contained between two boundaries; no faster than \\$10\\:\frac{\textrm{kV}}{\textrm{s}}\\$, but also no slower than \\$10\\:\frac{\textrm{V}}{\textrm{s}}\\$. So there are some restrictions that should be managed by any reset system.

There are some nice reset circuit ICs available which provide a manual reset input as well as a control line. I'd probably use one of those about a circuit I cared about. Okay. Actually, I'd make my own out of a PIC10LF320 in a SOT-23-6, which also includes a brown-out circuit of its own, which I'd probably also re-purpose, as well.

But let's look at this circuit. DTR is normally held HIGH (I believe) and is pulled LOW in order to initiate a reset. Assuming that the two MCUs are running on different power rails (or the same, doesn't matter), \\$C\_5\\$ is charged up to the difference between the ATmega328's rail (via \\$RN\_1\\$ and the DTR output line's HIGH value.) If there is no difference, the voltage will be nearly zero. But if the rails are different, then there will be a small voltage across \\$C\_5\\$ that represents this difference.

When DTR is pulled LOW, that end of \\$C\_5\\$ is also pulled down to that voltage (close to ground.) For the first moments, this also means that the other side of \\$C\_5\\$ is similarly pulled downwards, too. If there was some voltage rail difference, then that's the voltage that appears at the reset pin of the ATmega328. Depending on the voltage differences between the MCUs and the reset pin requirements of the ATmega328, this could be a problem. The datasheet says that it may be required to be as low as \\$600\\:\textrm{mV}\\$, though the typical only requires to be pulled down to \\$1.3\\:\textrm{V}\\$. But if no difference in the rails, then hopefully near-ground appears at the reset pin of the ATmega328. I'm going to assume there is no difference, here, so that we at least have a good chance it works okay.

Now, as soon as \\$C\_5\\$ is yanked down by DTR, \\$C\_5\\$ begins charging up through \\$RN\_1\\$, starting at a rate of about \\$500\\:\mu\textrm{A}\\$. The time constant is \\$1\\:\textrm{ms}\\$. So the voltage will rise rapidly. Assume that we only just barely achieved the required \\$600\\:\textrm{mV}\\$ at the start (the capacitor held a slight charge.) Then we'd cross over the minimum rising threshold of \\$1.1\\:\textrm{V}\\$ within about \\$100\\:\mu\textrm{s}\\$. This is well more than long enough for the earlier mentioned minimum reset pulse width of \\$2.5\\:\mu\textrm{s}\\$. So the spec is met here.

Now, let's go the other direction. Let's say that now DTR is held LOW for a long enough time that it charges up to about \\$5\\:\textrm{V}\\$ through \\$RN\_1\\$. Now, DTR is driven HIGH. What happens? Well, the other side of \\$C\_5\\$ will now be at about \\$10\\:\textrm{V}\\$ (the \\$5\\:\textrm{V}\\$ charge on \\$C\_5\\$ added to the DTR HIGH voltage value.) This is rapidly discharged, safely, via \\$D\_2\\$. That's why \\$D\_2\\$ was added. Otherwise, this voltage would be presented to the RESET pin of the ATmega328 and would have to be discharged via any internal protection diodes present there (which may themselves have additional specifications that must be met.)

What's interesting here is that the RESET pin in particular is called out in the datasheet on page 299. It says that it can support up to \\$13\\:\textrm{V}\\$ worst case. So, technically, that might mean that \\$D\_2\\$ isn't necessary to avoid driving protection diodes in the CPU. But it is still a good idea for an entirely different reason. This is to discharge \\$C\_5\\$ rapidly (it would be very slow, via \\$RN\_1\\$), so that it can be used for another reset very soon after being used.

---

Note on the reset pin:

As Majenko added in a comment, there is a high voltage programming mode for Atmel devices like this. I frankly don't fully apprehend it, as I haven't read a datasheet on the topic. But I did find out from an Atmel video that the PC6/RESET line, which normally acts like a /RESET line, can be changed into operating like a general purpose I/O port by changing the RSTDISBL fuse, which makes the general I/O function available. The bad thing about that is that the ISP programming mode NEEDS the /RESET line to do its job. So you can't program the device anymore, if you set up that fuse. This then forces you to use the parallel programming mode that is entered using the high voltage programming mode. I would guess that entering this mode uses the /RESET pin again, but this time places a high voltage on it that is detected in order to put the device into its parallel programming mode instead of the ISP programming mode.

I can't readily find a specific programming document on the details of using this mode to program their devices. Microchip publishes them. But it appears, cursory examination only, that Atmel does not. They document how to use the mode with their tools, such as the STK500 (which I have.) But not how to design your own tool. I'm guessing, for now, that this is a matter of non-disclosure for Atmel. And given that they have it available for so many different devices, I can see why they might want to avoid having to support it.

The details on this pin are starting to get complicated-sounding. But pins cost money and silicon is cheap. So Atmel, like other companies, try to come up with methods to use their scarce pins to provide as much versatility as they can to sell devices.

That's it.

# Answer
> 1 votes
The capacitor C5 and resistor RN1 are used to TEMPORARILY apply RESET to the microcontroller chip during power-up. It assumes that C5 is discharged and will conduct the "AC" (change from 0V up to 5V) until it becomes fully charged and releases the reset line so that the microcontroller can start up properly.

You can use this online calculator to see the time-constant for any given resistor and capacitor: http://www.referencedesigner.com/rfcal/cal\_05.php

When the circuit is first powered up, C5 holds the microcontroller -RESET line LOW (the active state) until C5 charges up through RN1. At that point RN1 holds the -RESET line HIGH which releases the microcontroller to start up in an orderly manner.

It is not clear exactly what is happening between the U3 DTR pin and the junction of C5/RN2. There is a label that says "LED3 Yellow", but there is no symbol for a LED or any other component there. But there is typically a way for an external device to apply a reset also, so that you can re-program the microcontroller, and that is likely what is happening there.

---
Tags: usb, uart, ftdi
---


# Question
Title: How can I deal with rapid fluctuation of Anemometer readings?
In my little weather station I collect temperature, humidity, MQ-2 smoke sensor, and wind speed readings for display on a 20x4 LCD display, every 500 ms.
The Anemometer readings jump up and down by quite a bit.

Initialization of variables before Setup is like so:

```
// Wind Speed Anemometer
const int sensorPin = A3;
int sensorValue = 0;
float sensorVoltage = 0;
float windSpeed = 0;
float voltageConversionConstant = 0.004887586;  // (5/1024)
float voltageMin = .33;   // 0.4 in the documentation
float windSpeedMin = 0;
float voltageMax = 1.5;   // 2.0 in the documentation
float windSpeedMax = 32;

// 20 x 4  LCD Display
#include <LiquidCrystal_I2C.h>
// set the LCD address to 0x3F for a 20 chars 4 line display\/ Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

```

Then in Setup I initialize the LCD and flash the backlight.

```
lcd.begin(20,4);
lcd.clear();
for(int i = 0; i< 3; i++) {
  lcd.backlight();
  delay(250);
  lcd.noBacklight();
  delay(250);
  }
lcd.backlight(); // finish with backlight on

```

In Loop, I paint the initial screen then take readings and display them

```
void loop() {
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Weather");

  ...etc... to display time and show temp and humidity

  // Wind Speed
  sensorValue = analogRead(sensorPin);
  sensorVoltage = sensorValue * voltageConversionConstant;
  if (sensorVoltage <= voltageMin) windSpeed = 0;
  else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);
  lcd.setCursor(0,3);
  lcd.print(windSpeed);
  lcd.print(" MPH  ");

  ...etc... to display smoke detection...

  delay (500);
  }  // end loop

```

So the question is: How can I slow down the Wind Speed fluctuations? It jumps up and down quite widely.

# Answer
> 2 votes
A: Use a running average

In the initialization I include an array to hold 10 values

```
// Wind Speed Anemometer
const int sensorPin = A3;
int sensorValue = 0;
float sensorVoltage = 0;
float windSpeed = 0;
float voltageConversionConstant = 0.004887586;  // (5/1024)
float voltageMin = .33;   // 0.4 in the documentation
float windSpeedMin = 0;
float voltageMax = 1.5;   // 2.0 in the documentation
float windSpeedMax = 32;

float ws[10] = { };      // (initializes all to zero)
int wsIndex = 0;
float wsTot = 0.0;
float wsDisplay = 0.0;

```

Then in the Loop I fill the array with values and display the average of the 10 readings stored there

```
  // Wind Speed
  sensorValue = analogRead(sensorPin);
  sensorVoltage = sensorValue * voltageConversionConstant;
  if (sensorVoltage <= voltageMin) windSpeed = 0;
  else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);

  if (wsIndex<9) {
    ws[wsIndex] = windSpeed;
    wsIndex++;
    }
  else {
    wsTot = 0.0;
    for (int i=0;i<=9;i++) wsTot = wsTot + ws[i];
    wsDisplay = wsTot / 10.0;
    lcd.setCursor(0,3);
    lcd.print(wsDisplay);
    lcd.print(" MPH  ");
    wsIndex = 0;
    ws[wsIndex] = windSpeed;
    }

```

# Answer
> 1 votes
How about this one, it supposed to press fluctuations of your sensors reading

```
void loop(){
..
...
....
last_reading = sensorValue2; //

sensorValue = analogRead(sensorPin);
sensorVoltage = sensorValue * voltageConversionConstant;
if (sensorVoltage <= voltageMin) windSpeed = 0;
else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);

sensorValue2 = (sensorValue+last_reading)/2;
....
...
..
}

```

---
Tags: sensors
---


title: PWM multiplexing on Arduino nano

text:
# Question
Title: PWM multiplexing on Arduino nano
simulate this circuit – Schematic created using CircuitLab

Its a simple project. I am trying to drive 3 RGB LEDs using Arduino Nano. Since Arduino Nano does not have 9 PWM pins, the only solution I can think of by multiplexing them. I have try multiplexing 12 7-segments driven by atmega16, the results was satisfying. Is it possible to do **PWM multiplexing** on **Arduino Nano**?
So far, here is what I have done:

```
const int R=9, G=10, B=11, M1=5, M2=6, M3=7;

//I use pin 5,6,7 as selector since they are on same PORT (PORTD)

void setup()
{
    pinMode (R,OUTPUT);
    pinMode (G,OUTPUT);
    pinMode (B,OUTPUT);

    pinMode (M1,OUTPUT);
    pinMode (M2,OUTPUT);
    pinMode (M3,OUTPUT);
}

void led(int r, int g, int b)
{
    analogWrite(R,255-r);
    analogWrite(G,255-g);
    analogWrite(B,255-b);
}

void loop()
{
    for(int i=0; i<256; i++)
    {
        led(0,0,i);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B10000000;      //select LED-1

        led(0,i,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B01000000;      //select LED-2

        led(i,0,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B00100000;      //select LED-3
    }

    for(int i=256; i>0; i--)
    {
        led(0,0,i);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B10000000;      //select LED-1

        led(0,i,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B01000000;      //select LED-2

        led(i,0,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B00100000;      //select LED-3
    }

}

```

But still, this does not work. The result is all the led turned on, with 'a little bit' different color, mainly white with a little addition of another color (while it supposed to be contrast, R, G and B for each LED), and its blinking. The blink is very short, but still, its annoying. One possibility I can think of my code still not optimum.
Someone had an idea?

**EDIT**
I fixed the diagram, I hope the diagram does not make any misunderstandings. As the suggestion from @jwpat7, I forget to inform that the led still error even if there is just one `for-loop`.
I am using `__asm__("nop\n\t")` as delay substitution because "theoretically", 1 clock cycle from 16mHz clock is shorter than 1 microseconds. (correct me if I am wrong, but I think its about 62.5 ns)

Thanks in advance

# Answer
I've copied and slightly modified your diagram, as below. Note the added connections of R1, R3 cathodes to that of R2, and similarly for green and blue LEDs.

simulate this circuit – Schematic created using CircuitLab

I'm supposing that unlike the original diagram, this one represents what you actually wired up.

A basic problem with your program is that it spends most of its time changing PWM settings, without letting PWM cycles actually occur. To see this, do some timing analysis on the code.

The code repeatedly executes sections of code like the following:

```
    led(0,i,0);
    __asm__("nop\n\t");     //one clock cycle delay
    PORTD = B01000000;      //select LED-2

```

The call to `led()` results in three calls to `analogWrite()`. As seen by perusing at garretlab the source code for `analogWrite()`, `digitalWrite()`, and `pinMode()`, each of those `analogWrite()` calls takes a few handfuls of cycles – let's say 50 at most – so the three lines of code shown above take less than a dozen microseconds to execute. Thus each of the two `for` loops takes less than 10 milliseconds to complete, causing the `loop()` routine to run more than 50 times per second. Persistence of vision will result in observers just seeing the average level of light, rather than any ramping up or down.

To fix the ramps-not-visible problem, determine how long you want each ramp up or down to take, and add corresponding delays in the `for` loops. For example, suppose you want to go up in one second and down in two. As 1000000 μs /256 passes ≈ 3906 μs per pass, you could add `delayMicroseconds(3906-36)` at the end of the first `for` loop, and `delayMicroseconds(2*3906-36)` at the end of the other, to achieve the specified rates. (The -36 term accounts for time used by other code in each loop. It's probably an overestimate and perhaps should be left out.)

However, the previous paragraph doesn't take multiplexing effects into account. You may, of course, want a different PWM level for each of the nine different LED chips. It probably is practical to just directly use as many PWM outputs as you have available, and emulate PWM in software for any remaining LEDs.

For more information about software PWM, see some articles that google turns up, including:
Arduino PWM pin vs digital pin PWM simulation on electronics.stackexchange, which presents basic ideas and some pros and cons of software-based PWM
AnyPWM Revisited, a blog article by Nick Borko about PWMing 12 LEDs using software PWM
PWMAllPins, an arduino.cc article apparently by Paul Badger or Seth Wolf about PWMing 11 LEDs using software PWM

Generally, software PWM hogs computing cycles and can be difficult to coordinate with other calculations. But if PWM control is the only significant task a processor is handling, software PWM can be an economical way to produce extra PWM pins.
> 2 votes

---
Tags: arduino-nano, pwm, multiplexer
---


title: State machinese for serial input

text:
# Question
Title: State machinese for serial input
I am trying to control a servo using keyboard.

```
void loop() {
if (Serial.available() > 0) {
  x = Serial.parseInt();
  while(pos < 180){
  pos = x + pos;
  Serial.println(pos);
  myservo.write(pos);
  delay(100);
 }
  }
else if(Serial.available() > 0){
if(pos>=180){
  pos = 0;
  delay(500);
  myservo.write(0);

  }
  }
 }

```

Right now the servo takes the input correctly. The only thing is that it wont change positions immediately. It will wait until it hits 180 resets to 0 and then use the input I put in. This isnt the behaviour I want. I want it to change immediately. How Do I set this up?

# Answer
> 1 votes
I don't understand why you use 2 `Serial.available` condition.
I try to rewrote your program based on my imagination, so do not hate me if its wrong.
Why don't you try this and tell the results:

```
int pos = 0,x=0;
void loop()
{
  while (Serial.available() > 0) x = Serial.parseInt();

  pos+=x;
  if (pos>180) pos = 0;
  myservo.write(pos);
  Serial.println (pos);
  delay(100);
}

```

---
Tags: serial, servo
---


# Question
Title: Arduino zero Error: unable to find CMSIS-DAP device
I am uploading a test sketch(Blink) to my new Zero(with Wifi101 shield) and when I press Upload in the IDE, the Console says the following:

Arduino: 1.6.10 (Linux), Board: "Arduino/Genuino Zero (Programming Port)"

```
Open On-Chip Debugger 0.9.0-gd4b7679 (2014-10-03-00:26)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
debug_level: 0
adapter speed: 500 kHz
adapter_nsrst_delay: 100
cortex_m reset_config sysresetreq
Error: unable to find CMSIS-DAP device
Error: No Valid JTAG Interface Configured.
Error: No Valid JTAG Interface Configured.

```

I am using the Zero programming port.

# Answer
> 3 votes
I had exactly the same error with the same board. Running the IDE as root solved the problem. So, Chris was right pointing out a permission issue.

I found more information here : http://bitofahack.com/post/1437909576

Then I added the file `/etc/udev/rules.d/98-openocd.rules` :

```
ACTION!="add|change", GOTO="openocd_rules_end"
SUBSYSTEM!="usb|tty|hidraw", GOTO="openocd_rules_end"
ATTRS{product}=="*CMSIS-DAP*", MODE="664", GROUP="plugdev"
LABEL="openocd_rules_end"

```

I then ensured that I was member of group `plugdev`.

`udev` looks for changes in his rules directory so you don't have to restart it.

I plugged the board again and it worked.

Note that you can force udev to read the rule files again by entering :

```
sudo udevadm control --reload

```

I had to do this because I first made a mistake in the rule file.

Hope this helps.

---
Tags: arduino-ide, arduino-zero
---