# Question
Title: Arduino IDE doesn't release COM port after programming
I have an arduino mega 2560 and I'm trying to program it using Arduino IDE 1.8.1. The problem is that I also need to keep open another program that will communicate with the Arduino using the COM port. I usually have to make very small changes to the code with the IDE and then check the results in the program.

However, when the IDE has finished uploading the program it will not release the COM port, and the program I'm using will give me an error message saying "access denied". This is a problem because I want to keep both programs open at the same time.

In fact I could just: make my correction to the code, close the IDE when it has finished, open the program I need, check whether the correction I made was right, otherwise close it again and open the IDE again, but that would take an insane amount of time and it would be quite annoying.

Is there a way to force the Arduino IDE to release the COM port so that other programs could communicate with the Aduino?

# Answer
> 1 votes
To force the Arduino IDE to disconnect from the COM port, simply go into the Tools menu, go to Ports and select another COM port.

Alternatively, you can open and then close the serial port monitor (Ctrl+Shift+M then Alt+F4).

# Answer
> 0 votes
This type of problem happens many time with me. Try to disconnect your ARDUINO MEGA from your PC / LAPTOP and then connect it again. It must be solve your problem. If this will not work then restart your PC / LAPTOP and try it out again.

---
Tags: serial, arduino-ide
---


title: Arduino motor and motor driver

text:
# Question
Title: Arduino motor and motor driver
I have a little problem. I have a motor driver (L298N). When I engage in electricity, my 2 motors start and after 5 second stop. Then they stop for about 2 seconds, and then start and in a moment (0.5 second) turn off. This make still around (go about 0.5 s, stop for 2 seconds...). And my motor driver is very hot after 1 minute.

Is it possible that it is because of weak voltage? (The motor driver is for 6-35 V, and I have a 6 V battery).

L298n: enter image description here

There is my code on Arduino:

```
const int motorPin1  = 9;
const int motorPin2  = 10;
const int motorPin3  = 6;
const int motorPin4  = 5;

void setup() {
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
}

void loop() {
  forw(3000);
  back(3000);
}

int fast = 255;

void forw(int timer) {
  analogWrite(motorPin1, 0);
  analogWrite(motorPin2, fast);
  analogWrite(motorPin3, 0);
  analogWrite(motorPin4, fast);
  delay(timer);
}

void back(int timer) {
  analogWrite(motorPin1, fast);
  analogWrite(motorPin2, 0);
  analogWrite(motorPin3, fast);
  analogWrite(motorPin4, 0);
  delay(timer);
}

```

# Answer
I ran the code on my arduino(kinda old), when I checked with my multimeter I noticed that the 5th PWM pin didnt osciallate every 3 seconds, could you please try the below code where I changed the 5th pin to 3rd PWM pin, also please change the connections on the l298 board.

```
const int motorPin1  = 9;
const int motorPin2  = 10;
const int motorPin3  = 6;
const int motorPin4  = 3;

void setup() {
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
}

void loop() {
  forw(3000);
  back(3000);
}

int fast = 255;

void forw(int timer) {
  analogWrite(motorPin1, 0);
  analogWrite(motorPin2, fast);
  analogWrite(motorPin3, 0);
  analogWrite(motorPin4, fast);
  delay(timer);
}

void back(int timer) {
  analogWrite(motorPin1, fast);
  analogWrite(motorPin2, 0);
  analogWrite(motorPin3, fast);
  analogWrite(motorPin4, 0);
  delay(timer);
}

```
> 2 votes

# Answer
The L298 is a very old, obsolete design based on bipolar transistors, which means it has a lot of internal losses.

The energy consumed in those losses shows up as heat.

It also has some degree of overload or overtemperature protection, so what you are observing is an automatic shutdown. Or perhaps, your motor is causing the battery voltage to sag and resetting your Arduino at which point the sketch resumes after a bootloader delay. 6v is really too low an input voltage to the Arduino's regulator, but too high for direct input without the regulator.

You need to make sure that the current draw of your motors is reasonable, and you likely want to replace the terrible L298 with a more modern, low less FET driver. You will need to select one rated for the actual current draw of your motor: you should consider not only free rotation of the motor, but the increased current draw if it is mechanically stalled.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Mega + SIM808 GPRS GSM GPS IPX-SMA module power on from code
Is it possible to turn on the SIM808 module from code? There is a button in the SIM808 board to activate the module, but I need to turn it on from the code automatically. This is because my device will be stored hidden inside a vehicle so I do not have to keep turn on and off by hand.

This is the model.

# Answer
> 1 votes
Looking at the pictures it looks like it should be possible to take the two exposed connections of the switch and add flying leads to them and run them back to the microprocessor to allow it to turn them on and off. The possible problem is the current that has to run through the switch.

You will need to investigate, but it looks like it could be done like that if you can't find a better solution.

---
Tags: arduino-uno, arduino-mega
---


# Question
Title: When uploading a sketch to an esp8266, isn't that the same as "flashing firmware"?
I thought that I read that using a PC running the Arduino IDE to "upload a sketch" to an esp8266 overwrites the original firmware (with the AT commands), and is actually "flashing the firmware" each time a "sketch" is uploaded. If I have that right, then why does the esp8266 WiFi still visible in available connections? There must be some code instructing the esp8266 to do this, but where is it? My sketch was simply the hello blinky thing and contained no #include statements. Where have I slipped?

# Answer
> 1 votes
Uploading a "sketch" is indeed "flashing firmware".

> why does the esp8266 WiFi still visible in available connections?

I'm not sure what you mean by that.

---
Tags: esp8266, wifi, firmware
---


title: FPC1020 + WeMos D1 Mini

text:
# Question
Title: FPC1020 + WeMos D1 Mini
I have a FPC1020am that work perfectly with arduino and a ESP8266 D1 Mini V2 NodeMcu 4MB Lua that can connect to server.

How can I connect the **FPC1020** direcetly to **ESP8266 D1 Mini** to scan finger and send matched id to server?

here is my code and error:

```
#include <NewSoftSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <FPC1020.h>

extern unsigned char l_ucFPID;
extern unsigned char rBuf[192];  //Receive return data
#define sw_serial_rx_pin 2 //  Connect this pin to TX on the FPC1020
#define sw_serial_tx_pin 3 //  Connect this pin to RX on the FPC1020

const char* ssid = "-------";
const char* password = "-------";

const char* host = "-------";
String url = "-------?id=";

NewSoftSerial swSerial(sw_serial_rx_pin, sw_serial_tx_pin); // Fingerprint serial (RX, TX)
FPC1020 Finger(&swSerial);

void setup() {
  Serial.begin(115200);
  Serial.print("connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  pinMode(4, INPUT);
}

void loop() {
  Serial.println("Please put your finger on the Sensor.");
  while(Serial.available()<=0);

  if( Finger.Search()){
    Serial.print("Success, your User ID is: ");
    url = "-------?id=" + l_ucFPID;
    Serial.println( l_ucFPID, DEC);

    WiFiClient client;
    if (!client.connect(host, 80)) {
      Serial.println("connection failed");
      return;
    }

    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 "User-Agent: BuildFailureDetectorESP8266\r\n" +
                 "Connection: close\r\n\r\n");

    String line = "";
    while (client.connected()) {
      line = client.readString();
    }

    Serial.println(line);

  }
  else {
    Serial.println("Failed, please try again.");
  }
}

```

And the error is:

```
C:\Program Files (x86)\Arduino\libraries\NewSoftSerial\NewSoftSerial.cpp:41:27: fatal error: avr/interrupt.h: No such file or directory

 #include <avr/interrupt.h>
                           ^
compilation terminated.

exit status 1
Error compiling for board WeMos D1 R2 & mini.

```

# Answer
I have never tried this, but a D1 Mini has 2.5 serial ports.

* The Tx and Rx pins are Serial0.
* Digital pin 4 is TX1 - There appears to be no RX pin.
* D7 and D8 are Rx2 and Tx2.

So rather than using SoftwareSerial or NewSoftwareSerial try using Serial2. It might work.
> 1 votes

---
Tags: arduino-uno, esp8266
---


# Question
Title: Alternative for IRF520 mosfet in Arduino shutdown schema
I’am using IRF520 mosfet according to this schema to shut down Arduino by low level on output to 10K ohms resistor

Schema of my device is

---

The issue is that IRF520 took too much place

Is it possible to substitute IRF520 with smaller mosfet?

***Additional info:***

I measured average power consumption – it’s about 22 mA on 12V = 0.264W

IRF520 is for 70W max according to datasheets.

The base schema is

# Answer
> 1 votes
For what you are trying to do, any transistor, bjt or MOSFET, would work. 2n2222 or 7000 for example. Irf5x0 is actually a poor choice here. It only worked due to the low load being switched.

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


# Question
Title: How do I use an image sensor with an arduino uno?
I have recently taken apart an old digital camera for its parts and I have found an image sensor inside it.

For those of you who don't know, an image sensor measures light; the shutter opens, light hits the sensor and the sensor converts this light into data to be stored as an image.

My question is how can I implement it into a project? What equipment do I need? It has a tape wire so I'm not really sure how I can use it. I have attached a photo of it also. Thanks!!

# Answer
You need to find markings on it and figure out what the component actually is. Then you can maybe find a datasheet for it that explains how it works and commmnicates. Once you know that you can decide if that's something you can do with an Arduino. Be prepared to learn that Arduino might not be big enough or fast enough to do anything with that particular sensor.
> 1 votes

# Answer
> how can I implement it into a project?

Find its datasheet, understand how it works and code to it.

Just as what you would with any other devices. The challenge here is that you will be hard pressed to find any info about those kind of devices.
> 0 votes

---
Tags: sensors
---


# Question
Title: Program NOT responding to loop()- Arduino UNO+GSM + Sensor
I'm trying to monitor the sensor values (range 0-1000) connected to Arduino UNO's 12th-pin. If the value stays below say 500, then it should SEND SMS. I tested the sensor and GSM shield seperately and both of them are working fine. But my program is not giving the sensor reading in the serial monitor nor sending the SMS. I'm pretty sure it got stuck at sendRequest() part of the code.

```
// the setup routine runs once when you press reset:
#include "Adafruit_FONA.h"

#define FONA_TX 2
#define FONA_RX 3
#define FONA_RST 4

// this is a large buffer for replies
//char replybuffer[255];
char buffer[50];
char r[15];
// We default to using software serial. If you want to use hardware serial
// (because softserial isnt supported) comment out the following three lines
// and uncomment the HardwareSerial line
#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX,FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
SoftwareSerial Sensor_Serial(12,13);

// Hardware serial is also possible!
//  HardwareSerial *fonaSerial = &Serial1;

// Use this for FONA 800 and 808s
//Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
// Use this one for FONA 3G
Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST);

uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);

uint8_t type;

byte readCO[] = {0xFF, 0X01, 0X86, 0X00, 0X00, 0X70};
byte response[] = {0,0,0,0,0,0};

//multiplier for value. default is 1.
int valMultiplier = 1;

void setup() {
  while (!Serial);

  Serial.begin(9600);
  Sensor_Serial.begin(9600);    //Opens the virtual serial port with a baud of 9600
  Serial.println(F("FONA basic test"));
  Serial.println(F("Initializing....(May take 3 seconds)"));

  fonaSerial->begin(4800);
  if (! fona.begin(*fonaSerial)) {
    Serial.println(F("Couldn't find FONA"));
    while (1);
  }
  type = fona.type();
  Serial.println(F("FONA is OK"));
  Serial.print(F("Found "));
  switch (type) {
    case FONA800L:
      Serial.println(F("FONA 800L")); break;
    case FONA800H:
      Serial.println(F("FONA 800H")); break;
    case FONA808_V1:
      Serial.println(F("FONA 808 (v1)")); break;
    case FONA808_V2:
      Serial.println(F("FONA 808 (v2)")); break;
    case FONA3G_A:
      Serial.println(F("FONA 3G (American)")); break;
    case FONA3G_E:
      Serial.println(F("FONA 3G (European)")); break;
    default:
      Serial.println(F("???")); break;
  }

}
void loop()
{
    sendRequest(readCO);
    float valCO = getValue(response);
    static unsigned long startTime = 0;
    if (valCO < 500)

   dtostrf(valCO, 3, 2, r); // I don't know how to covert the unsigned long variable to string and I know //this part does the float to string conversion
    sprintf(buffer, "%s High  Level", r);
    Serial.print("CO  = ");
    Serial.println(valCO);
    if (millis() - startTime > 1UL*60UL*1000UL) {  // Has it been 1 minute since the value was below 500?

      startTime = millis();
      fona.sendSMS("0XXXXXXX", buffer);
     }
  }

void sendRequest(byte packet[])
{
  while(!Sensor_Serial.available())  // If this part works the entire code works I think!!
//keep sending request until we start to get a response
  {
    //Sensor_Serial.write(readCO,9);
    delay(50);
  }

  int timeout=0;  //set a timeoute counter
  while(Sensor_Serial.available() < 9 ) //Wait to get a 9 byte response
  {
    timeout++;
    if(timeout > 10)    //if it takes to long there was probably an error
      {
        while(Sensor_Serial.available())  //flush whatever we have
          Sensor_Serial.read();

          break;                        //exit and try again
      }
      delay(50);
  }

  for (int i=0; i < 9; i++)
  {
    response[i] = Sensor_Serial.read();
  }
}

unsigned long getValue(byte packet[])
{
    int high = packet[2];                        //high byte for value is 3rd byte in packet in the packet
    int low = packet[3];                         //low byte for value is 4th byte in the packet

    unsigned long val = high*256 + low;                //Combine high byte and low byte with this formula to get value
    return val* valMultiplier;
}

```

OUTPUT: . . . . FONA is OK Found FONA 3G (European) ---\> AT+GSN \<--- 8XXXXXXXXXXXXXX Module IMEI: 8XXXXXXXXXXXX

I guess this part of the is waiting for like ever and not returning any response

```
while(!Sensor_Serial.available())  //keep sending request until we start to get a response
  {
    Sensor_Serial.write(readCO,9);
    delay(50);
  }

```

Any help guys?

# Answer
You have multiple software serial ports and are expecting them to work like real ones.

**They don't.**

You can only have one of them "active" at a time (that is, ready to receive data). You need to switch between them with `Sensor_Serial.listen()` and `fonaSerial->listen()`.

In general it is bad to have more than one SoftwareSerial (and personally I think even one is bad) since they are very heavyweight and block all other operations while they are either sending or receiving data (which means your listening one cannot operate at all while your non-listening one happens to be sending).

If you have a requirement for more than one serial port you should really be using a board that has more than one serial port.
> 1 votes

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


# Question
Title: Can I connect a voltage, higher that the 1.1V bandgap voltage, to an ADC pin
Can I (attempt to) measure a voltage that is higher that the ADCs Vref, without damaging my IC?

I'm trying to measure the battery voltage using a resistive divider, and using the internal 1.1V bandgap voltage. I selected the resistors so the voltage would be around 1V when fully charged.

My project can however also be power by a wall-adapter, which exceeds the batteries voltage, resulting in a voltage higher than 1.1V at the ADC.

In the datasheet the table of ADC Characteristics seems to indicate that the maximum input voltage is Vref. Though I'm not sure if that's the maximum voltage is can convert, or if that's the maximum voltage that's allowed.

Elsewhere in the datasheet it says: `Single ended channels that exceed VREF will result in codes close to 0x3FF`, which seems to indicate it isn't a problem to exceed Vref (as long as it's below Vcc).

The part I'm using is an ATtiny13A, but the relevant sections of the datasheet seem identical to the ATMega328.

# Answer
> 4 votes
Yes, you can go above VRef.

> Voltage on **any Pin except RESET**
>
> with respect to Ground ................................-0.5V to VCC+0.5

And as the ADC reference says anything above VREF will give you the maximum value (it will saturate).

So powered from 5V you can apply anything from -0.5V to +5.5V safely. That's basically the supply voltage plus one diode drop for the ESD protection diodes within the pin.

The ADC is just comparing two voltages. The VREF isn't used to power anything.

---
Tags: adc, attiny13
---


# Question
Title: How can I automatically get the time from the computer into an alarm clock (starts at 00:00 when plugged in)?
Okay so I did this project from Fritzing first in my circuits.io project then on the arduino itself, it all works fine just how I wanted it.

But here is what I wanted to add, as you can see when you plug the arduino in it will set the time to 00:00 and you can adjust it yourself to the time right now, let's say 12:57. Then you put in the alarm so let's say you want to sleep an hour u put the alarm on 13:57.

Is there a way to automatically get the time from the computer? So you don't have to adjust it yourself everytime and start from 00:00.

Thanks for all the help!

# Answer
There are several ways, and they are covered in the comments above.

1. The answer to your question. Via Arduino USB to serial interface. and a simple batch file on a windows computer example:

@echo off

set datetimef=%time:~0,2%.%time:~3,2%:%time:~6,2%

echo %datetimef% \> COM5

COM5 is used as a example, your serial port can be another number.

The format in the example is hour.minute:second
> 1 votes

---
Tags: communication, timers, time
---


title: Power bank turns off spontaneously

text:
# Question
Title: Power bank turns off spontaneously
I currently have a 50,000 mAH USB power bank powering my Arduino Uno and micro servomotor. Unfortunately, my power bank has an automatic shutoff and shuts off after 2 hrs of runtime (I need 16 hrs for my project). I can restart the power bank by hitting the on button and it will run just fine for another 1-2 hrs at which point it will shut off. In one instance, the power bank ran for the desired 16 hrs straight hours. I believe that my arduino/servo are very close to the current threshold of the bank which could explain some of the variability I am seeing in terms of turn-off time. Would hooking up a resistor in the circuit do the trick and if so where?

Not quite sure about the brand of power bank (just one I found off Ebay). I believe the arduino uno and servo consume about 60 mA for power.

# Answer
You have a couple of options, depending on how much you want to dive into electronics.

* Find/buy a new powerbank that does not auto-shutoff
* Find the current-sense resistor on the internal circuitry of your existing powerbank and change it out so that the device always thinks there is current flowing, or is more sensitive to your low-draw attachment. I was able to find a few websites describing this for specific powerbanks by searching.
* Add a dummy load in parallel with your circuit, which wastes power, but does trick the powerbank into staying on.

It's also worth noting on the side, that you very likely do not have 50,000 mAh capacity in this powerbank, as others have noted. However, you ought to be able to get 16h of runtime with even a lower-rated powerbank if your claim of 60mA current draw is true.
> 8 votes

# Answer
I can't see this helping.

It could only help if your power bank switched off its output when the current drawn dropped too low - but unless your circuit's current consumption drops after two hours, which you don't mention, that is unlikely to be the reason it's switching off.
> 2 votes

# Answer
Expanding @jose can u c first suggestion I did a little research and found that Voltaic Systems sells power banks with an option to disable auto-shutoff mode. There may be others. I found two of their power banks offered on Amazon. The blurb in the Amazon listing explicitly mentions using it with Arduino and Raspberry Pi.
> 1 votes

# Answer
As the company Voltaic has been mentioned I feel that it would be helpful if I warned you of that company. We are after all trying to offer solutions and if you follow the advice of the person who suggested Voltaic then I know from first hand experience that the thing turns itself off even when the auto shutdown mode is disabled. Though this may not be an end solution I know that by helping you to avoid useless information I can keep you on track and help you towards your solution. In detail : I'm a chauffeur and I bought a Voltaic for this specific reason and guess what? It switches off even when auto shutoff mode is disabled. I wanted my customers to be able to charge their devices as quick as poss and with as little complication as poss. I'm thinkin bout puttin a led fibre optic charging cable in so there is always a tiny power usage from the LED near the big USB jack. At least then also the cable wld be more 'look at me, look at me' I'm thinkin the problem comes either from an auto time out or from the completion of the charging of the power bank which is itself on a dribble charge from the car's electrics.
> 0 votes

---
Tags: power
---


title: LEDs on Arduino WiFi Shield

text:
# Question
Title: LEDs on Arduino WiFi Shield
I would like to know the purpose of the LEDs on top of the Arduino WiFi Shield: L9/Link/Error/Data (left in the picture). What do they indicate?

# Answer
The web page on the Arduino site for the board tells you in plain words what they mean:

> On board indicators The shield contains a number of informational LEDs:
>
> * L9 (yellow) : this is tied to digital pin 9
> * LINK (green) : indicates a connection to a network
> * ERROR (red) : indicates when there is a communication error
> * DATA (blue) : indicates data being transmitted/received
> 0 votes

---
Tags: led, wifi, shields, hardware
---


title: Can anyone identify these headers?

text:
# Question
Title: Can anyone identify these headers?
I'm very new to the Arduino platform and micro-controller projects in general, which is why I'm still learning about all the parts needed for circuit creation. There is one particular part that I would need for my current project but I'm having troubles figuring out what exactly this "thing" is ...

Please take a look at this picture: https://i2.wp.com/makezine.com/wp-content/uploads/2015/08/rolljam-hardware.jpg?fit=929%2C724

I need to know, please, what exactly these dual row female headers are called that are placed right to the Teensy board and are holding the two CC1101 units (so I can find them on Amazon or in other shops). Obviously, they are spanning the gap on the breadboard but is there something you can buy like this? Or are these common dual row headers that have had their pins bent and put into single row headers? I can't quite tell. The whole thing looks custom made though (to me it even looks like some hot glue was used, but I might be entirely wrong about that).

^^ And if my assumption is right, what might be the purpose of doing this? From my understanding this would create a full row for the power (instead of having two shorter rows), which the gap on the breadboard is meant to prevent?!

Thank you for suggestions.

# Answer
> 0 votes
From the pic, it looks like a 2x16 female header, PCB mount, with the pins bent outward and soldered to some male header pins.

I think they do this to provide mating sockets for the 2x5 male pins on the CC11001s that can be hooked up to a breadboard.

You could avoid this by prototyping on something like "stripboard' or 'Veroboard' like https://www.amazon.com/Soldering-Prototype-Printed-Circuit-Stripboard/dp/B019Q14GRQ/ and cutting/soldering a few traces where appropriate.

Or you could use a small chunk of stripboard tor protoboard to do the adapting from the 2x5 at 0.1" centers, to 2x5 on 0.1"x0.4" centers.

---
Tags: pins, breadboard
---


# Question
Title: Function for converting milliseconds to minutes?
I'm playing around with a Neopixel strip and want to be able to enter the amount of minutes I want an LED to do something rather than in milli seconds. So for example,

```
void loop() {

colorWipe(strip.Color(0, 0, 255), 50);
delay(sConversion(5));

colorWipe(strip.Color(0, 0, 0), 50);
delay(sConversion(5));

```

In my mind this should then delay the code by 5 minutes instead of doing

```
void loop() {
colorWipe(strip.Color(0, 0, 255), 50);

delay(300000);

```

The function I wrote is

```
sConversion(int minutes) {
    int milli = minutes * 60000;

    return milli
};

```

When I write this same function in JS it returns the correct value, 300000. But when I run it in the Arduino IDE the blue light never changes.

I have this function outside my void loop() and void setup(). Is that the correct place to put it? I have no errors returned.

Full code sample

```
void setup() {

strip.begin();
strip.show();

}

int sConversion(int minutes) {
    int milli = minutes * 60000;

return milli;
}

void loop() {

colorWipe(strip.Color(0, 0, 255), 50); // Blue
delay(sConversion(1));

colorWipe(strip.Color(102, 204, 0), 50); // Green
delay(300000);
}

void colorWipe(uint32_t c, uint8_t wait) {
for (uint16_t i = 0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
    };
};

```

Is this the reason?

> No other reading of sensors, mathematical calculations, or pin manipulation can go on during the delay function, so in effect, it brings most other activity to a halt.

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

# Answer
> 2 votes
Your `sConversion` returns an `int` as argument. You need to declare it as `unsigned long`.

This is what you are lookin for:

```
unsigned long conv(int x) {
  return x * 600000L;
}

```

# Answer
> 0 votes
> Function for converting milliseconds to minutes?

1 min has 60 seconds and 1s has 1000 me.

So take the ms and divide it by 60k you will get its equivalent min.

# Answer
> 0 votes
```
int sConversion(int minutes) {
    int milli = minutes * 60000;

return milli;
}

```

If minutes is greater than 1, you will overflow the int and not get the right answer. Use unsigned long here instead.

```
unsigned long sConversion(int minutes) {
    unsigned long milli = minutes * 60000ul;

return milli;
}

```

---
Tags: led, neopixel
---


# Question
Title: Accessing a C++ static variable from gcc inline asm
For some reason I want to mix a bit of assembly with C++ (not C).
To allow the code to be compilable using the standard Arduino IDE, I don't want to use direct assembly source.
I don't want to use a wrapper C file either.

My problem is as follows:

I have a class with a single instance (implementing some kind of driver) that looks like this:

```
class cDriver {
public:
    char ISR_param;
    // ...
};

cDriver Driver;

```

If I want to access the `ISR_param` of this single instance from within an ISR, I can do something like:

```
ISR (TIMER2_COMPA_Vect) {
    do_something_with (Driver.ISR_param);
}

```

This works like a charm: the address of `Driver.ISR_param` beign a constant, the compiler simply generates an `lds r24, &Driver.ISR_param` instruction to load the proper byte as a parameter for `do_something_with`.

Now when I try to replicate the same mechanism with inline assembler, things get a lot more complicated.

The address of `Driver.ISR_param` is only known to the C++ compiler as an mangled label, and I can't find a way to pass it to the inline assembler to generate the equivalent `lds r24, <&Driver.ISR_param>`.

# trying to remane the variable

The renaming of variables for assembly like so:

```
char global_var asm("my_var");

```

and an attempt to use it like so:

```
asm ("lds r24, my_var\n");

```

will compile, but produce a linker error (`my_var` is undefined).

Looking at the object symbol table, the only label for `global_var` is a C++-like mangled name.
However hard I tried this renaming trick, I could not bring the compiler to generate a `my_var` label.

# trying to use asm constraints

A constraint like

```
asm (lds r24, %0\n" : : "I"(&global_var));

```

will simply not compile. I scoured the possible parameter types and could not find a way to let the assembler know about this bloody address.

# a terribly awkward workaround

The only way I found to make the compiler generate this dreaded `lds r24,...` instruction is to perform an actual function call.

So you can do something like:

```
__attribute__((always_inline)) give_me_my_friggin_variable(char data)
{
    asm volatile ("cmp  %0,%0\n"::"r"(data));
}

ISR (TIMER2_COMPA_Vect, ISR_NAKED) {

    <some prologue to save SREG and all needed registers>

    //...

    give_me_my_friggin_variable(Driver.ISR_param);

    // continue assembly code with r24 properly initialized
}

```

That will generate:

```
    lds r24, <the proper address> // added by the compiler...
    cmp r24,r24                   // ...because of the register constraint here

```

Well, that sort of works, but at the cost of generating a totally useless instruction.

# so my question is...

Is there a simpler way to let the assembler know about addresses of C++ static variables?

# Answer
Try this:

```
asm volatile("lds r24, %0" : : "i" (&Driver.ISR_param));

```

The `"i"` constraint means you provide an integer constant. It can be any integer, unlike the uppercase `"I"` constraint which is limited to 6-bit positive integers.

**Addendum**: The constraints supported by gcc are listed in the gcc documentation, section Constraints for `asm` Operands:

* The `"i"` constraint is listed in the subsection “Simple Constraints” and is described as:

> An immediate integer operand (one with constant value) is allowed. This includes symbolic constants whose values will be known only at assembly time or later.

* The `"I"` constraint is in the subsection “Machine Constraints” and, for the AVR architecture, is defined as

> Constant greater than -1, less than 64.
> 4 votes

---
Tags: arduino-ide, c++, gcc
---


# Question
Title: Getting an error while uploading code to Arduino when ESP8266 is attached
I am trying to use an ESP8266 and an Arduino to access the Arduino from the network. I tried to do something but I'm facing some challenges. I hope I am using the correct board "Generic ESP8266 Module".

```
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial esp8266(rxPin,txPin);

void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  delay(1000);
}

void loop() {
  Serial.println("Sending an AT commands");
  esp8266.println("AT");
  delay(30);
  while(esp8266.available()) {
    String data = esp8266.readStringUntil('\n');
    Serial.println("Got response from esp8266: " + data);
  }
}

```

**Error**

```
Archiving built core (caching) in: C:\Users\XYZ~1\AppData\Local\Temp\arduino_cache_322251\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____feb0d75f3cf4e05271af4f91549cd009.a
Sketch uses 226657 bytes (52%) of program storage space. Maximum is 434160 bytes.
Global variables use 32464 bytes (39%) of dynamic memory, leaving 49456 bytes for local variables. Maximum is 81920 bytes.
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

```

# Answer
First off you have the wrong board selected. It's the Arduino Uno that you are programming, not the ESP8266. Just because you have connected an ESP8266 to the Arduino doesnt't magically change what the Uno is.

Secondly you cannot have anything connected to pins 0 and 1 of the Arduino while programming. Those pins are used for communication with the PC. As a general rule it is best to never use ghem for anything.

To communicate between the Arduino and the ESP8266 you should either pick two other pins and use SoftwareSerial or invest in a board that has at least one independent UART (such as the Mega2560 or the Leonardo).
> 3 votes

# Answer
Uploading programs to the Arduino requires the RX and TX lines. The ESP8266 module is probably interfering. You will need to disconnect the ESP8266 module, or at least, don't power the module while uploading.

Connecting the ESP8266 to RX/TX pins will probably also prevent you from using the serial terminal to output debugging information.

An alternative would be to use the (not so great, but it works) SoftwareSerial library.
> 0 votes

# Answer
I believe you are trying to directly program the ESP8266 and you're simply using the Arduino Uno as a USB to serial interface for your computer. There are many tutorials on the web on how to do this. First thing I see wrong with your setup is you've left the Arduino Uno MCU attached to the board. The first thing you'll want to do is remove this chip carefully (the pins can bend easily so apply force evenly). Right now when the Arduino IDE tries to talk to the ESP8266 the communication is going to both the ESP8266 and the Arduino. Physically removing the Arduino MCU chip will ensure any communication is directly with the ESP8266.

Also make sure you are connecting the correct voltage. ESP8266 can only handle 3.3V max, while the Arduino runs at 5V mostly. I believe the Uno board provides a 3.3V output but I'm not 100% sure.
> 0 votes

---
Tags: arduino-uno, arduino-ide, esp8266
---


# Question
Title: Pointer problems using Adafruit MotorController
This may be a very simple problem but it has had me going round and round in circles, it is VERY similar to this \[ Problem with wrapping Adafruit Motor Controller function calls in a class\] question but try as I might I couldn't resolve the issue using this example. So I will include my code and hope that someone with more experience takes pity on me. This code compiles with no errors but the motors don't start Like the linked question it all worked before it was separated into the individual files.

robot.ino:

```
#include "E:\chhs2017\LegoRobotics\SketchesThatNeedToWork\RobotBase\RobotBase.h"

RobotBase *base;

void setup(){
    base = new RobotBase();
}

void loop(){
    base->moveRobotForward(base->HALF_SPEED);
//  base->stopRobotAfter(1500);
}

```

RobotBase.h:

```
#ifndef ROBOTBASE_H
#define ROBOTBASE_H

#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

class RobotBase{

    public:
        const int MAX_SPEED = 255;
        const int THREE_QUARTER_SPEED = 190;
        const int HALF_SPEED = 127;
        const int QUARTER_SPEED = 90;
        const int MIN_SPEED = 30;

        RobotBase();

        void moveRobotForward(int inSpeed);
        void moveRobotBackward(int inSpeed);
        void moveRobotLeft(int inSpeed);
        void moveRobotRight(int inSpeed);
        void rotateRobotRight(int inSpeed);
        void rotateRobotLeft(int inSpeed);
        void stopRobotAfter(int time);

    protected:
        Adafruit_MotorShield AFMS;
        Adafruit_DCMotor *myMotorM1;
        Adafruit_DCMotor *myMotorM2;
        Adafruit_DCMotor *myMotorM3;
        Adafruit_DCMotor *myMotorM4;
};
#endif

```

RobotBase.ino:

```
/*************************************************************
* this is the robot base control class which is designed for a
* four wheel robot construction using an Adafruit_DCMotor controller
* and and arduino Uno
**************************************************************/

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
#include "E:/chhs2017/LegoRobotics/SketchesThatNeedToWork/RobotBase/RobotBase.h"

RobotBase::RobotBase()  {
    AFMS = Adafruit_MotorShield();
    myMotorM1 = AFMS.getMotor(1);
    myMotorM2 = AFMS.getMotor(2);
    myMotorM3 = AFMS.getMotor(3);
    myMotorM4 = AFMS.getMotor(4);
}

void RobotBase::stopRobotAfter(int time){
    delay(time);
    myMotorM1->run(RELEASE);
    myMotorM2->run(RELEASE);
    myMotorM3->run(RELEASE);
    myMotorM4->run(RELEASE);
}

void RobotBase::moveRobotForward(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(FORWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(FORWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(FORWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(FORWARD);
}

void RobotBase::moveRobotBackward(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(BACKWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(BACKWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(BACKWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(BACKWARD);
}

void RobotBase::moveRobotLeft(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(FORWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(BACKWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(FORWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(BACKWARD);
}

void RobotBase::moveRobotRight(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(BACKWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(FORWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(BACKWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(FORWARD);
}

void RobotBase::rotateRobotRight(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(FORWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(FORWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(BACKWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(BACKWARD);
}

void RobotBase::rotateRobotLeft(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(BACKWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(BACKWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(FORWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(FORWARD);
}

```

Thanks in Advance!

# Answer
> 0 votes
Hey Guy's As I suspected it was actually an easy fix after leaving it alone for a couple of days came back with fresh eyes and saw the problem straight away. I had failed to start the MotorController board. So all that was needed was the begin function call `base->AFMS.begin();` in the setup of robot.ino, all working fine now. Thanks again for your help.

# Answer
> 1 votes
It may be the way you are initializing the motor shield object. Try doing:

```
RobotBase::RobotBase() : AFMS() {
     myMotorM1 = AFMS.getMotor(1);
     myMotorM2 = AFMS.getMotor(2);
     myMotorM3 = AFMS.getMotor(3);
     myMotorM4 = AFMS.getMotor(4);
}

```

---
Tags: c++, adafruit
---


# Question
Title: How to add this old BASIC code snippet to work in Arduino C++ for FastLED?
I've been trying to implement this old code that randomly transitions to RGB color into my Arduino board that uses FastLED.

```
Static Col1, Col2, Col3 As Integer
Static C1, C2, C3 As Integer
If (Col1 = 0 Or Col1 = 250) And (Col2 = 0 Or Col2 = 250) And (Col3 = 0 Or Col3 = 250) Then
  C1 = Int(Rnd * 3)
  C2 = Int(Rnd * 3)
  C3 = Int(Rnd * 3)
End If
If C1 = 1 And Col1 <> 0 Then Col1 = Col1 - 10
If C2 = 1 And Col2 <> 0 Then Col2 = Col2 - 10
If C3 = 1 And Col3 <> 0 Then Col3 = Col3 - 10
If C1 = 2 And Col1 <> 250 Then Col1 = Col1 + 10
If C2 = 2 And Col2 <> 250 Then Col2 = Col2 + 10
If C3 = 2 And Col3 <> 250 Then Col3 = Col3 + 10
leds[x] = RGB(Col1, Col2, Col3)

```

Here is my Arduino setup:

```
#include <FastLED.h>

#define LED_COUNT 60
#define LED_OUT       13
#define BUTTON_IN     10
#define ANALOG_INPUT  A9
#define EXTRA_PIN_A    7
#define EXTRA_PIN_B   11

struct CRGB leds[LED_COUNT];

void setup() {
  Serial.begin(57600);
  LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
  LEDS.show();
}

void loop() {
  //where to implement
}

```

# Answer
I think this should work fine:

```
#include <FastLED.h>

#define LED_COUNT     96
#define LED_OUT       13
#define BUTTON_IN     10
#define ANALOG_INPUT  A9
#define EXTRA_PIN_A    7
#define EXTRA_PIN_B   11

struct CRGB leds[LED_COUNT];

void setup() {
  Serial.begin(57600);
  LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
  LEDS.show();
}

void colorLoop() {

  static int Col1;
  static int Col2;
  static int Col3;

  static int C1;
  static int C2;
  static int C3;

if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

// select a random number from 1 to 2 for the array
C1 = random(1, 3);
C2 = random(1, 3);
C3 = random(1, 3);
}

if (((C1 == 1) && (Col1 != 0))) {
    Col1 = (Col1 - 10);
}
if (((C2 == 1) && (Col2 != 0))) {
    Col2 = (Col2 - 10);
}
if (((C3 == 1) && (Col3 != 0))) {
    Col3 = (Col3 - 10);
}

if (((C1 == 2) && (Col1 != 250))) {
    Col1 = (Col1 + 10);
}
if (((C2 == 2) && (Col2 != 250))) {
    Col2 = (Col2 + 10);
}
if (((C3 == 2) && (Col3 != 250))) {
    Col3 = (Col3 + 10);
}

for (uint8_t i = 0; i < LED_COUNT; i++) {
   leds[i] = CRGB(Col1, Col2, Col3);
  }
delay(100);
LEDS.show();
}

void loop() {
  colorLoop();
}

```
> 1 votes

# Answer
Fairly simple. Understand what the basic code is trying to do and recreate that functionality in c.

In this case, it is looking for a set of conditions to trigger the generation of three random numbers which are then combined into a code for the run array.
> 0 votes

---
Tags: arduino-ide, c++, led, arduino-leonardo, rgb-led
---


# Question
Title: Connecting E-paper display (GD) to Arduino?
I'm still learning how to use Arduino and electrical components, but I will try my best to understand any answers!

So I just bought an e-paper display off a website, not from the manufacturer itself (http://www.good-display.com/products\_detail/productId=305.html). The product is a 1.54 inch E-paper display 200x200 partial update GDEP015OC1.

I was a bit puzzled by how to connect the display to the Arduino Uno. Turns out that to connect the display to a board, it needs a breakout board (is this the correct term?). I could buy it online from the manufacturer, however, it will take me at least a month and the shipping cost is too high.

I was wondering if it is possible for me to make my own breakout board? Is there any 'general' breakout board for an e-paper display, or does it have any special from the manufacturer? If it is possible, how difficult would it be for a beginner who has almost no knowledge on circuit building/electrical components?

The aim is just to display an image onto the e-ink display.

Thanks!

edit: I bought the mentioned display because of the size. I was afraid of not knowing how to connect the mention display (which is where I am now), so I bought this e-ink display also: https://www.smart-prototyping.com/E-ink-E-paper-Display-module-3.3V-2.04-inch-177x72.html I was thinking to take the 60mmx30mm display off the board and try connecting the 30mmx30mm display to the 'breakout board' if I am unable to build my own board. Both seemed to have the same pin number (need to confirm later).

# Answer
> 1 votes
E-ink displays require high voltages to operate them. They are electrostatic devices and the pixels need charging up to a high voltage (high compared to what an Arduino runs at) to attract the pigment powder (basically the same as laser printer toner) to create an image.

While it is possible to make your own board it's not something that is simple and straight forward. Designing boost converters requires a certain base level of knowledge and expertise to get it right. Not something I would recommend a beginner attempting.

Even though a display may have the same pin number as another it doesn't follow that the pins are in the same order on the connector. There is no standard and each display from different manufacturers (and even different displays from the same manufacturer) will have a different pin-out. You will need to compare the datasheets for the two displays to see if the pin-out is the same and if it isn't you would have to somehow map from one to the other on the driver board.

The simplest option is to just order the correct driver board for that display.

(Note: in this context it is called a *driver board* not a *breakout board*. A breakout board is typically a passive circuit board that converts from one hard-to-use connector or footprint to a simpler, say 0.1", header. A driver board contains active electronics, in this case a boost converter, to drive the device it is connected to.)

---
Tags: arduino-uno, display
---


# Question
Title: Choosing wireless tech for lowest possible lag
I am drafting a pub quiz project, where the Referee gives a signal and multiple players push their buttons. The first to push wins the right to give an answer.

I want all buttons (referee's + X players) to be wireless. Since the best quiz players can click a button within 10ms of the signal, it is very important that there is a very, very little variance in ping between different buttons. I cannot have players shouting "my button is laggy!" On the other hand, I don't want to use more expensive/complex tech than needed.

SO, what would be the optimal wireless tech to use? Please share your experience from similar projects (or just theoretical knowledge :) Here's what I researched so far (correct me if I'm wrong):

1. Bluetooth 4 LE (as in RFduino) Pros: 3-6ms latency (advertised), low energy Cons: cost, not more than 7 buttons to the device
2. Wi-fi Pros: 2ms latency (I justed pinged my wi-fi router), dozens of buttons if need be Cons: cost, power-hungry
3. RF data tranceiver Pros: dunno, cost seems to be a bit smaller Cons: multiple buttons at the same frequency will probably create a lot of noise
4. Simplest "Radio remote" Pros: zero lag since it's all electromechanical, no data Cons: multiple buttons at the same frequency won't work

So, did I miss anything? I appreciate any guidance.

# Answer
> 6 votes
I've used `NRF24L01+` chipset 2.4GHz wireless modules with Arduino before, and found them to be great, and super cheap (~$10 for 10 of them on ebay!). They have 3 modes of transmission: 250kbps, 1Mbps, and 2Mbps. The range decreases accordingly with higher bitrate, but the time spent sending a message does too. There are multiple Arduino libraries (e.g. RF24, Mirf, RadioHead) and tutorials for using the modules (see http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01). They also have built-in mesh networking modes which may or may not be of use.

Versions with an RP-SMA antenna connector and an advertised range of up to 1000m are also available for about $5 each. I would recommend using one of these for the referee's button at least, depending on the range you need.

According to Charles Hallard of hallard.me, The non-amplified chips can get **30m line-of-sight range in 250kbps mode**, and I have verified this in my own testing.

According to user sporadic on diychristmas.org, **sending a 32 byte payload in 250kbps mode takes 1432µs** from the start of Tx mode on the transmitter to receiving the full message on receiver. This decreases to **444µs on 1Mbps mode** and **283µs on 2Mbps mode**.

Given these statistics, they fall well within 2ms latency for triggering, suitable for your application, and they use very little power. It's up to you to work out the best balance of latency, range and expense.

# Answer
> 4 votes
Have you considered using real time clocks? You could synchornise them all ahead of time and then use any wireless protocol. Once a button is pressed, you'll look for the unit that reports the earliest time stamp and then once a window of a few seconds has passed let it know that it won. I'd consider using WIFI (802.11) with ESP8266s, RTCs and take a wireless access point along.

This isn't an answer to low lag wireless but eliminates the need for it.

# Answer
> 1 votes
In my humble opinion it might be even cheaper if you use IR or some other type of light, assuming you can ensure line of sight. You can use different wavelengths to ensure separation of the signals.

# Answer
> 0 votes
Low low tech solution.

1. The transmitter sends out its clock signal on command.
2. The receiver just needs to detect detect the prrsence of that signal.

The whole thing can be rf, or light based - for example one of the led lights can be configured as the transmitter.

Everything should be well within 1ms.

---
Tags: bluetooth, nrf24l01+, button, rf, wireless
---


# Question
Title: Purpose of extra pin slots on Pololu DRV8835
I have a Pololu DRV8835 motor controller. I managed to properly solder and connect it and it actually works, however I've been wondering about the purpose of the extra pin slots - especially the ones without pins headers soldered to them on the right side of the picture below, but also the ones marked A and B (I assume these ones are an alternative way to connect to motors, though). I wasn't able to find anything about them, so I assumed that it may be obvious to someone who is not a complete beginner (like me). What, if anything, could I use them for if I soldered pin headers there?

# Answer
> 1 votes
A and B are the same as the A and B screw terminals.

The pins on the right, if you use your eyes and follow the traces, are the same as the pins that plug into the Arduino. I guess they are intended to be used to isolate the existing pin assignments (cut tracks on the underside between adjacent holes with a knife) and solder wires to other pins so you aren't limited to just using the pins they have assigned.

---
Tags: pins
---


# Question
Title: How can I work with two devices that use the SPI protocol?
I'm working with a project in which I need to use an SD card module and an RFID antenna simultaneously. The devices that I'm using are the MFRC522 and the CATALEX SD Card Adapter. Both have SPI Protocol, and they're using the libraries MFRC522.h and SD.h.

This is the pin layout that I'm using:

```
/////// For RFID //////////
             Arduino
             Mega
  Signal     Pin
  ---------------------
  RST/Reset  5
  SPI SS     53 (CUSTOM)
  SPI MOSI   51
  SPI MISO   50
  SPI SCK    52

//////// For SD ///////////
             Arduino
             Mega
  Signal     Pin
  ----------------------
  SPI SS     49 (CUSTOM)
  SPI MOSI   51
  SPI MISO   50
  SPI SCK    52

```

As you can see the only line that they are not sharing is the Slave Select (aside from the RST pin of the RC522 module), so I believe that my wiring is correct.
I tried setting in LOW the chip select of the device that I wanted to use and in HIGH the one that I didn't. But this didn't work.

Any help you could provide would be appreciated! Thanks!

# Answer
If that SD card adapter looks similar like the picture, I never could get it to work together with another SPI device.

What I used was a data logger shield for Arduino (with SD card slot and proto part, unused in my case), something like this: SD logger
> 0 votes

# Answer
I have a few of those in my parts box and I have left a little note with them that says "exlusive SPI" to remind myself. A search brings up this which seems to confirm it. The OP's solution of powering it on and off with a pin seems pretty smart to me - assuming it doesn't draw too much current from the output pin.

Update: I found this which suggests that powering the SD card adapter from an output pin is a bad idea. The card could be drawing more than the pins can reliably supply.
> 0 votes

---
Tags: arduino-mega, spi, rfid, sd
---


title: ESP8266 - UDP send interruptions

text:
# Question
Title: ESP8266 - UDP send interruptions
I'm trying to transfer data from ESP8266(NodeMCU ESP12E) to my laptop. I'm coding ESP using Arduino IDE. I am able to receive correct packets (each containing 400 bytes) on a visual basic console program. However, to see whether the transmission is continuous or not, I have toggled an output pin whenever UDP.endpacket() returns 1. I observed waveforms on DSO. I found that UDP.endpacket() does NOT return 1 many times and the there is no transmission from ESP for a significant amount of time (milliseconds). Refer attached waveforms.

Why does UDP.endpacket() return 0 for such long time? Why is UDP transmission getting interrupted? How can I solve this? Please feel free to ask for more details if necessary.

Code :

```
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "Connectify-me33";
const char* password = "donfour276";

WiFiUDP Udp;
unsigned int localUdpPort = 65000;

unsigned int dest_port = 11000;

unsigned char clientBuf[400];
int clientBuf_len=0;

#define test_pin 5

int return_udp_fcn = 0;

void setup()
{

  WiFi.begin(ssid, password);
  delay(5000);

  Udp.begin(localUdpPort);

  pinMode(test_pin, OUTPUT);
  digitalWrite(test_pin, HIGH);

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);

}

void loop()
{
        digitalWrite(test_pin, HIGH);

        //filling up buffer
        for(clientBuf_len = 0; clientBuf_len<=399; clientBuf_len++)
        {
            clientBuf[clientBuf_len] = 0x7E;
        }

        //UDP transmit
        Udp.beginPacket("172.22.0.1", dest_port);
        Udp.write((const uint8_t *)clientBuf, 400);
        return_udp_fcn = 0;
        return_udp_fcn = Udp.endPacket();
        if(return_udp_fcn){
          digitalWrite(test_pin, LOW);
        }
        delayMicroseconds(100);

}

```

# Answer
> 1 votes
I think you need a `delay(1);` after your call to `write()`.

There is/was a bug where the underlying buffer files up and can't get time to clear. It looks like it will require a change to the ESP8266 firmware from the manufacturers before it will get fixed properly.

See what you think:

https://github.com/esp8266/Arduino/issues/1696

https://github.com/esp8266/Arduino/issues/2285

---
Tags: arduino-ide, esp8266, wifi
---


title: arduino send logged data over wifi

text:
# Question
Title: arduino send logged data over wifi
I am working on air quality measuring project. it should be able to record gps and air quality data into a SD card and then when wifi is available it should send it to a server. Please help me decide the required hardware for this. Can i use ESP8266 module to send this data

# Answer
> 0 votes
You need:

* SD card + reader
* GPS module
* Air sensor
* WIFI ESP 8266 should be ok
* Arduino Uno or Mega, depending on if everything fits and calculations to be performed

Start with finding each component, read examples how to use them, than combine them.

Looks like a big project to start with if you are new to Arduino.

---
Tags: arduino-uno
---


# Question
Title: Which is RX and TX pin of the HM-10 module?
i recently bought hm-10 ble module which works using cc2541 ti SOC but problem is there are many ports the the bluetooth module but the seller has not mentioned which is rx and tx pins so... I wanted to connnect it with Arduino uno and use AT commands but now i am stuck can anyone in this community help me finding which pin is Tx and Rx and the data sheet of the module is difficult to find on the net .....

# Answer
That's not an HM-10 but an EY-08. It's the same chip, but it's been provided in a different footprint (and maybe with different firmware installed).

Pin P03 is TX and pin P02 is RX.

The AT command set, pinouts, and examples for wiring it are detailed here (Thanks to Mikael Patel for finding that link).
> 1 votes

---
Tags: arduino-uno, bluetooth, wireless
---


# Question
Title: How to receive and process a long string sent over serial?
I want to receive about 5kb of data in Base64 format. The following code does not work. Only a few characters are received, sometimes CPU crashes.

```
String content = "";
char character;

while (Serial.available()) {
       character = Serial.read();
       content.concat(character);
}

```

I do not care about ram usage since on ESP32 there is plenty. How can I get all the data? Example input: https://pastebin.com/wYG5AhHK

# Answer
> 2 votes
I had to read until delimiter :D

```
String receive() {
        String content = "";
        content = Serial.readStringUntil('\r');
        return content;
    }

```

Now it is fine. I will also change String to large char array.

---
Tags: serial, esp8266, esp32
---


title: Arduino Mega PWM doesn't work in C Code

text:
# Question
Title: Arduino Mega PWM doesn't work in C Code
Why such horrible Arduino's Mega PWM doesn't work??

Below is my code.

I try to set Fast PWM 8-bit to dim and light up a LED connected to OCR1A Pin. I try to do it in C language, completelly without Arduino's lbraries and it doesn't work at all.

I'm working with documentation and the code seems me to be correct. Almost the same code worked on ATmega8 and ATmega16 (obviously, with special setting for those special ATmegas) but this one doesn't.

The comments in this code point out, that I tried to use few other flags to check if it work with some of another settings.

```
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

//Anode of LED connected to OCR1A (digital pin 11)
#define LED (1<<PB5)

int main()
{
  DDRB |= (1 << LED);

  //FAST PWM 8-bit, set OCR1A at the Bottom
  TCCR1A = (1 << COM1A1) | (1 << WGM10);    // | (1<<WGM11) | (1<<COM1A0)
  //Prescaler :1024
  TCCR1B = (1 << CS12) | (1 << WGM12);     //| (1<<WGM13); //Presc :1024  (1<<CS10) |
  //Enable to interrupt Compare Match A
  TIMSK1 = (1 << OCIE1A);

  uint8_t i;

  sei();

  while (1)
  {
    for (i = 0; i < 255; i++)
    {
      OCR1A = i;
      // _delay_ms(5);
    }

    for (i = 255; i > 0; i--)
    {
      OCR1A = i;
      //_delay_ms(5);
    }
  }
}

```

}

# Answer
I'm not sure this is right:

```
#define LED (1<<PB5)

```

Since later on you use:

```
DDRB |= (1<<LED);

```

That would expand out to:

```
DDRB |= (1<<(1<<PB5));

```

That would equate to:

```
DDRB |= (1<<(1<<5));

```

Take it a step further:

```
DDRB |= (1 << 32)

```

Shifting 1 to the left 32 times on an 8 bit register results in:

```
DDRB |= 0;

```

Which of course does nothing.

I can't comment on the rest of the code, other than to say "without delays in your loops you won't get much sense out of it".
> 1 votes

# Answer
Majenko showed you one of your mistakes.

Then you wrote:

```
//Enable to interrupt Compare Match A
TIMSK1 = (1<<OCIE1A);

```

And this is your other mistake. You should not enable an interrupt unless you have defined an ISR for it. Otherwise your program will restart every time the interrupt fires.
> 1 votes

# Answer
My advice. Stay simple. Try to get your code to output a duty cycle first. From there try to get your code to vary the duty cycle.

Once you do that the issues with your code will be clear.
> 0 votes

---
Tags: arduino-mega, c, pwm
---


# Question
Title: Gate opener code help - should be working
Can anyone see any errors in my code that would affect the opening command? Upon first power up the open command (remoteA) works fine.

After that the opening command does what its supposed to except it only momentarily fires "digitalWrite (power, LOW)" command. It should be set LOW for the same amount of time as "digitalWrite (openGate, LOW)", but it doesnt.

Strange thing is, the close command code is almost identical and it always works as it should, no problems.

Any suggestions? (hopefully the code pastes in here ok, its acting weird)

```
/*
 *  Swing Gate Opener with 2Ch remote, gate lock, motor, buzzer, amp monitor
and two independent limit switches
 *
 *  By Darren Clarke
 *
 */
int current = A0;  // monitor motor current
int buzzer = 3;  // operation buzzer
int power = 5;  // 24v power on/off
int remoteOpen = 6;  // remote button A to digital pin 6
int remoteClose = 7;  // remote button B to digital pin 7
int openGate = 8;  // open gate to motor on digital pin 8
int closeGate = 9;  // close gate to motor on digital pin 9
int gateLock = 10;  // gate lock connected to digital pin 10

// variables
int openRelay = 0;  // variable to store the motor direction
int closeRelay = 0;  // variable for previous motor direction
int remoteA = 0;  // variable for remote A condition
int remoteB = 0;  // variable for remote B condition
int lock = 0;  // varialbe for gate lock
int mA = 0;  // variable for motor current
unsigned long previousMillisA = 0;
unsigned long previousMillisB = 0;
unsigned long currentMillisA = 0;
unsigned long currentMillisB = 0;

void setup() {
    // put your setup code here, to run once:
    pinMode(buzzer, OUTPUT);   // sets the digital pin 4 as output
    pinMode(power, OUTPUT);   // sets the digital pin 5 as output
    pinMode(remoteOpen, INPUT);   // sets the digital pin 6 as input
    pinMode(remoteClose, INPUT);   // sets the digital pin 7 as input
    pinMode(openGate, OUTPUT);   // sets the digital pin 8 as output
    pinMode(closeGate, OUTPUT);   // sets the digital pin 9 as output
    pinMode(gateLock, OUTPUT);   // sets the digital pin 10 as output
    digitalWrite(closeGate, HIGH);   // sets relay to open
    digitalWrite(openGate, HIGH);   // sets relay to open
    digitalWrite(power, HIGH);   // sets relay to open
    digitalWrite(gateLock, HIGH);   // sets relay to open
    analogWrite(buzzer, 0);   // sets buzzer off
    Serial.begin(9600);
}

void loop() {
    // put your main code here, to run repeatedly:
    remoteA = digitalRead(remoteOpen);   // read remote A input
    remoteB = digitalRead(remoteClose);   // read remote B input
    openRelay = digitalRead(openGate);   // read state of openGate
    closeRelay = digitalRead(closeGate);   // read state of closeGate
    lock = digitalRead(gateLock);   // read state of gate lock
    mA = analogRead(current);   // read value of motor current
    currentMillisA = millis();
    currentMillisB = millis();
    Serial.print("aIn ");
    Serial.print(remoteA);
    Serial.print(", bIn ");
    Serial.print(remoteB);
    Serial.print(", Open ");
    Serial.print(openRelay);
    Serial.print(", Close ");
    Serial.print(closeRelay);
    Serial.print(", Lock ");
    Serial.print(lock);
    Serial.print(", mA ");
    Serial.print(mA);
    Serial.print(", cur ");
    Serial.print(currentMillisA);
    Serial.print(", prev ");
    Serial.print(previousMillisA);
    Serial.println(" ");

// to open the gate
    if ((remoteA == HIGH) && (remoteB == LOW)) {
        delay(500);   // time for gate direction reversal
        digitalWrite(power, HIGH);   // stops previous movement
        digitalWrite(closeGate, HIGH);   // Stop gate open command
        analogWrite(buzzer, 100);   // starts buzzer
        digitalWrite(gateLock, LOW);   // energize lock open (unlock state)
        delay(500);   // time for lock to open
        digitalWrite(openGate, LOW);   // actuate gate open
        digitalWrite(power, LOW);   //  supplies 24v power
        previousMillisA = millis();  // set time references
        currentMillisA = millis();  // set time references
    }

// to stop open command
    if ((closeRelay == HIGH) && (currentMillisA - previousMillisA) >= 6000) {
        digitalWrite(gateLock, HIGH);   // denergize lock (locked state)
        digitalWrite(openGate, HIGH);   // stop open relay to motor after open
        digitalWrite(power, HIGH);   // remove 24v power
        analogWrite(buzzer, 0);
    }

// to close the gate
    if ((remoteB == HIGH) && (remoteA == LOW)) {
        delay(500);   // time for gate direction reversal
        digitalWrite(power, HIGH);   // stops previous movement
        digitalWrite(gateLock, HIGH);   // de-energize lock on quick reverse
        digitalWrite(openGate, HIGH);   // Stop gate close command
        analogWrite(buzzer, 100);   // starts buzzer
        digitalWrite(closeGate, LOW);   // actuate gate close
        digitalWrite(power, LOW);   // supplies 24v power
        previousMillisB = millis();  // set time references
        currentMillisB = millis();  // set time references
    }

// to stop close command
    if ((openRelay == HIGH) && (currentMillisB - previousMillisB) >= 6000) {
        digitalWrite(closeGate, HIGH);   // stop close relay to motor
        digitalWrite(power, HIGH);   // remove 24v power
        analogWrite(buzzer, 0);
    }

    delay(100);
}

```

# Answer
Ok, i figured it out.

Thanks all for your help.

It only happens on the A channel because its first in the series of the code. The turn off command after the timer isnt specific enough. The if conditions are met on the B channel so it keeps turning the power off immediately.

I just need be more specific in my if command or make another tweek.

Thanks guys, your suggestions caused me to do much more digging and code adjustments.

Its working like a peach now.

Thanks.
> 1 votes

---
Tags: code-review
---


# Question
Title: is using two UARTs wiser compared to I2C and UART with Arduino + Xbee + BNO055 Sensor
### Hardware

1. Arduino Nano
2. XBee Pro S1 (802.15.4) Modules
3. Adafruit BNO055 Absolute Orientation Sensor

### Purpose

I want to send the Euler angles and Linear Acceleration angles to the a central **XBee Coordinator** (can be connected to a Computer or a Single Board Computer) every **100 ms**

Since the BNO055 has **SDA** and **SCL** pins for I2C how will the performance of the Nano matter when sensor data is acquired from the BNO sensor and send to XBee module which will be connected to the **Hardware Serial UART** Port?

An interesting observation was that if one:

> Shorts the PS1 pin to 3.3V for the BNO055, the **SDA** and **SCL** will function as **RX** and **TX** pins for UART. source

In terms of interfacing, I can think of the **Xbee** now connected to the **Hardware Serial Port** and perhaps the BNO sensor will can be connected to the Nano via `SoftwareSerial` port. But will that serve any better purpose in terms of performance and data acquisition i.e. using two *Asynchronous* Serial Ports compared to one?

# Answer
> 1 votes
All software serial solutions are much less efficient than `HardwareSerial` (i.e., `Serial`). `SoftwareSerial` is particularly bad, because it disables interrupts for long periods of time. 95% of the MCU time can be spent twiddling its thumbs, waiting for each bit to come in.

Using the I2C interface for the BNO055 means that the Arduino hardware will independently and concurrently handle each *byte* of data from the BNO055 and from `Serial` (i.e., the XBee). Your sketch can continue to do other things while each byte arrives. This is most efficient.

Software serial port libraries handle each *bit* of data, sometimes to the exclusion of all other activity.

---
Tags: sensors, arduino-nano, xbee
---


# Question
Title: Adding an LCD to Uno but not enough pins left
I am an absolute beginner and wanted to build a simple home automation system using DTMF module using this guide. My problem is out of 12 pins most of them are getting used in DTMF module(5) and the relay module(4). So how do i add an LCD display to it?

# Answer
> 4 votes
You are using 8 GPIO pins for your existing modules. That leaves 12 left for an LCD (assuming you aren't using the serial port).

An LCD can work from as few as 6 pins (4 data, E and RS) - WR can be tied LOW and RESET can be tied HIGH, and the remaining 4 data pins left floating (or tied low).

That still leaves you 6 pins to do other things. Or 4 if you (advisedly) steer clear of using pins 0/1 for anything.

# Answer
> 1 votes
I suggest you first try every component separately (or if you are new to Arduino, try first simpler components like LEDs, switches etc),

As told by others the following components are easier to use:

* Use a matrix keypad, see for example keypad. To reduce the number of pins you can use a multiplexer, such as 74HC165. 74HC165 are very cheap, although they need some additional programming and are slower than using direct pins (although for a keypad you will not notice).
* Use a display like 1602 or 2004. See example at 1602 Display. Make sure you order one that has an I2C adapter attached to it (or solder it yourself if you feel comfortable).
* After you tested all components separately (make different sketches and save them in case you need them later), you can combine them.

# Answer
> 1 votes
You can use arduino mega rather than uno or nano .... Or can use \**I2C adapter to control your LCD display, I2C adapter only needs two pins to communicate with arduino and is easy to use ...... \**

# Answer
> 0 votes
You have chosen a mighty task as your first project. I suggest that you run through as many of the example programs as possible before undertaking your project.

Firstly, I would recommend a matrix keypad instead of the DTMF keypad as it is much easier to use with an Arduino. This will also allow you to use a multiplexer which would use fewer pins.

I2C allows you to communicate to the LCD with only 2 pins. Here is such a I2C LCD (with buttons) sold by Adafruit.

As well as the tutorial over at Adafruit, there is a tutorial on such a topic over at ArduinoInfo.

Alternatively, you could upgrade to a Arduino Mega which has 54 IO pins as apposed to 14 on the Arduino Uno.

# Answer
> -1 votes
If some of the pins aren't used at the same time there are ways to reuse them.

Otherwise use a serial shifter or o.o expanders to drive the LCD. 2 to 3 pins max. Even 1 pin is possible if you tolerate lower speed of update.

---
Tags: arduino-uno, lcd, pins
---


title: Arduino digitalWrite not working

text:
# Question
Title: Arduino digitalWrite not working
I am trying to control this OWI Robotic Arm using the Arduino's digital outputs (I am using pins 12 & 13).

If I wire up the wires to ground and 5V it goes one way, if I switch the wires, it goes the other way. However when I have the pins wired up to the digital pins, it does not work, but the on-board LED does blink.

The code:

```
int a = 12;
int b = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  //up
  digitalWrite(a, LOW);
  digitalWrite(b, HIGH);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
  //down
  digitalWrite(b, LOW);
  digitalWrite(a, HIGH);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
}

```

# Answer
> 1 votes
The problem you are seeing here is that the Arduino can provide *nowhere* near as much current through I/O pins as it can power. Quoting from the Arduino website:

> DC Current per I/O Pin: 40 mA

This means that each pin can power maybe a couple of LEDs, and that's it. Additionally, motors provide "back-EMF": When opening (cutting power) an inductive load (e.g. a motor), the current wants to keep going. This will damage whatever just opened unless protection is used. So, I wouldn't be surprised if you damaged your Arduino by attempting to drive a motor with it.

So, what *can* you do? Use an H-Bridge. This circuit will allow you to easily control a motor & its direction. Many circuits can be found online, but an easy solution is a cheap L298N module, which can be as cheap as $3 a piece. This will safely & easily control the arm. Connecting your Arduino with the following circuit & using your existing sketch will make it work.

simulate this circuit – Schematic created using CircuitLab

---
Tags: current, robotics, digitalwrite
---


# Question
Title: LEDs Randomly smooth transitioning, accounting for black or how-to switch using HSV
I am stuck trying to get it not to account for black in RGB. My first instinct was to use the HSV color spectrum over the RGB rainbow but, the same code will behaves differently in HSV. If i could get the same effect in HSV I would, and that would account for the black, but I have not found a solution for that or the accounting for black in RGB. Here is my code:

```
#include <FastLED.h>

#define LED_COUNT     96
#define LED_OUT       13
#define BUTTON_IN     10
#define ANALOG_INPUT  A9
#define EXTRA_PIN_A    7
#define EXTRA_PIN_B   11

struct CRGB leds[LED_COUNT];

void setup() {
  Serial.begin(57600);
  LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
  LEDS.show();
}

void colorLoop() {

  static int Col1;
  static int Col2;
  static int Col3;

  static int C1;
  static int C2;
  static int C3;

  if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

    // select a random number from 1 to 2 for the array
    C1 = random(1, 3);
    C2 = random(1, 3);
    C3 = random(1, 3);
  }

  if (((C1 == 1) && (Col1 != 0))) {
    Col1 = (Col1 - 10);
  }
  if (((C2 == 1) && (Col2 != 0))) {
    Col2 = (Col2 - 10);
  }
  if (((C3 == 1) && (Col3 != 0))) {
    Col3 = (Col3 - 10);
  }

  if (((C1 == 2) && (Col1 != 250))) {
    Col1 = (Col1 + 10);
  }
  if (((C2 == 2) && (Col2 != 250))) {
    Col2 = (Col2 + 10);
  }
  if (((C3 == 2) && (Col3 != 250))) {
    Col3 = (Col3 + 10);
  }

  for (uint8_t i = 0; i < LED_COUNT; i++) {
    leds[i] = CRGB(Col1, Col2, Col3);
  }
  delay(100);
  LEDS.show();
}

void loop() {
  colorLoop();
}

```

# Answer
Black will basically be when all the colours have reduced to 0. That can only happen when all three of C1, C2 and C3 are 1. So you basically need to ensure that never happens.

And that is simple enough to arrange, with a "try again" construct:

```
if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

    // select a random number from 1 to 2 for the C1,C2,C3 array
    do {
        C1 = random(1, 3);
        C2 = random(1, 3);
        C3 = random(1, 3);
    } while ((C1 == 1) && (C2 == 1) && (C3 == 1));
}

```

Pick three numbers. If they are all 1 then you are destined towards black. So go back and pick three new random numbers. Keep trying until you get at least one result that isn't 1.
> 1 votes

# Answer
For it not to be *black*, at least one color (R,G,B) have to be on.

Before assigning the color values to the LED, maybe you can try using the *constrain* function to keep the values within a range. For example,

```
...

Col1 = constrain(Col1, 50, 150);  //If anything falls below 50, set it to the minimum value (50)
Col2 = constrain(Col2, 50, 150);
Col3 = constrain(Col3, 50, 150);

for (uint8_t i = 0; i < LED_COUNT; i++) {
   leds[i] = CRGB(Col1, Col2, Col3);
}

....

```

Sure enough! adding the *constrain* function to one of the static integers fixed the RGB from going to black. Now simply set 50 as the min value in the rest of the code:

```
void colorLoop() {
    //Set the minimum value to 50
    static int Col1 = constrain(Col1, 50, 255);
    static int Col2;
    static int Col3;

    static int C1;
    static int C2;
    static int C3;

    if ((((Col1 == 50) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

        // select a random number from 1 to 2 for the C1,C2,C3 array
        C1 = random(1, 3);
        C2 = random(1, 3);
        C3 = random(1, 3);
    }

    if (((C1 == 1) && (Col1 != 50))) {
        Col1 = (Col1 - 10);
    }
    if (((C2 == 1) && (Col2 != 0))) {
        Col2 = (Col2 - 10);
    }
    if (((C3 == 1) && (Col3 != 0))) {
        Col3 = (Col3 - 10);
    }
    if (((C1 == 2) && (Col1 != 250))) {
        Col1 = (Col1 + 10);
    }
    if (((C2 == 2) && (Col2 != 250))) {
        Col2 = (Col2 + 10);
    }
    if (((C3 == 2) && (Col3 != 250))) {
        Col3 = (Col3 + 10);
    }

    for (uint8_t i = 0; i < LED_COUNT; i++) {
        leds[i] = CRGB(Col1, Col2, Col3);
    }
    delay(100);
    LEDS.show();
}

```
> 0 votes

# Answer
I found this approach works:

```
if (((Col1 <= 50) && ((Col2 <= 50) && (Col3 <= 50)))) {  //avoid black
   C1 = 2;
   C2 = 2;
   C3 = 2;
}

```
> 0 votes

---
Tags: led, arduino-leonardo, rgb-led
---


# Question
Title: Attiny85 - Method to discard glitched ADC values?
I have a problem i need to solve so i will simply it as much as possible.

Basically there is a system with a micro-controller where it reads 2 sensors. These 2 sensors are of variable resistance type, aka their measuring value is output as different resistance. For example one is a pressure sensor where at 0psi the sensor has a value of 20ohms to ground, and for 100psi it has a value of 120ohms. The sensor is connected between ground and a fixed value resistor so the output acts like a voltage divider.

The micro-controller seems to be multiplexing by switching pull up between each 2 sensors (probably because using a single ADC), at random times (as the microcontroller performs other functions) but approx. every 80ms for each sensor, and about 40ms between each sensor. So at 0ms it reads one sensor, at 40ms the other sensor, and at 80ms back at the first sensor and so on. I have no idea why they haven't used a fixed pull-up, but the pull-up is only done when the controller wants to read the sensor for only about 120us.

I wanted to read these sensors to input to an ECU, without affecting the original device. Thus the easiest solution i could think off as the pull-up isn't always high to perform a read, was to add another microcontroller (in my case a Digispark based on the ATtiny85 running at 16.5MHZ). Alternatively i could open up the device and modify it to use a fixed pull-up but let's say i want to avoid this route. The digispark essentially reads both sensor outputs and when it sees a voltage above ground it outputs it to the ECU. I have since then updated the program to check the ADC values it reads so that it is between the nominal range of the sensor. And while this works there are times where the ADC will read a wrong value and output it to the ECU which looks as random spikes and dips in the data.

Look at my following code:

```
  const int oil_in = 0; //P5
  const int temp_in = 1; //P2
  const int oil_out = 1; //P1
  const int temp_out = 4; //P4
  int oil_value = 0;
  int oil_value_good = 0;
  int temp_value = 0;
  int temp_value_good = 0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(oil_out, OUTPUT);
  pinMode(temp_out, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  oil_value = analogRead(oil_in);
  if (oil_value > 106 && oil_value < 466)
  {
    oil_value_good=oil_value;
    analogWrite (oil_out, oil_value_good/4);
  }

    temp_value = analogRead(temp_in);
  if (temp_value > 113 && temp_value < 920)
 {
    temp_value_good=temp_value;
    analogWrite (temp_out, temp_value_good/4);
  }
}

```

Each ADC pin has a range of acceptable values. These correspond to the MIN AND MAX nominal values for each sensor. However there are times where the ADC will read at the wrong time and it will output either a MIN or a MAX value depending on the condition. I can replicate this on the breadboard by having the input to the ADC reading a nominal value, and by shorting it to either ground or VCC (5V) i can sometimes trick the ADC to read a MIN or MAX value. And since the next measurement will be done after some time, the output will produce these spikes. Since there is no sync between the readings these error data can be sometimes be outputed for 1-1.5s.

I've tried thinking hard about this problem, but i am not sure for a certain solution that will eliminate this problem. ADC interrupts, changing ADC pre-scaler, filtering of data, problem the reading window is really small (100-120us).

Also nominal ADC input values for each sensors are between 0.56V-2.33V for one sensor, and 0.6V-4.68V for the other sensor. Not sure if the interrupt can even be activated at such low voltage.

How do you think i should proceed?

Kind regards

# Answer
> 2 votes
> I have no idea why they haven't used a fixed pull-up, but the pull-up is only done when the controller wants to read the sensor for only about 120us.

If you want to get a good resolution in the resistance measurement, the resistance of your pull-up should be in the same range as the resistance of your sensor. If your sensors have low resistance, this means the voltage divider will draw significant current. In order to save energy, it makes sense to power the voltage divider only while you are doing the measurement.

> the reading window is really small (100-120us).

That's short indeed. If you `analogRead()` a single channel in a tight loop, you will get one reading every 108.6 µs (128×14 CPU cycles ÷ 16.5 MHz), and you have a small risk of missing the window. If you are reading two channels, then you have about 50% risk of missing the window.

Here is what I would do:

1. Set the ADC prescaler to 64 instead of 128. This way you will get one reading roughly every 54 µs, and at least one sample (but more often two) during the reading window.
2. Read a *single channel* in a tight loop, until you get a value above your minimum. Then take one more reading and use the largest of the two as your “good” value.
3. Switch to the other channel and go back to step 2.

This assumes that outside the reading window your ADC input reads close to zero, as it is grounded through the sensor, with no pull-up. You then have, on each channel, a train of positive pulses, and you want to measure the height of those pulses. There is a small risk of you sampling the rising edge of a pulse, which could give a wrong value which is nevertheless above your minimum. If this happens, then the next sample will be near the center of the pulse. That's why I recommend taking one extra sample and using the largest of the two.

---
Tags: adc, digispark, attiny85
---


# Question
Title: Using Arduino to pass data from a coin collector to android app
Okay. Basically I want the android app to be able to recognize that a coin was inserted into the coin collector before it allows the user to use certain functions of the app.

However I am unsure what would be the best way to pass the data from the coin collector to the Android app. My currently train of thought is to have the coin collector connect to an Arduino board which would then connect to the android app and send the input through that connection.

I was wondering if anyone knows of a better way to achieve this, or whether this is an acceptable/standard solution.

Thank you in advance!

# Answer
> 0 votes
Here are a couple of opitions for you:

1- Bluetooth - if in close range, an HC-05 will work great.

2- Wifi - wifi can work good. It is a little more complex then bluetooth but its range can get further. For example, a Tweet can be sent each time a coin is detected.

3- GSM - it is pretty much texting. You can make it so the coin collector texts you or someone there is a coin.

All of these solutions work great with the MIT app creator. It makes the data you receive much easier to process.

# Answer
> 0 votes
My take: use a nodeMCU (an ESP8266 based board) instead of Arduino.

nodeMCU have WiFi and you can run a minimal WebServer on it, so your Android app can communicate using simple HTTP GET commands. Using Bluetooth is not as convenient.

That's means the Android programming part will be easy and you can extend your solution to other platforms (iPhone).

And you only need a browser to develop and test the Android-Web Server interface on nodeMCU

Maybe you can even run your entire app in the nodeMCU, and use only a browser to interact with the coin collector.

---
Tags: android
---


# Question
Title: using references to SFRs in gcc inline assembler
I want to write a driver that can use either timer0 or timer2, based on a choice made at compile time.

So I want all references to timer registers to be abstracted, e.g. OCRA for OCR0A/OCR2A, etc.

I could do it with plain macros, like so:

```
#define _CONCAT3(a,b,c)   a##b##c
#define CONCAT3(a,b)   _CONCAT3(a,b,c)

// set timer number globally
#define MY_TIMER 2

// define an alias for each control register
#define OCRA CONCAT3(OCR, MY_TIMER, A)

```

**but** for some reason I don't want to use macros there.

So I came up with this scheme:

```
typedef volatile uint8_t& tRegister;

constexpr volatile uint8_t& timer_register (volatile uint8_t& a, volatile uint8_t& b)
{ return MY_TIMER==0 ? a : b; }

tRegister OCRA = timer_register (OCR0A, OCR2A);

```

It works pretty well for all its awkwardness, *but* when I try to use this definition in an inline assembly directive, I get strange results:

```
asm volatile("lds r24, %0" : : "i"(&OCRA));

```

will get an `error: impossible constraint in 'asm'`

Now this:

```
asm volatile("lds r24, %0" : : "i"(&timer_register (OCR0A , OCR2A )));

```

will compile (and produce `lds r24, 0x00B3` as it should).

By definition a reference to a static variable is a constant address, known at compile time, so I can't see why it can't be used in this context.

So my questions are:

* what is going on there?
* how to alias these registers (without macros) to please the inline assembler?

# Answer
> 1 votes
You could use pointers instead of references. With pointers, you have the separate notions of “constant pointer” and “pointer to constant”. A reference is a kind of pointer coated with syntactic sugar. However, whereas you can have a “constant reference” (equivalent to *pointer to constant*), I do not know how to declare a “reference with constant address” (which would be the equivalent of a *constant pointer*). And this is your issue: the `"i"` constraint in the `asm` statement requires a constant.

Here is my take with pointers:

```
typedef volatile uint8_t * tRegister;

constexpr tRegister timer_register(tRegister a, tRegister b)
{ return MY_TIMER==0 ? a : b; }

// The `const' below is essential.
const tRegister OCRA = timer_register(&OCR0A, &OCR2A);

asm volatile("lds r24, %0" : : "i"(OCRA));

```

Of course, you then have to change all your `OCRA = ...;` statements with `*OCRA = ...;`, which is awkward. But note that the avr-libc defines the SFRs with macros equivalent to

```
#define OCR0A (*address_of_OCR0A)

```

If you want this convenience, you may have to resort to using similar macros yourself.

---
Tags: programming, c++, assembly, gcc
---


# Question
Title: Solution for simple multi-Arduino communication network (or alternative?)
I know similar question has already been discussed here but I could not get clear answer. Here is the thing: I have one master device - Mega2560, and multiple (about 9 but could be expandedin future) I2C perfiferals - displays, that can have one of two possible I2C IDs - limitation by the manufacturer. As I can't connect and talk to them from a single I2C bus I chose to attach each two of them to a Mini-Pro's I2C pins and connect the 5 Mini-Pros to the master. The question is am I going to the right direction, and which connection would do the trick? I2C is obviously out of question, so the remaining are UART and SPI. UART would require some external hardware to cope with multiple outputs from the slaves, SPI would require additional pins from the master for chip select signal. Data rates are not high - min 10-20 kbps. I think the SPI offers better solution, but I'm no expert, what do you think?

Cheers!

Stefan

# Answer
> 0 votes
SPI afaik is not good over bigger distances (\> 1 meter). If you need many CS signals you always can use a multiplexer (like 74HC595N). I am not sure if it is 'normal' to have many SPI devices connected to one Arduino though.

Other solutions: I2C, but I don't have much experience with them. I heard about I2C expanders (MCP23017) that maybe are useful.

Also RF might be a possibility, also depending on the distance and most important speed (and latency).

In case for the Mega, it has 4 UARTs so that could maybe be used to spread the load.

# Answer
> 3 votes
Thanks all for your answers.

I did some more research with the new info you provided and found my perfect solution: TCA9548A. That's a 1-to-8 port i2c multiplexer that will allow the master MEGA2560 to control up to 8 independent i2c buses, where I can connect my displays. The chip is dirt cheap here - 2 euro only, and it is available in the store.

Thanks again guys!

# Answer
> 0 votes
I would suggest using 485 communication though it will increase the hardware but you will be able to add upto 32 devices and also have greater communication distance. You can use MAX485 IC or you can directly use TTL to 485 Module

---
Tags: i2c, communication, spi, uart
---


# Question
Title: Is it safe to short two pins together for conditioning a sketch?
I want to make a sketch which behaves differently, i.e.:

```
pinMode(pin1, OUTPUT);
digitalWrite(pin1, HIGH);

pinMode(pin2, OUTPUT);
digitalWrite(pin2, LOW);

pinMode(pin3, INPUT);
// And a user decides to short pin3 with pin1 or pin2

if (digitalRead(pin3) == HIGH) {
  // behavior 1
} else {
  // behavior 2
}

```

But, I wonder whether shorting two pins with/without a resistor safe or not. If it is dangerous, what is an alternative way to do such a thing?

# Answer
> 3 votes
Firstly, why would you?

All you are doing is connecting the input pin 3 to either VCC or GND, since that is what setting a GPIO to HIGH or LOW gives you - why would you waste two GPIO pins for that purpose?

"shorting" an input pin with VCC or GND is what you do with a button or switch anyway. The resistor in that case is used to hold the pin in the opposite direction when the button isn't being pressed. The same effect can be created using a two-way switch connecting the pin to either VCC or GND with no resistor required.

So yes, you can "short" the input pin with an output pin safely - as long as that input pin never becomes an output pin at any time (hint: never use pin 13 on an Uno for this - it becomes an output to flash the LED during the bootloader over which you have no control. The same goes for the TX pin.)

---
Tags: pins
---


# Question
Title: Weird arduino bug, using microphone and relay
I made a clap light switch to control my room lights and ground LEDs, and it works perfectly but when ever I have both the LEDs and the lights on it kinda stops working. I use two claps for the lights and three for the LEDs. Does anyone know what could be wrong? here is my code.

```
/* DEFINE PINS */
const int buzzer = 2;
const int micPin = 0;
const int relayLED = 9;
const int relayLights = 8;

const int sampleWindow = 50;
const int N = 50;

unsigned int sample;

boolean lights = false; //lighs on or off
boolean leds = false; //leds on or off

double soundArray[N]; //array to check claps

int i = 0;
int clapsCount = 0;

void setup() {
  pinMode(relayLED, OUTPUT);
  pinMode(relayLights, OUTPUT);
  digitalWrite(relayLED, HIGH);
  digitalWrite(relayLights, HIGH);
}

void loop() {
  /* gets 50 constant sound sample and resets */
  if (i<N) {
    soundArray[i] = getVolts();
    i++;
  } else {
    i = 0;
  }
  if (i == N-1) {
    clapsCount = clapCount(soundArray);
  }

  /* if 2 claps detected do this */
  if (clapsCount == 2) {
    if (lights == false) {
      turnOnLights();
      lights = true;
    } else {
      turnOffLights();
      lights = false;
    }
    playSound();
    clapsCount = 0;
  }

  /* if 3 claps detected do this */
  if (clapsCount == 3) {
    if (leds == false) {
      turnOnLeds();
      leds = true;
    } else {
      turnOffLeds();
      leds = false;
    }
    playSound();
    clapsCount = 0;
  }
}

int clapCount(double soundArray[]) {
  int claps = 0;
  for (int j=0; j<N; j++) {
    if (soundArray[j] > 3.0 && soundArray[j] < 3.5) {
      claps++;
    }
  }
  return claps;
}

void turnOnLights() {
  digitalWrite(relayLights, LOW);
}

void turnOffLights() {
  digitalWrite(relayLights, HIGH);
}

void turnOnLeds() {
  digitalWrite(relayLED, LOW);
}

void turnOffLeds() {
  digitalWrite(relayLED, HIGH);
}

/* gets mic volts */
double getVolts() {
  unsigned long startMillis= millis();  // Start of sample window
  unsigned int peakToPeak = 0;   // peak-to-peak level
  unsigned int signalMax = 0;
  unsigned int signalMin = 1024;
  // collect data for 50 mS
  while (millis() - startMillis < sampleWindow)
  {
    sample = analogRead(micPin);
    if (sample < 1024) {
       if (sample > signalMax) {
          signalMax = sample;  // save just the max levels
       }
       else if (sample < signalMin) {
          signalMin = sample;  // save just the min levels
       }
    }
  }
  peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
  double volts = (peakToPeak * 5.0) / 1024;  // convert to volts
  return volts;
}

void playSound() {
  tone(buzzer, 1000);
  delay(100);
  tone(buzzer, 500);
  delay(100);
  noTone(buzzer);
}

```

**Edit:**
When I do both two claps and three claps, both lights turn on and no matter how many times I clap none of them turn back off.

**Edit 2:**
Components I am using are, a simple buzzer, and microphone called MAX4466 and a 5v relay with two outputs.

# Answer
> 0 votes
I've looked through your code and can't see anything obvious that is causing the problem, so I have refactored it a bit in the hope that the problem becomes more obvious.

```
/* DEFINE PINS */
const int PinBuzzer = 2;
const int PinMic = 0;
const int PinRelayLED = 9;
const int PinRelayLights = 8;

const int sampleWindow = 50;
const int MaxSamples = 50;

// Simple enumeration to clarify which state is on and off.
enum EOnOff { Off, On };
EOnOff lights = Off; //lights on or off
EOnOff leds = Off; //leds on or off

double soundArray[MaxSamples]; //array to check claps

void setup()
{
    pinMode(PinRelayLED, OUTPUT);
    pinMode(PinRelayLights, OUTPUT);
    digitalWrite(PinRelayLED, ConvertOnOff(leds));
    digitalWrite(PinRelayLights, ConvertOnOff(lights));
}

void loop()
{
    for (int sample = 0; sample < MaxSamples; ++sample)
    {   // Get the samples
        soundArray[sample] = getVolts();
    }
    switch (clapCount())
    {   // Analyse the samples
    case 2:
        lights = ChangeRelay(lights, PinRelayLights);
        playSound();
        break;
    case 3:
        leds = ChangeRelay(leds, PinRelayLEDs);
        playSound();
        break;
    }
}

/// Count the number of 'claps' in the sample data
int clapCount(/*clap array is global*/)
{
    int claps = 0;
    for (int sample = 0; sample < MaxSample; ++sample)
    {
        if (soundArray[sample] > 3.0 && soundArray[sample] < 3.5) /* Why 3.5?? */
        {
            ++claps;
        }
    }
    return claps;
}

/// Convert an EOnOff value to a HIGH or LOW value.
// OFF = HIGH
int ConvertOnOff(const EOnOff& state)
{
    return state == Off ? HIGH : LOW;
}

/// Change a relay to the given state.
/// Return the new state.
EOnOff ControlRelay(const EOnOff& state, const int& relayPin)
{
    EOnOff result = state == On ? Off : On;
    digitalWrite(relayPin, ConvertOnOff (result));
    return result;
}

/* gets mic volts */
double getVolts()
{
    const unsigned long startMillis = millis();  // Start of sample window
    unsigned int signalMax = 0;
    unsigned int signalMin = 1024;

    unsigned int sample;
    // collect data for 50 mS
    while (millis() - startMillis < sampleWindow)
    {
        sample = analogRead(PinMic);
        if (sample < 1024)                  // ?? Should this be 1024 or signalMin?
        {
            if (sample > signalMax)
            {
                signalMax = sample;  // save just the max levels
            }
            else if (sample < signalMin)
            {
                signalMin = sample;  // save just the min levels
            }
        }
    }
    const unsigned int peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
    const double volts = (peakToPeak * 5.0) / 1024.0;       // convert to volts
    return volts;
}

void playSound()
{
    tone(buzzer, 1000);
    delay(100);
    tone(buzzer, 500);
    delay(100);
    noTone(buzzer);
}

```

What I have tried to do is to reduce the number of lines of code. If there are less lines then there should be less bugs :)

You used a bool to record the on off state, I changed that to an enumeration because that adds a bit of clarity, and when working with mains voltages I like things being clear.

I changed your while loop into a for loop, I think it looks cleaner. This was also the reason I changed your if statements into a switch statement.

The guts of the if statements have been removed and placed in a function `ChangeRelay()`, it returns the new state of leds or lights. I could have gone with a reference to make `state` an in out parameter, but decided a return was simpler.

`ClapCount()` and `GetVolts()` are relatively unchanged apart from a bit of const'ing of variables to make things easier to read. Also you might have noticed I, j and N have all been removed, because single letter variable names are my nemesis, who knows what `q` means and why `r` and `t` are being added to it to make `z`?

ControlRelay lets you route all you relay switching through one function, if there was a copy and paste bug in your code (which I don't think there was) then they will either all work or not work now.

There is a big difference between "my" code and yours, you won't be able to switch both on at the same time because the switch statement won't let you. So in a way you problem is solved. If you really wanted to you could add:

```
case 5:
    lights = ChangeRelay(lights, PinRelayLights);
    leds = ChangeRelay(leds, PinRelayLEDs);
    playSound();
    break;

```

---
Tags: arduino-uno, relay
---