title: 'setup' does not name a type?

text:
# Question
Title: 'setup' does not name a type?
Was trying to work some code that I found online to suit my needs and it continues to show the same error **'setup' does not name a type**. I have tried setting it to void, Void as well as rewriting the code but still the same issue arises and I was wondering how to fix this issue.

This program will at some point compile data from 3 different sensors and do its various calculations within these separate loops and print to serial in a table that can then be saved or exported. The only sensor attached at the moment is a ultrasonic sensor that measures the distance it is from a surface. (last 2 groups of code have a basic print function just so the loop is occupied)

Here is the code:

```
#include <CapacitiveSensor.h>

long timeCounter; // milliseconds counter
long timePassed; // The actual milliseconds time
int trigPin = 2;
int echoPin = 3;

long delay1 = 10;    // ms for cycle of event 1
long delay2 = 5;     // ms for cycle of event 2
long delay3 = 25;    // ms for cycle of event 3
long delay4 = 10;

// Counters for the number of triggered events before the
// corresponding event starts
int countEvent1, countEvent2, countEvent3, countEvent4;

int TRIGGER = 5; // ms to trigger the milliseconds timer

int MAX1 = 2; // Number or triggered milliseconds to start event1
int MAX2 = 1; // Number or triggered milliseconds to start event2
int MAX3 = 5; // Number or triggered milliseconds to start event3
int MAX4 = 2;

// Initialisation
setup {
     timeCounter = millis(); // read the actual internal time
     timePassed = 0; // we start with no time passed

     countEvent1 = 0;
     countEvent2 = 0;
     countEvent3 = 0;
     countEvent4 = 0;
}

// Infinite cycle
loop() {

     // Read the actual time
     timePassed = millis() - timeCounter;
     // The smallest unit of time that should trigger an event is for event 2 (5 ms)
     // so our trigger should count this smaller unit

     // Check if the time passed after last reading is the trigger time
     if(timePassed >= TRIGGER) {
          if(++countEvent1 == MAX1){
               // Reset the trigger and start the event
               event1();
               countEvent1 = 0;
          } // Event 1

          // It's time to manage the events
          if(++countEvent2 == MAX2){
               // Reset the trigger and start the event
               event2();
               countEvent2 = 0;
          } // Event2

          // It's time to manage the events
          if(++countEvent3 == MAX3){
               // Reset the trigger and start the event
               event3();
               countEvent3 = 0;
          } // Event3

          if(++countEvent4 == MAX4){
               // Reset the trigger and start the event
               event4();
               countEvent4 = 0;
          } // Event4

     } // Trigger

} // LOOP

// ============ Event functions ==============

event1() {
  long duration, distance;
  digitalWrite(trigPin,HIGH);
  delay(100);
  digitalWrite(trigPin, LOW);
  duration=pulseIn(echoPin, HIGH);
  distance =(duration/2)/29.1;
}

event2() {
Serial.print("work")
}

event3() {
Serial.print("work")
}

```

I am very new to coding so there will be stupid mistakes hidden amongst this I can guarantee it.

# Answer
All your functions (including setup and loop) need a type as part of the declaration. This for example:

```
event2() {
Serial.print("work")
}

```

Should be:

```
void event2() {
  Serial.print("work");
  }

```

Note also the semicolon after the `Serial.print` function call.

I have a page that explains the basics.

On that page is a diagram that breaks down what a function declaration looks like:
> 3 votes

# Answer
You have a problem with function definition. Let me explain with an example.

```
int kPinLed = 8; // LED - Pin 8

void setup()
{
  pinMode(kPinLed, OUTPUT); // LED as output
}

void loop()
{
  ledFun(); //Create LED Function
}

//Now write function's code with type, here "void"

void ledFun()
{
  digitalWrite(kPinLed, HIGH); //LED ON
  delay(1000);
  digitalWrite(kPinLed, LOW);  //LED OFF
  delay(1000);
}

```

Same things you have to do with your code. Just write properly function's type. I hope this will help you.
> 3 votes

# Answer
Function declarations start with a type:

```
void setup() {

}

void loop() {

}

```

void means the function doesn't return a value.
> 1 votes

# Answer
Yeah you never defined setup or loop which need the void before them.

```
void setup(){

}

void loop(){

}

```
> 1 votes

# Answer
> error 'setup' does not name a type. I have tried setting it to void

the correct typing of it is this:

```
void setup(void) {
...
}

void loop(void) {
...
}

```
> 0 votes

---
Tags: arduino-uno, serial, timers, events
---


title: Sketch Memory in Pro

text:
# Question
Title: Sketch Memory in Pro
```
    void storedata(File filename ,int type , String data)
{
    if(type == 1){
      Serial.println("Group Creation");
    }
    //Storing Data into file
    pinMode(10, OUTPUT);
    if (!SD.begin(SD_CS_PIN)) {
    Serial.println("initialization failed!");
    return;
  }
    Serial.println("initialization done.");
    filename = SD.open("filename.txt", FILE_WRITE);
    if (filename) {
    Serial.print("Writing to filename.txt...");
    SdFile file("sdfile.txt", O_WRITE | O_CREAT);
    if (!file.isOpen()) {
    Serial.println("filename.txt");
   }
    sdfile.println(data);
    //close the file:
    filename.close();
    Serial.println("done.");
    }else{
    // if the file didn't open, print an error:
    Serial.println("error opening filename.txt");
  }}

```

Im using this function to write on the Sd card , before calling this function the sketch memory is 28802 bytes ie ) 93% , simply just by calling this function from setup increased the sketch memory to 102% and iam unable to compile is there any unusual memory usage in this code ?

# Answer
> 1 votes
The good thing is that flash memory is instantly to be checked (you get the result after a (succesfull) compilation.

Refactoring you can do to reduce space:

* prevent duplicate code; try to make a function from duplicated code and call it whenever needed; this also makes the program much more easy to maintain (bugs in those part have to be solved only once, and changed only adapted once).
* If the code is almost the same but not an exact duplicate, use parameters in the function for the differences.
* Remove code that does not have a function but still is called. The compiler can automatically delete UNUSED code, but USED code that has no function you have to do yourself.
* Normally PROGMEM and F() is used to store arrays/strings in FLASH instead of SRAM, since mostly SRAM is more scarce, in your case you should not use this. Try to optimize code using less lines. This does not mean you have to remove spaces or make big oneliners; that will not help. But changing code structurally without changing the functionality will reduce flash memory.
* Remove unused libraries (although these are probably optimized out by the compiler)
* Global variables/structs/arrays and lots of const variables will cost memory to. For const values it might be useful to use #defines, however this will reduce maintainability/type checking.
* Remove debugging code (printf's for debugging functionality); I never tried but I think it should be feasible to make unit tests separately from the sketch code.
* A tricky way that could help is to optimize the libraries and reducing code there when needed. It is not useful to throw away functions that will not be called though. And debugging information should not be present, but maybe you can remove some conditions or code fragments that will never occur.

# Answer
> 1 votes
If you have a function that isn't called the compiler will just delete it (optimise it out). It also deletes any functions that the function calls that aren't used anywhere else.

By then calling that function the compiler keeps it, along with any other functions it relies on.

That includes the SDFat library code, much of which will have been removed before.

To make it now fit you will have to optimise your program. Look for blocks of code that do the same thing and replace them with calls to a function. Look for parts that could be replaced by a loop and an array instead of discrete calls to the same function(s) over and over again. Things like that.

Either that or use a board that has enough flash for your project.

---
Tags: sd-card, memory-usage
---


# Question
Title: What happens to the Arduino if you don't use a resistor with an LED?
Making a blinking light seems to be one of the most common beginner projects with Arduino. A typical approach is to connect an LED + resistor (in series) to an IO pin, and connect the other end to ground. In code, you make the pin an output, and bring it `HIGH` and `LOW` repeatedly to flash the LED.

What happens if you leave that resistor out? Obviously you're going to wreck the LED, but will it also damage the Arduino in some way?

# Answer
From page 411 of the ATmega328P data sheet, we have a graph of the output current vs voltage.

We can see over the the 20mA range of output currents, we drop ~0.5V, giving an approximate internal resistance of 25Ω.

A typical LED has a forward voltage of about 2V. Therefore, we end up in the situation where we will drop 3V over the 25Ω internal resistance of the ATmega328P, giving an output current of 120mA.

I = (5-2)V / 25Ω = 120mA

This is a simplification, but this 120mA is far larger than the recommended maximum current per pin of 40mA of the microcontroller, and far in excess of what a normal LED should take.

That said, most LEDs and the ATmega328P seem to survive this kind of abuse, especially for short periods. In general, if the pin continues to work after this is done, it should be fine.
> 19 votes

# Answer
Leaving series resistors out will definitely greatly (exponentially) shorten lifetime of both the controller and the LED. Absolute maximum ratings for most AVRs are (a.o.):

* max. 40mA per GPIO pin
* max. 200mA per package.

A new Arduino sets you back $20 or more, a fist full 220 ohm resistors sets you back 1$. When treated within spec, an Arduino (and LEDs for that matter) can survive a lifetime.
> 15 votes

# Answer
I have done this once (being a beginner concerning electronics). The LED died, luckily the Arduino survived (without any pin problems).

Wouldn't recommend this as it is not good for the Arduino.
> 0 votes

---
Tags: safety, pins, led, resistor
---


title: Programming Chinese Arduinos

text:
# Question
Title: Programming Chinese Arduinos
I have an authentic Arduino UNO, but I didn't want to pay full price for a new one to build semi perminate projects, so I bought a few ATMEGA328P-PU chips off of AliExpress:

https://www.aliexpress.com/item/1pcs-lot-ATMEGA328P-PU-CHIP-ATMEGA328-Microcontroller-MCU-AVR-32K-20MHz-FLASH-DIP-28/32346944696.html

But when I try to use Arduino IDE to upload the sketch to the new chips, I get these errors:

> avrdude: stk500\_recv(): programmer is not responding
> avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x00

It happens 10 times and quits.

It works fine when I put the original chip back in.

If anyone has any experience with this I'd be very grateful!

**EDIT:**

Trying the burn bootloader steps, and I'm getting a new error.

Steps I took:

I'm doing the 8MHz option, and so I downloaded the breadboard-1-6-x.zip file. (I'm using Arduino IDE 1.6.5 on Mac).

I uploaded the ArduinoISP example to my working chip, then wired it up to the breadboard as per the picture.

I switched the programmer to Arduino as ISP and set the board to ATMEGA328 on breadboard (8MHz clock)

I went to tools\>burn bootloader, and got this error:

> Arduino: 1.6.5 (Mac OS X), Board: "ATmega328 on a breadboard (8 MHz internal clock)"
>
> /Users/andy/Desktop/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Users/andy/Desktop/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -P/dev/cu.usbmodem411 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0x05:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xE2:m
>
> avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2009 Joerg Wunsch
>
> ```
>      System wide configuration file is "/Users/andy/Desktop/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
>      User configuration file is "/Users/andy/.avrduderc"
>      User configuration file does not exist or is not a regular file, skipping
>
>      Using Port                    : /dev/cu.usbmodem411
>      Using Programmer              : stk500v1
>      Overriding Baud Rate          : 19200 avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x15
>      AVR Part                      : ATmega328P
>      Chip Erase delay              : 9000 us
>      PAGEL                         : PD7
>      BS2                           : PC2
>      RESET disposition             : dedicated
>      RETRY pulse                   : SCK
>      serial program mode           : yes
>      parallel program mode         : yes
>      Timeout                       : 200
>      StabDelay                     : 100
>      CmdexeDelay                   : 25
>      SyncLoops                     : 32
>      ByteDelay                     : 0
>      PollIndex                     : 3
>      PollValue                     : 0x53
>      Memory Detail                 :
>
>                               Block Poll               Page                       Polled
>        Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
>        ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
>        eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
>        flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
>        lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
>        hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
>        efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
>        lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
>        calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
>        signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
>
>      Programmer Type : STK500
>      Description     : Atmel STK500 Version 1.x firmware
>
> ```
>
> avrdude: stk500\_getparm(): (a) protocol error, expect=0x14, resp=0x14
>
> avrdude: stk500\_getparm(): (a) protocol error, expect=0x14, resp=0x02
>
> avrdude: stk500\_getparm(): (a) protocol error, expect=0x14, resp=0x10 Hardware Version: -1543397124 Firmware Version: 2165568.-1543397124 Topcard : STK502 Vtarget : 1.8 V Varef : 0.0 V Oscillator : Off SCK period : 0.1 us
>
> avrdude: stk500\_initialize(): (b) protocol error, expect=0x10, resp=0x01 avrdude: initialization failed, rc=-1 Double check connections and try again, or use -F to override this check.
>
> avrdude: stk500\_disable(): protocol error, expect=0x14, resp=0x10
>
> avrdude done. Thank you.
>
> Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Making a little progress at least...

**Solution:**

I was using this layout:

Since that was failing I decided to try using the nano that I got at the same time, and after a lot of research I found this video:

https://www.youtube.com/watch?v=94KCYqS3--A

I jumpered the pins shown at the 1:30 mark to the ICSP port, **and tried burning the bootloader twice per chip, and on the second try it worked! Don't know why it had to be tried twice.**

I may go back to trying the breadboard method, just to see if it works if I try burning it twice.

# Answer
It's because these are unprogrammed chips, meaning they haven't had a bootloader programmed into them yet. Here is a tutorial for using your Arduino board to program a bootloader into them (there are many such tutorials available).

It only needs to be done once per chip so it will be worth your while to program all of them, once you have set up to do one. This is a very economical way to build "home-brew-duinos".
> 10 votes

---
Tags: arduino-uno, arduino-ide, atmega328
---


title: Arduino car parking program help

text:
# Question
Title: Arduino car parking program help
Here is a program and circuit diagram of an Arduino-based car parking (copy pasted from http://www.arduining.com/2012/10/13/arduino-parking-lot-filled/ ) I want to replace the Exit and End switch with IR sensor or ultrasonic sensor.

```
/*ParkingL02.pde
  Arduining.com 08 JUL 2012
  Code used in the production of the Youtube material.
*/
#include <Servo.h>
Servo myservo; // create servo object to control a servo
#define ServoM 12 //Connected to the servo motor.
#define Bright 11 //servo library disable PWM on pins 9 and 10.
#define Exit 9 //Pin connected to the EXIT button.
#define In 8 //Pin connected to the IN button.
#define BarLow 177 //Low position of the barrier.
#define BarUp 95 //Up position of the barrier.
#define CAPACITY 8 //Capacity of the parking lot.
#define INTEN 80 //Display intensity %
//Pins conections to segments (cathodes).
#define segA 0
#define segB 1
#define segC 2
#define segD 3
#define segE 4
#define segF 5
#define segG 6

int SensorIn(void);     // declare the sensor function for entering autos

//Array with the segments to represent the decimal numbers (0-9).
byte segments[10] = {
  // pgfedcba <--- segments
  B00111111, // number 0
  B00000110, // number 1
  B01011011, // number 2
  B01001111, // number 3
  B01100110, // number 4
  B01101101, // number 5
  B01111101, // number 6
  B00000111, // number 7
  B01111111, // number 8
  B01101111 // number 9
};

void setup() {
  myservo.attach(ServoM); // attaches the servo.

  pinMode(Exit, INPUT); // set "EXIT" button pin to input
  pinMode(In, INPUT); // set "IN" button pin to input

  digitalWrite(Exit, HIGH); // Connect Pull-Up resistor.
  digitalWrite(In, HIGH); // Connect Pull-Up resistor.

  pinMode(segA, OUTPUT);
  pinMode(segB, OUTPUT);
  pinMode(segC, OUTPUT);
  pinMode(segD, OUTPUT);
  pinMode(segE, OUTPUT);
  pinMode(segF, OUTPUT);
  pinMode(segG, OUTPUT);
  pinMode(Bright, OUTPUT);

  analogWrite(Bright, 255 * INTEN / 100);
  myservo.write(BarLow); //Barrier in the low position
  // delay(1000);
}

int Available = 9; // Number of places available.

void loop() {
  Display(Available);
  if ( SensorIn() == 0 )
  {
    if (Available != 0) {
      Available--;
      myservo.write(BarUp);
      delay(3000);
      myservo.write(BarLow);
    }
  }
  if (digitalRead(Exit) == 0)
  {
    if (Available != CAPACITY) {
      Available++;
      myservo.write(BarUp);
      delay(3000);
      myservo.write(BarLow);
    }
  }
}

/*-------------------------------------------------------------------
  Put the segments according to the number.
  --------------------------------------------------------------------*/
void Display(int number) {
  byte segs = ~segments[number]; //"~" is used for commom anode.
  digitalWrite(segA, bitRead(segs, 0) );
  digitalWrite(segB, bitRead(segs, 1) );
  digitalWrite(segC, bitRead(segs, 2) );
  digitalWrite(segD, bitRead(segs, 3) );
  digitalWrite(segE, bitRead(segs, 4) );
  digitalWrite(segF, bitRead(segs, 5) );
  digitalWrite(segG, bitRead(segs, 6) );
}

// We've moved the "sensor code" for entering autos to this function
// For now, the "In-sensor" is just a push-button.
int SensorIn(void) {
  return ( digitalRead(In) );
}

```

# Answer
If it were me, I'd approach it this way:

* Move each button read (digitalRead(xxx)) into its own routine.
* Get everything to work, still using the buttons.
* Write a separate sketch for whatever sensor or sensors you're going to use. All it needs to do is light an LED so you can be sure when it is detecting and when it isn't.
* Now replace the contents of each of the new button routines (from step 1) with the sensor code you just wrote. Your routines should return the *same values* for sensor detection that they returned for button detection. You shouldn't need to change any other part of your original code.
* Fix any bugs you made in the step above, and you're done.

Update:

I've just indented your code (above) and made one of the changes I suggested. You'll see that I made a new function called SensorIn() and put the code to read the "In" button there. Do the same thing for the "Exit" button.

Then, using a new sketch, learn to write code for whatever kind of sensor you want to use for entering autos. When that works, copy it into this sketches 'SensorIn()' function, replacing the line that reads the push button. Get this much working.

Then do the same thing, write a new sketch for the exit sensor until you can make that work reliably, too. Of course, if you choose to use the same kind of sensor for Exit as you used for In, you can just re-use the same code. Get this sketch working again.

Now you should have a sketch, just like your pushbutton sketch, but one that uses two real sensors instead of buttons.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to detect lipo battery % charge left?
I am currently working with a few robotic projects where i use lipo batteries. Currently I am working with a 1500 mah 3s lipo.

With my current setup I am using a arduino uno and a power distribution board. I put my lipo charger in my power distribution board which has two connections where I put two cables that goes to the VLN and GND.

(If needed I can make a quick schematic to explain it better!)

How can I now see the current battery percentage of the lipo?

I came across a project that uses this codesnippet:

```
long previousMillis = 0;

long interval = 1000;

int sensorValue = analogRead(A0);
float voltage = sensorValue * (5.0 / 1023.0);

unsigned long currentMillis = millis();

if (currentMillis - previousMillis > interval) {
  previousMillis = currentMillis;
 if (voltage <= 3.5)
      Serial.println("Low Battery");
     else
      Serial.println(voltage, DEC);
}

```

This snippet works with the A0 and I do not have anything connected there so I assume not.

Appreciate every help! :)

# Answer
LiPo batteries do not work well for percentage of charge remaining when using voltage as a reference. Lithium chemistry batteries hold a voltage quite close to level up to the point of near-exhaustion. That is to say, you can deplete such a battery by 80%, leaving only 20% capacity and have a few tenths of a volt reduction, depending on the configuration of your battery pack.

Unfortunately, should you continue to deplete the battery, damage may result. Some will say that damage WILL result.

The only certain way to determine a battery capacity is to use a smart charger and/or a smart discharger (often combined into one) to profile a battery.

For example, I have a 2000 mAh battery. After a few conditioning runs, either in use or on the smart dis/charger, the battery shows as having 1600 mAh capacity to 80% discharge.

Using a device to monitor the discharge rate, one can determine that if one uses 1550 mAh of the capacity, one is quite close to the risky cut-off point. To continue discharging, there is risk involved in the lifespan of the battery.

LiPo batteries will have greater than 4 volts reading immediately off the charger and will "flatten" to optimum voltage in a short time and hold very close to that level, depending on the current load, until it virtually vanishes at the cut-off point.

One can approximate a safe voltage for the cut-off point, but one risks the chance of an inaccurate volt meter. Collecting ampere-hours as a reference for cut-off is the most accurate method and also allows more capacity with less chance of damage.
> 2 votes

# Answer
Characterize a few such batteries by putting them through a charge / discharge cycles so you can link their voltage with remaining capacity.
> 0 votes

---
Tags: arduino-uno, c++
---


# Question
Title: Sending NEC IR signals makes LED strip blink
I'm trying to make my ESP8266 (running NodeMCU meaning Arduino code gets compiled on it). I followed a guide and now I can read the IR codes from my remote using my Arduino UNO, and then send them to the LED strip. So far sending it actually works, but it blinks REALLY fast.

Some part of me tells me it's trying to send it twice or the radio frequency is wrong. For TVs and so on, it doesn't really matter, as you can't turn on and off a TV instantly. You can with this LED strip though. This is how I send my NEC signal to the strip:

```
irsend.sendNEC(0xFF02FD, 433);

```

433 is the frequency (433 kHz), as I read that's the most common frequency these LED strips work at. The entire code I used can be found here. Do you think I have a frequency issue? I have tried a lot of different frequencies and they all seem to do the same thing.

Also, when I try to send the exact same NEC signal to my receiver, I get two different results. It is only being sent one time as well. Here is what I receive:

**Using the actual receiver**:

```
Decoded NEC(1): Value:FF02FD (32 bits)
Raw samples(68): Gap:51848
  Head: m8750  s4550
0:m450 s650 1:m450 s650      2:m450 s650    3:m450 s650
4:m500 s650 5:m450 s650      6:m450 s650    7:m450 s650
8:m450 s1750    9:m500 s1750         10:m450 s1750  11:m450 s1750
12:m500 s1750   13:m450 s1750        14:m450 s1750  15:m500 s1750

16:m450 s650    17:m450 s650         18:m450 s650   19:m450 s650
20:m500 s600    21:m500 s650         22:m450 s1750  23:m450 s650
24:m450 s1750   25:m500 s1700        26:m500 s1750  27:m450 s1750
28:m500 s1700   29:m500 s1750        30:m450 s650   31:m450 s1750

32:m450
Extent=66900
Mark  min:450    max:500
Space min:600    max:1750

```

**Using `irsend.sendNEC(0xFF02FD, 433)`**

```
Decoded Unknown(0): Value:0 (0 bits)
Raw samples(38): Gap:18088
  Head: m8850  s4550
0:m500 s1750    1:m500 s650      2:m450 s650    3:m500 s650
4:m500 s650 5:m450 s650      6:m500 s650    7:m450 s1800
8:m450 s700 9:m450 s1800         10:m450 s1800  11:m450 s1800
12:m450 s1800   13:m450 s1800        14:m450 s1800  15:m450 s650

16:m500 s1750   17:m500
Extent=43200
Mark  min:450    max:500
Space min:650    max:1800

```

EDIT: I forgot to mention: 0xFF02FD is the signal power/on/off button. If I change the 0xFF02FD to anything else (like 0xFF18E7 to make it yellow), the LED strip will just blink.

# Answer
32 kHz seems to be the winner. Now all my codes work! Damn, if I only had read that ONE SITE that showed it haha.
> 1 votes

---
Tags: esp8266, ir, nodemcu
---


title: Which motors to choose?

text:
# Question
Title: Which motors to choose?
I don't know if this is the right place to ask, but I'm an arduino newbie and I'm seeking some suggestions.
For my Robotics subject at University, I'm going to build a robot that should be able to move some objects (dragging them on the ground, not lifting them) from one place to another. I was looking around the web for the necessary components when I stumbled on a doubt: are 3-6V motors powerful enough for the wheels? Or do I need something more powerful like the 12V motors?
I'm not sure of what to choose between step motors or servo motors either, what do you suggest?
Oh and last thing, I opted for a L293D bridge driver for the motors, is this a good idea?

Thanks in advance!

# Answer
A 12 volt DC motor is good for dragging items, but then again it depends on the items weight. Stepper is used for millimeter precision, like 3D printing. Servo is an DC motor with precision for 180 degree movement, like robot arms. If the moving object is over 1kg you should look into geared DC motors or even the stronger brushed motors, or geared brushed motors. Whats the max weight?
> 2 votes

# Answer
You need to size your motors correctly depending on how much load they are expected to overcome. You first consideration should be how much maximum force would your robot need to exert at any given time....

For a robot just starting to drag a load (assuming the surface is flat) behind it, the robot would have to at least apply a force just greater than...

Maximum Static Frictional Force due to Robot's own weight on its wheels + Maximum Static Frictional Force due to object being dragged.

Maximum Frictional Force = Normal Force (weight) * coeff of Friction for the two surfaces

So for example, the coeff of friction between a brick (load) and ice (surface) would be lesser than between a brick (load) and asphalt (surface).

You need to do these calculations first.

If the speed limitations of your robot are inconsequential, then you only need to choose your wheel size and then determine how much torque your motor needs to be able to generate.

You do this like so.....Motor Torque needed = Force to generate / (radius of wheel * number of motors you want to install). So for instance, the torque needed per motor in a 4WD robot would be half that needed for an equivalent robot with only 2 powered wheels.

Once you have the motor torque you need, you can choose a motor and then choose a suitable power source for this motor.

Now repeat ALL the steps above this time accounting for the weight of the motors and the battery.
> 2 votes

---
Tags: motor, servo, stepper
---


title: How to check 8266 module

text:
# Question
Title: How to check 8266 module
I am using an Arduino board with an ESP8266 module to connect to a WiFi device. How do I check if the device is connected?

# Answer
You can use:

```
AT+ CWJAP?

```

or

```
AT+ CIPSTATUS

```

to see if you're connected to wifi. (The first will tell you access point status, the second will tell you IP address.)
> 2 votes

# Answer
Firstly,If your ESP8266 module is coded then AT commands won't be responding directly, In that case You can check in Serial monitor(if u already wrote print in the existing code on module) else u have to flash a new code.

If didn't flash any code then use AT commands(AT+CWJAP?) for checking SSID. (AT+ CIPSTATUS) for IP adress.
> 0 votes

---
Tags: esp8266
---


# Question
Title: Reading a car mass air flow, volumetric air flow meter
I'm looking to build an air flow meter that will output in standard liters per minute. The cheapest sensors seems to be a car's Mass Air Flow sensor. I'm wondering if there is a way use one of these MAF to measure air flow in liters per minute.

Essentially I need to measure a medical ventilator's air flow in order to calibrate it. The gas flow analyzers that are normally used are way too expensive and offer too many extra features that I don't need.

Thank You

# Answer
> 3 votes
There's no reason that an MAF couldn't be used with an Arduino. It's likely that the sensor will run on 12v and output an analog voltage from 0 - 12, so you might need to use a voltage divider with the Arduino.

See this Sparkfun article on implementing a voltage divider to scale down the 0-12 volt signal to 0-5v for the Arduino.

# Answer
> 1 votes
Does the sensor have to elecrtonic? How about a ball and tube flow-meter, say a lucite tube with a gradually expanding bore (harder) or constant bore just larger than a ping-pong ball, with a number of relief holes up the side (easier)? The higher the ball rises, the more air escapes through the relief holes. leaving less to support the ball while escaping around it.

You'd calibrate it with a positive displacement (piston) pump driven at values of (displacement/time) in the range if interest, and marking pen to record the ball position for each.

# Answer
> 0 votes
If you don't need to much precision, then use pulse counting from turbine wheel measuring device, that will give you the speed og air in the duct, multiply with duct area and you get the flow Volume. Alternatively use a delta pressure sensor for the air speed measurement something like http://www.rcdrone.cl/producto/sensor-velocidad-aire-para-aviones/

Just some idea from Lars Funder Have a great day

---
Tags: sensors
---


# Question
Title: Arduino UNO R3 as flight control plus brushless motor driver
I am trying to build an RC plane using an arduino UNO as the flight control board.

I found a code on the arduino forum for driving a 3 phase AC motor with an arduino. http://forum.arduino.cc/index.php?topic=8642.0

I believe it will also work for brushless motors commonly used in RC airplanes.This will eliminate the need for an ESC (Electronic Speed Controller) which are pretty expensive.

Now I plan to use a single arduino board to communicate with the nrf2l01 rf receiver , control the servos as well as drive the brushless motor(mentioned above).

In each cycle of the code the arduino will be fetching data from the receiver,sending a pwm signal to the servos and setting which two phases of the brushless motor will be high and which one will be low. Since so many things are being done in each cycle the phase change of the brushless motor might not be fast enough and this might hamper the motor speed? Or is the arduino fast enough to handle all this and it won't affect the speed noticeably.

# Answer
> 2 votes
> Since so many things are being done in each cycle the phase change of the brushless motor might not be fast enough and this might hamper the motor speed? Or is the arduino fast enough to handle all this and it won't affect the speed noticeably.

This is very much an engineering question. How would one go about answering this?

One method is do a worst-case execution time measurement. Another method is to use control theory and estimate the minimum control frequency for the system (or sub-systems).

Let us assume (for this argument) that the required update frequency is 50 Hz (20 ms cycle time). That gives approx. 320.000 instructions (AVR @ 16 Hz) per control cycle.

The algorithm sketch above in your question is basically dominated by the time to receive the message. This depends on a number of factors; PLL start up, write message from AVR to NRF, transmission frequency, coding, etc, but also message loss and retransmission/acknowledgement. With 2Mbps and 5 byte address, 32 byte payload, and 2 byte checksum the transmission time is at least 300-400 us plus approx 100-200 us for the AVR/SPI to NRF communication. A total of 400-600 us which is well under the 20 ms.

What other design considerations are there? Motor interference on the communication, antenna design, range, protocol design, etc.

Cheers!

---
Tags: arduino-uno
---


title: Adding Library to my sketchbook

text:
# Question
Title: Adding Library to my sketchbook
Hey so basically I have my Arduino uno r3 setup with my RFID-RC522. I am looking to add this library to so I can use the examples alongside the ones I already have. https://github.com/BoolLi/RC522\_RFID\_NFC\_Utilities

I haven't been able to add them correctly and hope someone can help me out doing this. I currently have these ones already added and working correctly: https://github.com/miguelbalboa/rfid

# Answer
> 1 votes
1. Download https://github.com/BoolLi/RC522\_RFID\_NFC\_Utilities/archive/master.zip
2. Copy the folder `RC522_RFID_Utilities` from the downloaded file to {sketchbook folder}/libraries. You can find the location of your sketchbook folder in the Arduino IDE at **File \> Preferences \> Sketchbook location**.
3. If you're using Arduino IDE 1.6.5-r5 or older restart the Arduino IDE. If using a newer version no restart is necessary.

The other three folders in the downloaded file are example sketches, not libraries. After installing the RC522\_RFID\_NFC\_Utilities library following the instructions above you will be able to use them. You can store those folders anywhere you like but you should not put them directly under the libraries folder as this will cause warning messages about invalid libraries on every compilation. If you do want to bundle them with the RC522\_RFID\_NFC\_Utilities library, as is customary, you can do this:

1. Create a folder named `examples` in {sketchbook folder}/libraries/RC522\_RFID\_NFC\_Utilities
2. Copy the example sketch folders (NDEFFormattingExample, etc) from the downloaded file to the `examples` folder you created.
3. Restart the Arduino IDE if it's running.

The example sketches will now be accessible via **File \> Examples \> RC522\_RFID\_NFC\_Utilities**.

---
Tags: arduino-uno, rfid
---


title: Execute function until called again?

text:
# Question
Title: Execute function until called again?
I am building a simple security system with my Arduino Uno. I have an `alarm()` function:

```
void alarm() {
  tone(8, 3300, 200);
  delay(200);
  tone(8, 3000, 200);
  delay(200);
}

```

When I call it in the `loop()` function like so:

```
void loop() {
  alarm();
}

```

the alarm sounds fine. I just want to be able to stop it. What I mean is, I want it to start the alarm (if it is off) when I call the `alarm()` function, then stop it when I call the `alarm()` function again. How can I do this?
**P.S. Can someone with over 150 reputation please make the `tone` tag?** I can't believe it's not here!

**Edit:** I tried the following code, but the alarm just kept going:

```
bool alarmOn;
void setup() {
  pinMode(8, OUTPUT);
  alarm(true);
  delay(5000);
  alarm(false);
}

void loop() {
}

void alarm(boolean call) {
  if (call) {
    alarmOn = true;
  } else {
    alarmOn = false;
  }
  while (alarmOn) {
    tone(8, 3300, 200);
    delay(200);
    tone(8, 3000, 200);
    delay(200);
  }
}

```

# Answer
> 2 votes
You can just have a variable that remembers whether the alarm is supposed to be on or off. Let's call it `alarm_on`. Then:

```
bool alarm_on;
static void start_alarm() { alarm_on = true; }
static void  stop_alarm() { noTone(); alarm_on = false; }

void loop()
{
    if (alarm_on) alarm();
    if (some_condition()) start_alarm();
    if (some_other_condition()) stop_alarm();
}

```

For a better approach that allows you to sound the alarm without blocking the whole program, see the Blink Without Delay Arduino tutorial.

**Edit**: I just wrote (but did not test) a non-blocking version of this alarm, based on a state machine and the timing technique from the *Blink Without Delay* tutorial. Here it is, as a class:

```
class TwoToneAlarm {
public:
    static const uint16_t HIGH_FREQ = 3300;
    static const uint16_t LOW_FREQ  = 3000;
    static const uint16_t TONE_DURATION = 200;

    TwoToneAlarm(uint8_t output_pin)
    : state(OFF), pin(output_pin) {}

    // Start the alarm.
    void start()
    {
        tone(pin, HIGH_FREQ);
        state = HIGH_TONE;
        last_tone_change = millis();
    }

    // Stop the alarm.
    void stop()
    {
        noTone(pin);
        state = OFF;
    }

    // Call this periodically to handle the tone changes.
    void update()
    {
        if (state == OFF) return;
        if (millis() - last_tone_change >= TONE_DURATION) {
            switch (state) {
                case HIGH_TONE:
                    tone(pin, LOW_FREQ);
                    state = LOW_TONE;
                    break;
                case LOW_TONE:
                    tone(pin, HIGH_FREQ);
                    state = HIGH_TONE;
                    break;
                default:
                    break;
            }
            last_tone_change += TONE_DURATION;
        }
    }

private:
    enum { OFF, HIGH_TONE, LOW_TONE } state;
    uint16_t last_tone_change;
    uint8_t pin;
};

```

It could be used like this:

```
TwoToneAlarm alarm(8);

void loop()
{
    if (some_scary_condition()) alarm.start();
    if (some_other_condition()) alarm.stop();
    alarm.update();
}

```

Note that the whole program must be non-blocking (`delay()`-free), otherwise the tone changes will not be done on time.

**Edit**: more about being non-blocking.

There is normally no reason for you to use `delay()` at all in your program. The only reason for this function to exist is to help complete beginners write their first blink-the-LED program. As soon as you start writing anything non trivial, you should ban it from your vocabulary. The Blink Without Delay tutorial is here precisely to teach you how to get rid of `delay()` by using `millis()`.

In this particular case, however, the drawback of `delay()` may not be too severe: if the alarm is sounding and you delay a tone change, you may hear it as a glitch that breaks the rhythm of the sound. If the delay is short enough, maybe up to 10 ms or so, you are unlikely to notice it. Longer delays will be noticeable, and it's up to you to decide whether you find them annoying or not.

It is possible to ensure a very steady rhythm despite the delays by using interrupts, but this will cost you your 16-bit timer. Or you could write your own implementation of `tone()` that does both the pin toggling and the tone changes using a single timer. Any such option will require you to learn about low-level timer programming, which is significantly more demanding than learning to use `millis()`.

---
Tags: arduino-uno, sound, piezo, buzzer
---


# Question
Title: Turning an LED on when an error occurs, then turn it off after 2 seconds
I am currently working on making some test equipment for µUSB cables. The code is supposed to recoqnise when an error in the cable occurs. Most of it works as expected, but I have some trouble understanding the use of millis() timers. I, therefore want to ask, in the code below, how can I make my program pick up on an missing connection in the cable and make sure it turns on the LED always? And secondly, how can I make it stay on for 2 seconds, even if the cable has "fixed" itself again (i.e. the connection has returned)?

*Update* It seems that I have misunderstood the assignment. The program should turn on a LED, when an error is present and keeps this on while the error is present (already fixed this in the code). When the connection has been regained a timer should start, which turns off the LED after two seconds. (Here's the trouble I'm having, I can't seem to pinpoint where and how this timer should start)

```
case microUSB:
  if (Vcc_Ext_val > 50)
  {
    digitalWrite(ActivateLoad, HIGH);
    LoadActivated = true;

  }
  else if (Vcc_Ext_val < 30)
  {
    digitalWrite(ActivateLoad, LOW);
    LoadActivated = false;
  }
  if ((Vcc_Ext_val < 50) || (USB_DP_VAL < 10)|| (USB_DM_VAL < 10))
  {
    PulseCurrentMillis = millis();
    if (FirstPulse == true)
    {
    digitalWrite(RedIntLED, StateLEDON);
    FirstPulse = false;
    }
    if (PulseCurrentMillis - PulseLastMillis >= PulseInterval)
    {
      PulseLastMillis = PulseCurrentMillis;
      if (LEDState == StateLEDON)
      {
        LEDState = StateLEDOFF;
      }
      else
      {
        LEDState = StateLEDON;
      }
    }
    digitalWrite(GreenIntLED, StateLEDOFF);
    digitalWrite(RedIntLED, LEDState);
  }
  else
  {
    digitalWrite(GreenIntLED, StateLEDON);
  }
  break;

```

# Answer
When you turn on the led, record the time.

After that, turn off the led if

1. The led is on and
2. Sufficient time has passed.

edit: this is what I would do.

```
//detect if sufficient time has passed
//1. turn on the led on button high -> low transition
//2. turn off the led after certain time (LED_DLY)
uint8_t led_ctrl(void) {
    static uint32_t led_timeoff=0;                              //time to turn the led off
    uint32_t time_now = millis();                               //take time now

    //if sufficient delay has passed, turn the led off
    if (isLED_ON() && (time_now >= led_timeoff)) {              //if led is already on
        LED_OFF();                                              //turn off the led
    }

    //if the button has experienced a the falling edge, turn on the led and set up the time to turn the led off
    if (btn_pressed()) {
        LED_ON();                                               //turn on the led
        led_timeoff = time_now + LED_DLY;                       //set up the time to turn off the led
    }

}

```

it is almost a literal implementation of what I wrote above.

here is the code in action, responding to button's falling edge with a 150ms delay turn off for the led: the button is on D12 and the led on D8.

fairly straight forward, isn't it?
> 0 votes

# Answer
I have made it work now.

The working code is as following, if anyone else gets the same issue.

```
case microUSB:
  if ((Vcc_Ext_val > 50) && (USB_DP_VAL > 10) && (USB_DM_VAL > 10) && (digitalRead(RedIntLED) == StateLEDON))
  {
    if (FirstStart == true)
    {
      StartMillis = millis();
      FirstStart = false;
    }
    PulseCurrentMillis = millis();
    if ((PulseCurrentMillis - StartMillis >= PulseInterval) && (digitalRead(RedIntLED) == StateLEDON))
      {
        PulseLastMillis = PulseCurrentMillis;
        digitalWrite(RedIntLED, StateLEDOFF);
      }
  }
  if (Vcc_Ext_val > 50)
  {
    digitalWrite(ActivateLoad, HIGH);
    LoadActivated = true;

  }
  else if (Vcc_Ext_val < 30)
  {
    digitalWrite(ActivateLoad, LOW);
    LoadActivated = false;
  }
   if ((Vcc_Ext_val < 50) || (USB_DP_VAL < 10) || (USB_DM_VAL < 10))
    {
      FirstStart = true;
      digitalWrite(GreenIntLED, StateLEDOFF);
      digitalWrite(RedIntLED, StateLEDON);
    }
    else
    {
      digitalWrite(GreenIntLED, StateLEDON);
    }
  break;

```
> 1 votes

# Answer
Look at one of the timer libraries such as SimpleTimer. It handles the timing for you and calls a routine you specify at the appropriate time. Your code just has to call its run() function frequently - once in every loop() iteration is typical.

Update:

Either library should work for you; neither should disturb the hardware timers or millis(), which depends on them. Try one of the timer example programs, blinking two leds at different rates for example, and expand or adapt from there.
> 0 votes

---
Tags: arduino-uno, led, timers, signal-processing
---


title: Is it wrong power supply?

text:
# Question
Title: Is it wrong power supply?
I used this cheap impulse power supply, and it worked on Arduino with prototype board for some short time, but then it stopped while I felt a burning smell. Is "impulse" a wrong type of power supply for Arduino board?

*On that board I had 0,96" OLED display (0,08W) connected, 3 LED's, 2 thermistors, 1 buzzer. All is working fine while powered by USB cable from laptop.*

# Answer
> 1 votes
A DC power supply with the right voltage is okay, also that one. You did connect it to the barrel jack ?

The most likely reason is that your Arduino board draws too much current for the voltage regulator on the Arduino board. Suppose you have an Arduino Uno with a servo motor or a lot of leds and they require 500mA. The voltage regulator would heat up with (9V-5V)\*500mA = 2 Watt.
Can you find the voltage regulator on the Arduino board ? You can check if it is getting to hot by holding your finger on the voltage regulator. If you can keep your finger on it, then it is okay.
The voltage regulator should reduce the current too prevent that it gets too hot, but it is not hard to blow the voltage regulator despite that.

The DC power supply could be bad quality and could have an output voltage that is too high or has voltage peaks, or there is a leakage current from the mains. Do you have another power supply ?

I use a good quality and certified DC power supply of 7.5V. In the photo I see all the right certification labels, but I don't know if they are real.

What was connected to your Arduino board ? If nothing was connected, then you are in trouble, and it could be faulty DC power supply or a bad Arduino board.

---
Tags: power
---


# Question
Title: How to drive a strip of 12 V no-addressable LEDs?
I recently bought this LED Strip. I got the 5M 3528 300LEDs SMD RGB Non-waterproof ones. However, I am not sure how to use them. On the strip there is four wires. I have tried supplying power to the wire that says it needs power and then I put ground to each of the other wires, but that only turns on a colour. How do I make it so I can choose what colour to use (Wiring, Code, etc.)?

# Answer
> 1 votes
**EDIT:** I'm sorry, I misunderstood! I assumed your LEDs were the 4pin serial version, whereas it makes more sense to me that they are the 6pin analog version. I must've brushed over the part where you said you grounded the colored wires and got that corresponding color.

You will provide 12V to the Power wire. To light the strip Red, you'd ground the Red wire, ground Blue for Blue, etc. Ground Red and Blue to light Purple, mixing colors etc etc.

So what if you wanted teal? or maybe a different shade of green? You'll need a way to generate PWM on the R, G, and B pins. Basically if you have an 80% duty cycle on Blue, that means it's only grounded 80% of the time. This corresponds to 80% brightness of the blue LEDs, then you could mix that with say 60% red and 10% green, or whatever you wanted to get a full 16 million colors. This is most easily accomplished with a microcontroller, and so I'll provide schematic and code tips for the simplest solution: an Arduino.

## Schematic

simulate this circuit – Schematic created using CircuitLab

I chose Pins 9, 10, and 11 of the Arduino because they are all PWM; you can choose any PWM pins you want (denoted by ~ or # usually). Just reflect those changes in the sketch.

Arduino pins are also only capable of sinking about 40mA if I remember correctly, so you'll need to control some MOSFETs with the PWM. I find you can't go wrong with the IRFZ44N, but that's just what I've had available to me.

## Arduino Sketch

How you control it is up to you; sensors, potentiometers, networked, bluetooth, constant fade pattern, there's a slew of options. So this code will tell you the necessary functions, but from there it's a matter of programming and integration of whatever else you want.

```
void setup(){
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}

void loop(){
  //255 -> 100%   ;   0 -> 0%
  analogWrite(9, 255); // turn red to 100%
  analogWrite(10, 0); // turn green to 0%
  analogWrite(11, 128); // turn blue to 50%
}

```

If this doesn't work, please let me know and I'll fix it. I forget if analogWrite is okay with being called in a simple, unrestrained loop over and over, and I also forget if Arduino pins have internal pull-downs

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


# Question
Title: Help Led matix isn't lighting up correctly Is it a Hardware or software issue?
I am trying to reverse engineer the project from this video: https://youtu.be/zc1zbwheyE0?t=50s.

From the video a visible 10 wires are going from the LEDs to the Arduino mega, i am assuming that they are wired in a 5x5 matrix (5 rows, 5 columns) given that there are 25 keys on the Midi controller so there most be 25 LEDs.
I reconstructed the project the best a could from observing the video, but my issue is when i press 3 keys 5 LEDs light up unlike in the original video where 3 keys are pressed and 3 LEDs light up(as seen @ 0:50 of the video).
This is the issue i am having : https://i.stack.imgur.com/ppLJn.jpg.
I am thinking the issue is related to how i have my LEDs wired, but my LEDs are wired exactly the same as in the video. isn't it ? is there something i might have missed? How is the project in the video able to light up 3 LEDs without having an issue with extra LEDs lighting up in their matrix? how can i fix my circuit to replicate the video?

Here is some of my coed for turning on an LED when a key is pressed:

```
<include MIDI.h>

MIDI_CREATE_DEFAULT_INSTANCE();

byte anodes[5] = {30, 32, 34, 36,38};

byte cathodes[5] = {31, 33, 35, 37,39};

byte data1 = 0;

void setPinTo5V(byte pin) //set a pin given to this function to a 5V voltage source

{
    pinMode(pin, OUTPUT);
    digitalWrite(pin, HIGH);
}

void setPinToGND(byte pin) //set a pin given to this function to a GROUND (GND pin)
{
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
}

void loop() {
    MIDI.read();
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
    data1 = MIDI.getData1();

    if (data1==48){//C3
        setPinTo5V(anodes[0]);//set pin 30 to 5V
        setPinToGND(cathodes[0]);//set pin 31 to GND

        delay(1); //do nothing for 1 ms
    } //this is done for all 25 keys

}

```

any help would be appreciated Thanks.

# Answer
This was what i was able to come up with, once a notes is press the blink function turns the LED on and off really fast. i am now have trouble getting the led to turn off once the notes is being pressed am not sure if the code is exiting from the while loop.

# include

MIDI\_CREATE\_DEFAULT\_INSTANCE();

# define LedR 3 //

# define LedC 4 //pin for each led

byte data1 = 0;

unsigned long previousMillisR\[2\]; //\[x\] = number of leds

unsigned long previousMillisC\[2\]; //\[x\] = number of leds

int Status \[25\];

void setup() {

MIDI.begin(MIDI\_CHANNEL\_OMNI);

MIDI.setHandleNoteOn(MyHandleNoteOn);

MIDI.setHandleNoteOff(MyHandleNoteOff);

pinMode(LedR, OUTPUT);

pinMode(LedC, OUTPUT);

}

void loop() {

MIDI.read();

//BlinkLedR(LedR,2000, 0); //BlinkLed( which led, interval, one of the stored prevMillis

//BlinkLedC(LedC, 10, 0); //last parameters must be different for each led

}

void BlinkLedR (int led, int interval, int array){

//(long) can be omitted if you dont plan to blink led for very long time I think

if (((long)millis() - previousMillisR\[array\]) \>= interval){

```
previousMillisR[array]= millis(); //stores the millis value in the

```

selected array

digitalWrite(led, !digitalRead(led)); //changes led state

}

}

void BlinkLedC (int led, int interval, int array){

//(long) can be omitted if you dont plan to blink led for very long time I think

if (((long)millis() - previousMillisC\[array\]) \>= interval){

```
previousMillisC[array]= millis(); //stores the millis value in the

```

selected array

```
digitalWrite(led, !digitalRead(led)); //changes led state

```

}

}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {

data1 = MIDI.getData1();

if (data1==48){//C3

Status\[0\]=1;

while(Status\[0\]==1) {

BlinkLedR(LedR, 10, 0); //BlinkLed( which led, interval, one of the

stored prevMillis

BlinkLedC(LedC, 1, 0); //last parameters must be different for each led

if (Status==!1){

break;

}

}

}

}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {

data1 = MIDI.getData1();

if (data1==48){//C3

Status\[0\]=0;

}

}
> 1 votes

# Answer
Your code is incomplete, so it's impossible to be sure, but I suspect your problem is with the way you are lighting the LEDs in the matrix.

Think about it conceptually: your LEDs are on the junctions of rows (anodes) and columns (cathodes). To light an LED you make the row high and the column low.

Let's call the rows R1, R2, R3, R4 and R5, and the columsn C1...C5.

Let's say the first LED you want to light is at the junction of R1 and C1. You make R1 high and C1 low.

Now you want to light an LED on the junction of R3 and C3. You make R3 high and C3 low.

What happens? Four lights light up. Why? You have R1 and R3 high, and C1 and C3 low. The circuit doesn't "know" that you want only two LEDs lit: it will light R1C1, R1C3, R3C1 and R3C3.

What is the solution? Remember which LEDs you want lit. Cycle through the matrix and deal with one row at a time: light all the LEDs you want lit in that row. Then move to the next row and repeat. Do this very fast. Your LEDs will be flashing, but if you write your code properly they'll do it so fast you won't be able to see it.
> 0 votes

---
Tags: arduino-mega, c++, electronics, midi
---


# Question
Title: Broadcast data to radius of at least 500 meters
I need to broadcast small amounts of data in a radius of about 500 meters to 2 Kms. in real time. Any compatible receiver in the range should be able to receive that data. Is there a suitable module for the same? I am considering HC-12 but don't think it can used for broadcasting data to all the surrounding receivers.

# Answer
Maybe you can look into the LoPy Microcontroller, a MicroPython enabled controller, that has a 1km WiFi range. It uses the Espressif ESP32 chipset (with 802.1b/g/n 16mbps WiFi) and has Bluetooth (BLE & Classic) integrated into the board.

(Reference: https://www.pycom.io/product/lopy/)
> 1 votes

# Answer
You can use NRF2L01 2.4ghz rf tranceivers.They have a range of approx 1 km without antannae and 1.8 km with antannae.Also the ESP8266 wifi module normally has a range of 300m but can be used for the ranges you require with some big dish antannae.
> 0 votes

---
Tags: wireless
---


title: Obstacle avoidance algorithm

text:
# Question
Title: Obstacle avoidance algorithm
## TARGET

The task I have taken as a challenge is to make a GPS-guided robot incorporated with features like Arduino for programming, ultrasonic sensors for obstacle avoidance and a GPS module to specify the way points location (from starting point to end point).

This robot should be able to avoid both static and moving obstacles while moving to its end point assigned from the GPS. I have found the robot manoeuvring around both static and moving obstacles to be a bit challenging. I was wondering if there is an effective obstacle avoidance algorithm that I can use.

I will appreciate it if I could get some helpful suggestions and insights.

# Answer
> 3 votes
In a real world scenario, your robot would know its start point and end point but due the limited range of its sensors (radar/ sonar/ visual) and the inability to "see" around corners, it would never be able to plan a full route at the very start of its journey. It would need to start the journey, detect obstacles as it moved and then re-calculate its path as it proceeds to its destination.

There is a very simple weighted index algorithm called the '*Bubble Rebound Algorithm*' to accomplish this type of maneouvering developed by IOAN SUSNEA, VIOREL MINZU and GRIGORE VASILIU.

Be aware however, that this is NOT a 'Maze Solving' algorithm. It is only meant for avoiding obstacles.

But first I suggest you take a look at my blog post about the python simulation I wrote using this algorithm. This will help you understand what is going on and give you a broad idea about how the problem is solved.

I also made two very important modifications (which I have described in the blog) to the algorithm that help the robot actually reach a destination.

On the blog post you will find a link to the source code hosted at codeskulptor and a YouTube video demonstrating the algorithm at work.

# Answer
> 2 votes
**The problem**

Given an unknown graph (or just world), a robot/person should be able to find a way between two points.

Pathfinding is often done on a known world, this website allows you to check out the different algorithms, which very much look like what you want to achieve.

Since you mentioned moving obstacles, you may also look at collision avoidance algorithms. But it depends on if the moving obstacles themselves also avoid collisions. To be able to avoid moving obstacles, you'll have to be able to know their location, direction and speed, to be able to calculate where you would collide (and how to avoid it). But usually, just braking whenever they get too close may just work (maybe even drive backwards if they get even closer).

**The approach**

So, we've got a startpoint and an endpoint. Our initial plan would be to travel straight from start to end, since this is obviously the shortest path.

But it would be ideal if there wasn't an obstacle, and for us to verify our approach, we'll just think of an obstacle. Let's say there is a wall right in front of you, what are you going to do? You can't see where it ends (I believe your robot doesn't), so you're just going to walk around it, you could choose a random way, (left or right, maybe even backwards)

**What algorithm**

Basically you want to get to the endpoint, so you're going to have an algorithm that has some kind of "fitness" based on how close you are to the endpoint.

You could:

* Brute force: Try every single route, until you've found the way.
* Right hand rule: I've heard that, in mazes, if you always hold your right hand against the (right) wall, eventually you'll get to the end.
* Greedy algorithm: Just move towards the point, if you can't go any furhter, choose whatever seems to get you closer. If nothing is getting you any closer, choose the route that moves away the least.
* Heuristic algorithm: Move one way, until choosing another round will be more likely to be a solution, then choose to go down another lane. Until this one seems to be leading you away.
* Search algorithm, like breadth first or depth first search, check this video

Just try some of the algorithms, to see which one works best. Or try to determine/explain why one algorithm is/should be better than the other.

---
Tags: programming, c++, c
---


# Question
Title: How to include Voltage code in 4 digit 7 segment dislay
As a continuation of my question. Here's the code for controlling the 4 digit 7 segment display:

```
int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;
int p = 9;

int d4 = 10;
int d3 = 11;
int d2 = 12;
int d1 = 13;

void setup()
{
  //set all the pins of the LED display as output
  pinMode(d1, OUTPUT);
  pinMode(d2, OUTPUT);
  pinMode(d3, OUTPUT);
  pinMode(d4, OUTPUT);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(g, OUTPUT);
  pinMode(p, OUTPUT);

}
/***************************************/
void loop()

{
  //The 7-segment LED display is a common-cathode one. So also use digitalWrite to  set d1 as high and the LED will go out
  digitalWrite(d1, HIGH);
  digitalWrite(d2, HIGH);
  digitalWrite(d3, HIGH);
  digitalWrite(d4, HIGH);

  switch(x)
  {
    case 0:
    digitalWrite(d1, LOW);//Light d1 up
    break;
    case 1:
    digitalWrite(d2, LOW); //Light d2 up
    break;
    case 2:
    digitalWrite(d3, LOW); //Light d3 up
    break;
    default:
    digitalWrite(d4, LOW); //Light d4 up
    break;
  }
}
//The function is to control the 7-segment LED display to display numbers. Here x is the number to be displayed. It is an integer from 0 to 9
void pickNumber(int x)
{
  switch(x)
  {
    default:
    zero();
    break;
    case 1:
    one();
    break;
    case 2:
    two();
    break;
    case 3:
    three();
    break;
    case 4:
    four();
    break;
    case 5:
    five();
    break;
    case 6:
    six();
    break;
    case 7:
    seven();
    break;
    case 8:
    eight();
    break;
    case 9:
    nine();
    break;
  }
}
void clearLEDs() //clear the 7-segment display screen
{
  digitalWrite(a, LOW);
  digitalWrite(b, LOW);
  digitalWrite(c, LOW);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, LOW);
  digitalWrite(p, LOW);
}

void zero() //the 7-segment led display 0
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(g, LOW);
}

void one() //the 7-segment led display 1
{
  digitalWrite(a, LOW);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, LOW);
}

void two() //the 7-segment led display 2
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, LOW);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(g, HIGH);
}

void three() //the 7-segment led display 3
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, HIGH);
}

void four() //the 7-segment led display 4
{
  digitalWrite(a, LOW);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void five() //the 7-segment led display 5
{
  digitalWrite(a, HIGH);
  digitalWrite(b, LOW);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, LOW);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void six() //the 7-segment led display 6
{
  digitalWrite(a, HIGH);
  digitalWrite(b, LOW);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void seven() //the 7-segment led display 7
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, LOW);
}

void eight() //the 7-segment led display 8
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void nine() //the 7-segment led display 9
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, LOW);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);

```

My problem is how to include the voltage code here? Here's the code for voltage code:

```
    /*
* Display5vOrless sketch
* prints the voltage on analog pin to the serial port
* Warning - do not connect more than 5 volts directly to an Arduino pin.
*/

const float referenceVolts = 5.0; // the default reference on a 5-volt board
const int batteryPin = 0; // battery is connected to analog pin 0

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

void loop()
{
 int val = analogRead(batteryPin); // read the value from the sensor
 float volts = (val / 1023.0) * referenceVolts; // calculate the ratio
 Serial.println(volts); // print the value in volts
 delay(500);
 }

```

Please help me! Thank you!

# Answer
> 1 votes
Yes you can display single digits what happen when you want to display double or triple digits. You need a code that can handle that. You need to cut up volts an iterare over it. Anyway create a class that takes volt and return it on the display. That's what you you need to do to merge that code. Are you up for that? Or are you gonna find a library that can handle that?

---
Tags: arduino-uno
---


title: What happens if we connect GND and +5v?

text:
# Question
Title: What happens if we connect GND and +5v?
What will happen if I by mistakenly connect GND and +5v of an Arduino Nano? Is there any protection for it? Or will it get short and fry out something?

# Answer
> 6 votes
Depending on how you are powering your board different things will happen.

1. If you are powering through USB from a PC the PC should, according to the USB standard, detect an over-current situation and disconnect the power from the port. However some don't, in which case see point 2.
2. If you are powering through USB from a USB power supply (phone charger, etc) the charger's output voltage will drop to near zero and the current will hit maximum for the supply. This may or may not damage the supply, but either way it's not a nice thing to do.
3. If you are powering from a small external battery (say a 9V PP3 battery) things will start to get hot. The voltage regulator will most likely overheat, the battery may overheat, but not much damage should occur - a small PP3 battery can't provide much current.
4. If you are powering from a large external battery (e.g., Li-Ion cells) or an external power supply, things will get more nasty. The on-board regulator will overheat. If it isn't thermally protected (genuine Arduinos should be, but cheap Chinese clones may not be) then it will fail and you will find smoke coming out of the regulator. At this point the regulator is dead. If the board contains a polarity protection diode that may fail in the same way (I have seen these blow clean off the board before). Physical damage (blackening and blistering) may occur to the PCB as well.

So all in all shorting +5V to GND is never a good idea.

# Answer
> 3 votes
According to this image and this datasheet, that nano's voltage regulator is internally limited.

That means it will heat up and shut down if over-loaded. Of course, your nano could use a less-effective regulator and simply smoke away. It's also possible that the 5205 would not clamp in time to prevent damage on an instant dead-short. Generally, i've found the arduino boards to be fairly resilient, compared to other MCUs, so you can *probably* get away with it at least a time or two.

Dead shorting is never a good idea even if you can get away with it because there can be incremental (as opposed to catastrophic) damage. You might cause instability in the regulator, and you might limit it's ability to limit volts. Those problems might not be revealed instantly, but instead at the worst (unexpected) time.

EDIT: based on your edit, it sounds like your "FTDI" is fried, but not *necessarily* your MCU.

---
Tags: power, arduino-nano
---


# Question
Title: Why is the BLE device not starting on my Arduino Pro Mini?
I recently purchased a 5V arduino pro mini that I now wish to connect to a BLE device.

I firstly tried the BLE device with my Uno board and it worked very well! However when I now try to use it on my mini it does not start.

This is my wiring: First I connect the pro mini to the uno in order to upload the code looking like this:

1. Arduino Mini Pro to Arduino Uno
2. RX --\> TX
3. TX --\> RX
4. VCC --\> 5v
5. GND --\> GND
6. RST --\> RST

Then I wire the mini to my BLE device (https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/hooking-everything-up):

1. Arduino Mini Pro to BLE nRF8001
2. 13 --\> SCK
3. 12 --\> MISO
4. 11 --\> MOSI
5. 10 --\> REQ
6. 9 --\> RST
7. 2 --\> RDY
8. GND --\> GND
9. VCC --\> VIN

When I connect this setup to the computer the arduino uno starts and also the pro mini (both has LED lights on). I upload a simple test code that worked when i tried it with the uno but the BLE device does not respond (it seems like it does not turn on) when i use it with the pro mini.

Any idea what might be wrong? I have my board put as: Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz).

Thanks a ton!! :)

# Answer
> 1 votes
> This is my wiring: First I connect the pro mini to the uno in order to upload the code looking like this:

```
Arduino Mini Pro to Arduino Uno

RX --> TX
TX --> RX
VCC --> 5v
GND --> GND
RST --> RST

```

How would this work? The bootloader in the Uno and Mini Pro will both try to reply. You need a FTDI or a USB-to-UART module instead of the Uno. Alternatively, start by programming the Uno to act as a USB-to-UART converter using Serial and SoftwareSerial.

Cheers!

---
Tags: c++, arduino-pro-mini
---


# Question
Title: Arduino Uno suddenly not recognized in Windows 8.1 (code 43)
I had my Arduino Uno connected to an external 12 V supply for 2-3 hours as I was working on other parts of my project. Suddenly the voltage from pin 9 which I was monitoring in the oscillator dropped down to 0 approximately.

I went on removing the external supply. The board was very very hot. I then connected the USB to my laptop and I got an error 43 (Windows did not allow the device to connect because it was reporting problems). I can't load any program of course. The 5 V pin works but it outputs a voltage lower than usual (at about 3.9 V). When I connect the external supply the 5 V pin outputs full voltage.

Any idea? Any fix?

# Answer
> 2 votes
Something is shorted out.

When you connect via USB, the USB port cannot supply enough current because of the short. The output drops to 3.9V and the USB port on your computer reports an error, probably due to over current.

When you connect the external power supply, it has enough power to supply the short. The output remains at 5V.

You can think of power supplies as having a very small internal resistance (R\_p), and the board as being a resistive load (R\_b). This forms a voltage divider, but because R\_b \>\> R\_p the voltage seen by the board is basically the same as that of the power supply. With a short, R\_b is often \< R\_p, and thus the voltage seen by the board is much lower than the power supply voltage.

The fix will depend on which component is getting hot. Plug in the external power supply and check which one it is. *Note: The component will get hot enough to burn your finger after a few seconds.* One way is to check one component at a time, disconnecting the power between each check. Start with the big ICs.

If either the Atmega328P or the smaller ATmega8u2 (?) are hot, they will have to be replaced.

Finally, boards don't short out by themselves. Something is wrong with your circuit or you may have placed the board down on some conductive surface. If you post you circuit we might be able to spot the problem.

# Answer
> 1 votes
I've been dealing with the same issue, and have resolved it in a manner similar to random approach described above.

Drivers will get corrupted as we all know. But if you want to get past that Code 43 error, you need to have the arduino unplugged from the USB when reinstalling. Otherwise windows will bind the USB.inf generic driver to the device, which prevents the install of the CH341SER driver.

So unplug USB, delete the unknown device via Device mgr, run the CH341SER, \*then plug in the USB cable. So I think that random approach worked not because the 9v reset was done unplugged, but because that was first chance (unplugged) that the CH341SER driver had to install without resources bound to generic USB.inf driver.

---
Tags: arduino-uno
---


# Question
Title: Send serial commands through IDE while RX pin is in use
This is really a two part question. I have an ESP8266 hooked up to USB. I have connected my LED strip (WS2812B LEDs) to the RX port, so I can control them individually and so on. I realised WiFi is a bit slow and will eventually crash the ESP8266 if I send enough requests, which is why I want to give serial a go.

1. If I open up the serial monitor, how do I send something to it, such as a color or 100 colors in one command? I'd assume `Serial.read()` inside a `Serial.write()` would display whatever I type in, but it doesn't do that. I can `Serial.write()` inside a loop, and it will display that.
2. Is something like this even possible? I'm looking for a way to send a lot of information (could be 100 colors (1 per LED)) as fast as possible. Speed is the key here.

Software serial is an option as well, as long as it's faster than WiFi.

# Answer
Regarding “I have connected my LED strip (WS2812B LEDs) to the RX port”: If you connect an LED strip to the RX pin, there's a good chance you won't be able to read serial data reliably on that pin, and may have trouble loading new sketches. It makes sense to connect the LEDs to some pin other than RX.

Regarding “If I open up the serial monitor, how do I send something to it”: Ordinarily, one uses the serial monitor to receive data from an attached MCU or to send data to the MCU. (An MCU is a microcontroller – eg an Arduino or ESP8266.) In the sketch on the MCU, use `Serial.write()` to send binary data to the monitor, and `Serial.print()` to send text and formatted numbers to the monitor.

If you want to send serial data rapidly from your host computer to the MCU, write a C or Python (etc) program that opens a serial port, marshals the data, and sends it. In the sketch on the MCU, use `Serial.available` to test if characters are available to read, and `Serial.read` to read a character. For faster transmission, you can send binary data instead of ASCII, but would need to read up on that before attempting it.

For fast data transmission, aim for either high data rates or strong data compression. For example, you might make up a protocol that only sends colors for pixels that are going to change; or might have high-level commands that tell the MCU how to generate a set of data, via color end points, step rates, and numbers of steps.

In general, wifi data rates are somewhat higher than serial data rates. If that is not what you are experiencing, perhaps review the article *Found a way to upload data VERY fast by wifi* from github.com/esp8266.

---

*Edit 1:* Regarding “Nothing is displayed in the serial monitor” \[from code like `if (Serial.available()) { Serial.write(Serial.read()); }`\]: I'm assuming that the sketch in use has a `setup()` routine containing a `Serial.begin(somedatarate)` statement, with the same data rate selected in the serial monitor as in the `Serial.begin()` statement. I'm also assuming the sketch has a `loop()` routine containing the `if (Serial.available()) { Serial.write(Serial.read()); }` code.

I'm also assuming the sketch was properly downloaded, and then the serial monitor was opened, using the USB-serial port the ESP8266 is attached to, and then you typed some text into the text entry box of the serial monitor and pressed or clicked Enter to send the text to the ESP8266, with a proper setting for the end-of-line character.

If all those assumptions are correct, but nothing shows up in reply to the text you send, then it seems likely some hardware or software issue is occurring. For example, when the Serial data structure is set up (when the sketch begins running) it might be selecting an incorrect Rx pin. Or something may be loading down the Rx pin. To find out if either of those is the case, use an oscilloscope (if you have one) to look at what's arriving at different ESP8266 pins when you send text from the serial monitor. If no scope, connect a 5K-10KΩ resistor to an LED and use that as a logic probe. One end of the resistor connects to a probe; the other end goes to the LED anode; and the LED cathode is grounded. Test if that's working by touching the probe to +3.3V. When the probe appears to be working ok, use it to check for brief flashes of data at different Rx pins on the ESP8266 when you send data from the serial monitor. If no data gets to the ESP8266, it can't echo it. (Note, I'm not sure how your NodeMCU ESP8266 handles serial-via-USB data; my notion that serial data should be visible on some Rx pin might be wrong.)

If it appears data is getting to some pin but isn't showing up as available, you might try opening software serial on that pin. Some examples appear in code in a serial monitor note at github.com/esp8266. I don't know enough about NodeMCU / ESP8266 to say what to do if probing and software serial don't help.
> 5 votes

---
Tags: serial, esp8266
---


title: How to read NodeMCU GPIO pin status?

text:
# Question
Title: How to read NodeMCU GPIO pin status?
I am setting up a page on NodeMCU running as a web server and I want to be able to turn on and off a light based on the url being clicked.

I want to know how I can get the status so that I can set the URL based on the pin status as well as pass the GPIO pin status in the JSON from the NodeMCU web server.

The code is here.

# Answer
Independent of the setting of port direction (input or output), pin can be read through the digitalRead():

```
int pin_light = 3;
int status = digitalRead(pin_light);

```
> 2 votes

---
Tags: esp8266, pins, c, nodemcu
---


# Question
Title: how to send argument to ESP8266WebServer objects on function
this probably simple thing to do however I can't think of a way to pass argument to function call

```
ESP8266WebServer server ( 80 );

void toggleRelayOne() {
  char temp[400];
  String msg = "";
  if (relay1 == 0) {
    relay1 = 1;
    msg = "Light is turned on";
  }
  else {
    relay1 = 0;
    msg = "Light is turned off";
  }

  digitalWrite (5, relay1); //GPIO 5 // Relay 1
  snprintf ( temp, 400,
             "<html>\
  <head>\
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU DHT11 Sensor and Relay Board</title>\
    <meta http-equiv='refresh' content='0; url=../'>\
    </head>\
  <body>\
  %d .</body>\
  </html>"
             , 1);
  server.send ( 200, "text/html", temp );
}

void setup ( void ) {

  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );
  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( host ) ) {
    Serial.println ( "MDNS responder started" );
  }
  MDNS.addService("http", "tcp", 80);
  server.on ( "/", handleRoot );
  server.on("/relay1", toggleRelayOne);
  server.begin();
  Serial.println ( "HTTP server started" );
}

```

in the above function where I am calling `toggleRelayOne` using `server.on("/relay1", toggleRelayOne);` I want to be able to pass relay id so I can use same function to toggle multiple relays.

# Answer
Use `server.arg()` to pass commands from the web as GET params:

`digitalWrite (5, relay1);`

becomes

`digitalWrite (server.arg("pin").toInt(), relay1);`

where the URL is something like `http://192.168.1.5/relay1?pin=15`

Of course, the rest of your code probably needs to be adapted to manage the extra states, read/write all in one http call, etc.
> 2 votes

---
Tags: programming, c++, c, sketch
---


title: DC Motor's don't stop immediately

text:
# Question
Title: DC Motor's don't stop immediately
## Functionality

I have written this code below for a buggy to continue moving forward until there is an obstacle which is \<= 25cm both motors should stop.

## Result

both motors stop when there is an obstacle which is \<=25cm but the motors happen not to stop immediately when it comes across the obstacle please do find my code below is there something wrong with my code and how can I make it much better.

## Code

```
#define PING_PIN  12  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
#define PING_MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

//initializing left DC Motor
const int in_1 = 2; // initializing the IN1 to Pin 2
const int in_2 = 3; //initializing the IN2 to Pin 3
const int EnA = 4;  //initializing pin 4 as pwm

////initializing Right DC Motor
const int in_3 =5;  // initializing the IN3 to Pin 5
const int in_4 = 6; // initializing the IN4 to Pin 6
const int EnB = 7;  //initializing pin 7 as pwm

// initialzing Ultrasonic sesor (Front view)
const int trigPin = 8;
const int echoPin = 9;

//For providing logic to L298 IC to choose the direction of the DC motor
void setup()
{
    /// initialize serial communication:
    Serial.begin(9600);
    pinMode(EnA,OUTPUT);   //we have to set PWM pin as output
    pinMode(in_1,OUTPUT);  //Logic pins are also set as output
    pinMode(in_2,OUTPUT);
    pinMode(EnB,OUTPUT);   //we have to set PWM pin as output
    pinMode(in_3,OUTPUT);  //Logic pins are also set as output
    pinMode(in_4,OUTPUT);

    //--------------------------------------------------------------
    // Reading the signal from the sensor: a HIGH pulse
    //-----------------------------------------------------------------
    pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)
    pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)
    //pinMode(trigPin2, OUTPUT);// set the trig pin to output (Send sound waves)
    //pinMode(echoPin2, INPUT);// set the echo pin to input (recieve sound waves)
}

void loop()
{
    int duration, Distance; // start the scan
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2); // delays are required for a succesful sensor operation.
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10); //this delay is required as well!
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    //---------------------------------------
    // convert the time into a distance
    //---------------------------------------
    Distance = (duration/2)/29.1;
    Serial.print(Distance);
    Serial.print("cm");
    Serial.println();
    delay(1000);
    if (Distance <= 25)
    {
        //Stopping Right and Left Motors
        digitalWrite(in_1,HIGH);
        digitalWrite(in_2,HIGH);
        digitalWrite(in_3,HIGH);
        digitalWrite(in_4,HIGH);
    }
    else {
        //Moving both Motors in a Foward motion - IN_1 = LOW , IN_2 = HIGH, IN_3 = LOW , IN_4 = HIGH
        digitalWrite(in_1,HIGH);
        digitalWrite(in_2,LOW);
        analogWrite(EnA,200); // Enablling the Right motor @ speed of 200
        digitalWrite(in_3,HIGH);
        digitalWrite(in_4,LOW);
        analogWrite(EnB,200);// Enablling the Left motor @ speed of 200
    }
}

```

# Answer
> 2 votes
As already stated, your problem is in the use of `delay()`, which *blocks* the program until the delay is over. When your program needs to be responsive, you have to write everything in a *non-bloking* manner. The basics of non-blocking management of time are covered in the Blink Without Delay Arduino tutorial, which I strongly encourage you to read. Applying the technique of the tutorial to your printing of the distance gives something like this:

```
static uint32_t last_time_printed;
uint32_t now = millis();
if (now - last_time_printed >= 1000) {
    Serial.println(Distance);
    last_time_printed = now;
}

```

I think the code is quite straightforward: you record the last time you printed the value and, if it has been one second since last time, you print it again.

You also have some other blocking calls in the section where you operate the sonar. I would not worry too much about `delayMicroseconds()`: these are really tiny delays, and your robot does not need to be *that* responsive. I would worry about `pulseIn()` though: this function blocks until it sees the end of the pulse, or until it reaches a timeout. The default timeout is one second, which is way too large for this application. Instead of relying on the default, you should specify a timeout as a third parameter, as in

```
duration = pulseIn(echoPin, HIGH, 50000);  // timeout: 50 ms

```

This would limit the range to about 8 m, which I think should be more than enough.

Reading the sonar pulse in a completely non-blocking fashion is possible, by using either an input capture unit or an interrupt, but I guess it is not worth the trouble, as your robot can probably cope well with being blocked for 50 ms.

# Answer
> 0 votes
As some of the comments have mentioned, the `delay(1000);` is probably doing you in. What's happening there is the code does absolutely nothing but count 1000ms for that time, so if the obstacle comes within 25cm during that delay, nothing will happen until the delay is done counting and the if statement occurs.

If you still want it to serial print every second, but not have that effect of slowing your response, try a counting variable (I forget the actual name). It's like a flag that you count on, so for example, you could have `int printCount = 0;` and instead of the delay(1000);, you'd have

`delay(1);
if(printCount > 999){
 Serial.println('Whatever');
 printCount = 0; //resets counter
} else{
 printCount++;
}`

# Answer
> 0 votes
While I totally agree with the other answers on the issue of using a non-blocking timer, I would like to add another factor about motor braking from a purely "electrical" point of view.......

To "brake" a running DC motor, you need to short the two terminals. This will generate a back current in the coil which will reverse the magnetic field and stop the motor much faster than by just cutting off power to the terminals. This is not possible to implement using a Bi-polar H bridge motor driver like L293D. You need to use a MOSFET type H-bridge.

---
Tags: programming, c++, c
---


# Question
Title: Passing a substring to a function or sub
I'm trying to send each character of a string object to a subroutine. I'm using the following code to do this, but it doesn't work:

```
string sInput = "some text"
for (int i=1; i < sInput.length(); i++) {
  showLetter(sInput.substring(i, i));
}

```

Subroutine:

```
void showLetter(String sInput)

```

My belief is that this should be iterating through the string and selecting one character (not to be confused with a char) at a time and sending it to the subroutine.

I haven't used C++ for 30 years and I am having difficulty finding why this won't work. I understand that I could use a char array, but I wanted to use this method.

If C++/Arduino coding doesn't work this way, to get credit you MUST explain why not.

Any help would be appreciated.

entire code follows...

```
/*
visual morse code

a dot is 1 unit
a dash is 3 units
  space between parts of the same letter is one unit
the space between letters is 3 units
the space between words is 7 units
*/

void parseString(String sInput);
void showletter(char sInput);
void dot(void); //dot
void dash(void);  //dash
void letterSeparator(void); //between letters
void wordSeparator(void); //space
int baseUnitLength = 100;

// the setup function runs once when you press reset or power the board
void setup(){
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop(){
  //call a routine with a string.
  //the routine parses the string and blinks the dot and dash for morse code for each character

  parseString("sos ");

  //showLetter("s");
  //showLetter("o");
  //showLetter("s");
  //showLetter(" ");
}

void parseString(String sInput)
{
  for (int i=1; i<sInput.length(); i++){
    showLetter(sInput.substring(i,i));
  }
}
void showLetter(String sInput){
  if (sInput == "a")
    {
      dot();
      dash();
      letterSeparator();
    }
  else if (sInput == "b")
    {
      dash();
      dot();
      dot();
      dot();
      letterSeparator();
    }
  else if (sInput == "s")
    {
      dot();
      dot();
      dot();
      letterSeparator();
    }
  else if (sInput == "o")
    {
      dash();
      dash();
      dash();
      letterSeparator();
    }
  else if (sInput == " ")
    {
      wordSeparator();
    }
}
void dot(){
    digitalWrite(LED_BUILTIN, HIGH);
    delay(baseUnitLength);
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength);
  }
void dash(){
    digitalWrite(LED_BUILTIN, HIGH);
    delay(baseUnitLength * 3);
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength);
  }
void letterSeparator(){
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength * 3);
  }
void wordSeparator(){
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength * 6);
  }

```

# Answer
> 1 votes
Mr. jfpoilpret provided me with the answer and should be credited, as such. It appears the subString function needs to have 1 added to the second parameter in order to properly reference the number of characters you need in the String.
In my case, iterating through a String and referencing only one character at a time means I need to do the following sInput.substring(i,i+1) Also, the String object uses a zero based index. EX:
String sString = "This is a peach."; sString.substring(0,4) //should return "This" sString.substring(8,9) //should return "a" sString.substring(15,16) //should return "."

In addition, you could also use the String function charAt (EX: sString.charAt(i)). The charAt returns a char and if you are passing it to a function/sub you need to make sure the function/sub is expecting a char data type. Also, it is easier to use a switch case when using the charAt function, as you don't have to do a conversion from String to char, as switch case does not work with Strings.

# Answer
> 1 votes
You got your answer, and you understood how this works. However, your sentence “*It appears the subString function needs to have 1 added to the second parameter \[...\]*” makes me believe you find this behavior somewhat contrived, whereas it should be intuitive to any C or C++ programmer.

As I think this may help, I will share here the mental picture I use for thinking about array indices. I call it the “L-shaped cursor”, and it goes like this:

An array index can represent two different things:

* a particular cell within the array
* an “edge” of a cell, i.e. either the limit between two cells or an edge of the whole array.

This is depicted in following picture of an array of length `N`, where the numbers above it are the edge indices and the numbers below are the cell indices. `i` and `j` are just two particular indices:

```
0   1   2           i           j               N
┌───┬───┬───┬───────┰───┬───────┰───┬───────┬───┐
│   │   │   │  ⋅⋅⋅  ┃   │  ⋅⋅⋅  ┃   │  ⋅⋅⋅  │   │
└───┴───┴───┴───────┺━━━┵───────┺━━━┵───────┴───┘
  0   1   2           i           j          N−1

```

Since each index can represent two things, I like to think about them as being L-shaped cursors, like the ones I've drawn in bold for the indices `i` and `j`.

Now, if you think about the purpose of the `substring()` method, it's job is to cut a slice along the string, and you need to tell it where to place the “knife”. Since the knife will cut along edges, it's perfectly natural to use edge indices for that. Then

```
someString.substring(i, j)

```

will give you the slice of the string that lies between the edges `i` and `j`. Looking at the picture above you can see this includes the cell numbered `i` but not the one numbered `j`.

I hope this picture helps you find the behavior of `substring()` more natural now. It *does* help me avoid fencepost errors.

# Answer
> 0 votes
I would suggestion the following:

```
String sInput = "some text";

void showLetter(char c);

for (int i = 1; i < sInput.length(); i++) {
  showLetter(sInput[i]);
}

```

Rewritten using C/C++ strings (null-terminated character vector):

```
const char* sInput = "some text";

void showLetter(char c);

for (int i = 1; i < strlen(sInput); i++) {
  showLetter(sInput[i]);
}

```

And slightly more efficient:

```
const char* sInput = "some text";

void showLetter(char c);

const char* sp = sInput;
char c;
while ((c = *sp++) != 0) {
  showLetter(c);
}

```

The next step is to move the string literal to program memory to reduce the amount of RAM needed.

Cheers!

---
Tags: arduino-uno, c++
---


# Question
Title: How can I split a string into three parts after space and turn the values to doubles?
I am currently gathering info from a BLE device. I made a thread earlier where I successfully split a string consisting of 5 letters to their unique chars.

However from this BLE device i will also send some different information from time to time where I send 3 different values with a space after each one. So for example looking like this:

`-0.1 0.51 0.07`

So what I want to do now is to store this three numbers in different doubles and what I have done so far is this:

First i store the recieved message:

```
String recievedMessage;

recievedMessage += (char)BTLEserial.read();

```

Now I have to determine if the value sent is the 5 letters or if it is the numbers with a space between each value.

```
if (recievedMessage.length() > 5) //so if the recievedmessage is more than 5 words then it is the 3 values that is being sent.
{
char * charTheMessage = recievedMessage.c_str();
char *str;
str = strtok(charTheMessage, " ");

double one = str[0];
double two = str[1];
double three = str[2];

Serial.println (one);
Serial.println (two);
Serial.println (three);

}

if (recievedMessage.length() == 5)
{
 //http://arduino.stackexchange.com/questions/36227/how-can-i-split-a-string-into-multiple-parts/36237?noredirect=1#comment72313_36237
//Here I split the letters into 5 different values if the value sent is 5.
}

```

But this values do not come out right when I print them in the serial monitor. I have also read that strtok is not reliable when data is sent fast so is strtok the right way to go you think?

# Answer
> 2 votes
You're almost there. Strtok returns the *first* token in the string only. You then have to convert that to a double yourself. You then call strtok again with NULL as the source string to get the next token. And so on.

I have written a good strtok example on here already. Look around, you may find it.

---
Tags: c++
---


title: Complex Arduino programs

text:
# Question
Title: Complex Arduino programs
Im working on a RGB LED matrix project (10 x 10 Neopixels) and I'm using classes to handle the different hardware components. Whats the best way to deal with multiple files in the project eg, I have a class which holds the various display functions such as writing text and drawing circles, but every time I change something it takes ages to compile (Greater than 30 seconds) is there a way to have multiple files without using classes?

Any help would be greatly appreciated.

Cheers

# Answer
I noticed that it is very hard to use classes with the default IDE. Each file will be in a different tab, but normally each class has a header (.h) and implementation (.c) file, so 2 extra tabs per class.

If you have just 3-4 classes you can use the default IDE.

However, if you want to use more, you have to use e.g. Eclipse or Visual Studio, whatever IDE you like best.

Search for Eclipse/Arduino, I think there are multiple options.

Myself I use visualmicro ... it is free except you cannot use the debugger option.

I used several classes in my sketch and don't think the compile time was 30 seconds; it might be depending also on the amount of include files.

Also a complex program is not necessarily a program with many classes. I would say, that if you put too much functionality in one class (or one single sketch), you get a complex program.
> 1 votes

# Answer
Yes you can have multiple files without classes.

Functions don't have to go in classes, see loop and setup for an example. All you have to do is declare the function in a header file and then implement it in a body.

so:

```
// File Bob.h
#ifndef __BOB_H__
#define __BOB_H__

int SomeFunction(const char val);

#endif // __BOB_H__

// File Bob.cpp
#include Bob.h
int SomeFunction(const char val)
{
   return (int)val;
}

// File SketchName.ino
#include "Bob.h"

setup()
{
  ......... Stuff

```

Now in **theory** the compiler will only rebuild Bob.cpp when you change code in it. In practice you will change code in it and the compiler won't rebuild it and you'll tare your hair out until you remember that if all else fails, rebuild all!

In `SketchName.ino` some people will say you should always put your includes first, some will say last and some will say it makes no difference. In my experience its easier to fix duplicate definitions by changing your code so I always put 'my' includes last, because that way the compiler will report the errors against my code.

BTW 30 seconds is not a long build time. I've worked on projects taking 12+ hours, and missing a semi colon on those projects does not make you popular :)
> 1 votes

---
Tags: ide, build, software
---