title: Can't assign elements to index in array

text:
# Question
Title: Can't assign elements to index in array
I'm trying to create an array of strings. I'm building each individual string by parsing a json file and getting the strings between '{'s and '}'s. However, for some reason, my array is only assigning one index with the string i want. This is my code:

```
  String day = "";
  String Combo[] = {"0","0","0","0","0","0","0","0"};
  int x = 2;
  int number = 0;

  /* Read data until either the connection is closed, or the idle timeout is reached. */
  unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    /* Reads one character at a time*/
    while (www.available()) {
      char sym = www.read();

      if (sym == '{') {
        x = 1;
      }
      if (x==1){
        if (!day.concat(sym)) {
          //Serial.println("concat() error!");
        }
      }
      if (x==1 && sym == '}'){
        x=0;
        Serial.println(number);
      }

      if ((number > 0) && (number < 9) && (x==0)) {
        Combo[number-1] = day;
        Serial.print(day);
        Combo[number-1] = day;

        Serial.println(F("-------------------------------------"));
        Serial.println(Combo[number-1]);

        Serial.println(F("-------------------------------------"));
        Serial.println(F("-------------------------------------"));
        day = "";
        number +=1;
        x = 2;
      } else if (number ==0 && x ==0){
        day = "";
        number +=1;
        x = 2;
      }
      lastRead = millis();

    }

  }

```

Which returns this:

```
{
    "firstString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "secondString"
    }-------------------------------------
{
    "secondString"
    }
-------------------------------------
-------------------------------------
{
    "thirdString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "fourthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "fifthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "sixthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "seventhString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "eighthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "secondString"
    }-------------------------------------

```

Based on this output I know that day is being constructed correctly but for some reason isn't assigned to an index in Combo (except "secondString") Does anyone know what's going on?

Ideally Combo would equal: {"secondString", "thirdString", ... "eighthString"}

# Answer
> 1 votes
I'm trying to understand your code.

1. It looks like `x` is a state variable, with the following values:

```
2 = "Looking for start brace (`{`)"
1 = "Found! Now accumulating `day` until stop brace (`}`)"
0 = "Finished!"

```

If so, you may instead want to use the following:

```
enum States { Looking, Adding, Done };

// int x = 2;
States state = Looking;

// x = 1
state = Adding;

// if (x==1){
if (state==Adding) {

```
2. If you follow the flow of code, when `number` is still `0` and `x` finally becomes `0`, you:

* Print out `number` \- the first line of your output;
    * You then miss the main `if` (`number` is *not* greater than `0`);
    * And enter the `else` (which is satisfied);
    * And then you immediately clear your hard-earned `day`.
3. The second time through, after `x` becomes `0` again, this time you:

* Print out `number` \- the second line of your ouptut;
    * You *do* enter the main `if`:

    + You assign `day` to `Combo[1]`
        + You print out only the first seven entries in the the array (you want `<=7`, not `<7`)

        - This should print out `0{?}000000` (I don't know what `day` should be).
            - The fact that it doesn't seems to imply that your `concat()` failed. Can you please change it to

            ```
            // day.concat(sym);
            if (!day.concat(sym)) {
                Serial.println("concat() error!");
            } // if

            ```
        + You then print out the row of dashes - and start a new line.
    * The third time through, it seems to work - you get your `{$ "first string" $}` (where `$` represents `\n` and/or `\r` \- can you strip those out?)

    ```
          // if (x==1){
          //    day.concat(sym);
          if (x==1 && sym>=' '){ // Don't concat new line characters!
              day.concat(sym);

    ```
    * And the final few times `concat()` seems to have failed again.

The reason I say "`concat()` has failed" is that it looks like `day` is still `""` when it is assigned to `Combo`

### Edit

You've changed the code so that the main if now does the following:

1. Assigns `day` to `Combo[number-1]`;
2. Prints out `day` \- this seems to work;
3. Assigns `day` to `Combo[number-1]` ***again***;
4. Prints out a line of hyphens - this works;
5. Prints out `Combo[number-1]` \- this does **NOT** seem to work;
6. Prints out two lines of hyphens - this works.

Since 5 is printing out nothing, it implies that 3 failed. This really does look like you're in a low-memory condition, and the system is failing to allocate memory from the heap.

You don't say what Arduino you're working on - note that most don't have much memory, and if you're already parsing a JSON file you've probably used a lot of it. You also don't say which version of the Arduino IDE you're using. There was a `String` bug in the earlier versions.

Rather than trying to use the String class (a renowned heap hogger), you should try to use normal `char` arrays and work the buffer management yourself.

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


title: Moving ATMEGA to 3.3V

text:
# Question
Title: Moving ATMEGA to 3.3V
I currently have a barebone arduino built from just an Atmega 328P and a 16Mhz external crystal.

I planning to move this system down to 3-3.6V but I have read that on low voltage I have to use 8Mhz crytstal so my only question is that because of this change do I have to take the chip out to reflash with the programmer again or it will work as it did before?

What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

# Answer
> ...I have read that on low voltage I have to use 8Mhz crytstal...

Technically you can run anywhere below 13Mhz or so, so you have lots of choice.

You may also be able to use the prescaler to divide the clock by 2, either by hoping the ATmega can run the short time at 16MHz, or by programming the CKDIV8 fuse to start it at 2MHz.

> ...do I have to take the chip out to reflash with the programmer again...

If you move to a frequency within spec with either a clock change or prescaler use, yes. The bootloader and Arduino libraries expect a 16MHz clock, so you will have to rebuild the bootloader with the new clock rate, and sketches that use `delay()` et alia as well as the intrinsic delay functions will also need to be rebuilt.

> What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

It may work, it may not.
> 4 votes

# Answer
> I planning to move this system down to 3-3.6V but I have read that on low voltage I have to use 8Mhz crytstal so my only question is that because of this change do I have to take the chip out to reflash with the programmer again or it will work as it did before?

Any time-sensitive code -- such as delays and UART I/O -- will run at half speed with the 8 MHz crystal. If any of this matters, you'll need to reprogram the chip. (This will include the bootloader, which will now run at half the baud rate it used to!) If this is OK, though, you can leave it alone.

> What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

The ATmega328P isn't specified to run reliably at 16 MHz at 3.3V. Many chips will actually work at this speed, but some will fail, possibly in subtle ways or at inconvenient times. Don't rely on it working.
> 4 votes

---
Tags: atmega328
---


title: How to make a Smart Light Bulb?

text:
# Question
Title: How to make a Smart Light Bulb?
I was wondering what I would need and what I should do, to make a **Smart Light Bulb**, like the Hue one from Philips.

1. I know these light bulbs can be **controlled** by their **Apps** from the smartphone, is there a way I can achieve this too?
2. What **components** would I need to purchase?
3. Is there a reference or a tutorial on how I should **program** this light bulb?

# Answer
> 4 votes
You could use an ESP8266 NODEMCU. There is an example for making it emulate a Hue bridge ( https://github.com/probonopd/ESP8266HueEmulator ). To have the official bridge control your lights would take Zigbee and finding out the protocol that Philips uses. Their API is open source, however the zigbee protocol they use is not afaik. ESP8266 is a very cheap solution that works with arduino ide and does not need an arduino. There are powerplugs which have an ESP8266 in them (https://www.itead.cc/smart-home/sonoff-sv.html)

---
Tags: led, bluetooth
---


title: Using an External ADC with Arduino

text:
# Question
Title: Using an External ADC with Arduino
For my project I have to measure a signal of the order of few microvolts. As we know the least an Arduino can measure is ~5mV, due to its 10bit ADC and 5V reference voltage.

A solution to this problem can be to use an external ADC (16bit, I think will do).

Can you please guide me on this problem.Is it possible to use a external ADC,if yes how should I.Any other simple solution ? Thank You

Anupam

# Answer
Yes, if you have a 0 to 30 mV signal that you need to measure to an accuracy of 2 microvolts, you'll need an ADC with an effective number of bits (ENOB) of at least 13.9 bits and an amplifier to make the signal to match the range accepted by the ADC. Most ADCs pretty much require some sort of op-amp or differential amplifier between such low-level input signals and the ADC input pins. A few ADCs have a differential amplifier already built in -- that makes things a lot easier to get working, but I don't know if any of such ADC available would meet the other requirements of your project.

I don't know any way to make such high-resolution measurements other than using a dedicated external ADC chip.

You'll want to read the ADC datasheet -- some of them, and so far all the microcontrollers I've seen that claim to have a built-in "16 bit ADC", have an effective number of bits (ENOB) worse than the 13.9 ENOB you need at the sampling rates I typically use.

Adafruit has a very nice tutorial describing how to connect the 12-bit ADC ADS1015 or the 16-bit ADC ADS1115 to an Arduino.

The Arduino playground has a brief tutorial describing connecting a 12-bit ADC MCP3208 or a 13-bit ADC MCP3304 to an Arduino.

I see from the Arduino blog and other sites that people have connected some even higher resolution ADCs to an to an Arduino board, including the 24-bit Linear LTC2440 ADC; the 18-bit LTC2400 ADC (24 bit at 5 samples per second); and the 24-bit ADC TI ADS1220.

Sounds like a fun project. Good luck.

EDIT:

Everyone that uses an ADC needs some antialiasing filter between the signal and the ADC.

People that measure very faint signals usually need some sort of amplifier between the signal and the ADC. You may find the list of suggested op amps on p. 7 of the AMP03 datasheet useful.

Because historically ADCs were expensive (and high-resolution ADCs were unavailable), people have developed many clever tricks for processing signals before feeding the processed signal into a relatively low-resolution ADC. (Lock-in amplifiers, chopper amplifiers, manual precision gain adjustment, manual precision offset adjustment, heterodyning, etc.)

Have you tried asking "What sort of amplifier do I need to measure ((something)) with a 16-bit ADC" at https://electronics.stackexchange.com/ to learn some of those tricks that specifically apply to ((something))?
> 2 votes

---
Tags: adc
---


# Question
Title: Cannot enter programming mode on Arduino Uno
I have an Arduino Uno that I've been programming with an AVR Dragon through Atmel Studio 7.

I did two things in close proximity, and I'm not entire sure which action is the culprit. I tried using the DebugWIRE interface (for the first time) instead of ISP in the tool select screen. I also hit the Arduino's reset button as Atmel Studio was compiling/uploading to the Arduino (stupid, I know.)

Now I cannot program with ISP the normal way, or do anything really. If I try to upload to the Arduino I get:

I've tried to use the device programming feature using the Dragon and change the fuses as I've read about in other posts and get:

I've tried burning a new bootloader with the Arduino IDE and the IDE tries ten times, but it tells me that the programmer is not responding.

When I plug my AVR ISP mk2 into a different Arduino Uno I get a nice constant green light. If I plug it into the board I've been discussing it blinks red.

I'm not sure where to go from here...

# Answer
> 1 votes
I think either the chip or the board is fried. Try swap the chip (only the chip) to the other board and retry loading the program.

---
Tags: avr
---


# Question
Title: Why doesn't this work on a Mega2560 although it works on an Arduino Uno
So, This is your code slightly altered. I am using it to read the readings of the roll and pitch of a quadcopter. I have tried using this code for a mega 2560 but it does not work in ports A0 and A1. I think it might in A5 and A6 but I am unsure how to alter this code. THank you, Rohan Paleja

```
/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: http://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */

#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[2]; // times of prev. rising edges
volatile unsigned long rcTimes[2]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter
int Roll, Pitch;
// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(9600);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[2]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    Roll = rcTimes[0];
    Pitch = rcTimes[1];

    sei();          // reenable interrupts

    Serial <<  " " << Roll << " " << Pitch
       << " "  << rcN << endl;

  }
  sei();            // reenable interrupts
  delay(1000);
}

```

# Answer
> 1 votes
You are trying to do an Pin Change Interrupt on Port F (A0-A7). On the arduino Uno, this port does support PCINT but not on the Arduino Mega.

An option is to use the Port K for the PCINT. Instead of A0 and A1 you then use A8 and A9. A few little changes in the code should do the job:

```
void setup_rcTiming() {
rcOld = 0;
pinMode(A8, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
pinMode(A9, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

PCMSK2 |= 0x0F;       // Four-bit mask for four channels
PCIFR  |= 0x04;       // clear pin-change interrupts if any
PCICR  |= 0x04;       // enable pin-change interrupts
}

```

and

```
ISR(PCINT2_vect) {
byte rcNew = PINK & 15;
...
}

```

---
Tags: arduino-mega
---


# Question
Title: Running sensor input for given time, stopping, then running seperate scheduled relay output
I've set up an Arduino Uno to run a pretty basic garden watering schedule, with the delay function.

I've now built a solar thermal water heater with a pump and tried running it separately through a 555 timer using a thermistor (33k Ohm approx). I couldn't get this running as the change in resistance with a water temperature rise to 30 deg or so wasn't enough to trip and untrip the 555 timer (thermistor at about 20 k at 20 deg, maybe 50k at 30 deg). (Any pointers to circuits that achieve this would be appreciated by the way.)

I've decided to try to run the solar thermal motor with my arduino set up as I have 2 relays free in a relay shield. My question is how I can run the sensor to start the solar thermal pump, then stop operating the solar thermal system and return to the garden watering code, then restart the sensor input, and so on. The issue is that my power supply is only 1 Amp, and running both systems at once might overheat it.

Hope this makes sense, Brian

# Answer
If you are just running the relays off the 1 Amp supply, and there aren't more than 6 relays they shouldn't draw more than an amp.(I will edit this statement if need be)

What you can do in the way of coding you can is to do a classic spinoff of using the `millis()` function.

```
//monitors temperature and schedules its operations
//RSM
#define TimeBetweenHydration 10000  //10 seconds
#define TimeBetweenThermal 1000  //1 second
#define Temperature_Thresh  25   //25°C

float temperature = 0.00;

unsigned long lastTempReadTime = 0;  //keep track of the time temperature was checked
//boolean MotorOn = false;  //state monitoring

unsigned long lastWaterTime = 0; //last time the system did something with the watering thing
//boolean Watering = false; //state monitoring

// other variables related to specifics
//…
//

void setup(){

//setup of analog inputs
//setup of digital pins

}

void loop(){

 unsigned long presentTime = millis();

if((presentTime - lastTempReadTime) > TimeBetweenThermal){
lastTempReadTime = presentTime;
 int inADC = analogRead(0);

  //do whatever conversion is needed to get a value of the temperature
temperature = inADC*3.14;

if(temperature > Temperature_Thresh){

//   if(!MotorOn){
     digtalWrite(RLY, HIGH); //turn on pump
//     MotorOn = true;
//  }
 }
  else{
  digitalWrite(RLY, LOW); //turn off pump
  }
}

   if((presentTime - lastWaterTime) > TimeBetweenHydration){
   lastWaterTime = presentTime;

//put your watering code stuff here

  }
}

```

If you want to make the pump run without a microcontroller you could use a comparator with the thermistor and use its output to switch a transistor. I do not have the 555 timer art skills.

T1 is you thermistor. You should use the values listed for R1 - R3. The transistor, coil and flyback diode are there to show how you should connect it up, the coil could be a motor or a relay to control the motor. The comparator changes around the 30-40Kohm mark.
> 1 votes

# Answer
I really appreciate your answer, thanks. I knew I'd have to let go of the delay function at some stage, and this is the moment I think ;)

As for the PS, I'm actually also powering two solenoid valves and the arduino through the same PS, so just being on the safe side.

I wasn't too happy with a transistor circuit I made previously, but I'll give yours a go for sure. I actually came up with a workaround, which is probably pretty lame. I rigged up a second 555 timer with a large resistor to switch on and off the supply to the first 555 with thermistor every minute or so (a la flashing LED). So the thermistor now goes to temp, switches on the load, but then won't switch it off; the second 555 then resets the first 555, load switches off and either immediately switches on again if at temp, or stays off. Pretty ugly, right!
> 1 votes

---
Tags: temperature-sensor
---


title: Arduino fast start not working properly

text:
# Question
Title: Arduino fast start not working properly
I have an Arduino 328p (custom) and I can program it using a FTDI header.

However, when I power it from the FTDI using only the RAW (5V) and GND, it only executes simple programs (example blink). If in my sketch I attempt to use SPI for example, it will just get stuck.

If I power the arduino from the FTDI with the DTR pin connected, it will work just as expected for any sketch. I can even remove the DTR pin at this point and there will be no issue.

What could be the cause of this behavior?
Can it be an issue with optiboot fast start?

**PS:** FTDI is configured for 5V but VCC for the Arduino is 3.3V (I'm using the MCP1703 regulator). This means that the Arduino is powered by 3.3V but the RST pin will have 5V.
**PPS:** The Arduino is running at 16MHz

# Answer
> 0 votes
The reason for this issue is to do with SPI.

Basically in my custom arduino I have a 4Mbit flash and it communicates over SPI. It seems that when the RST pin is connected it also automatically initializes the SPI protocol.

When the arduino is powered from RAW + GND directly from an external power source you need to initialize SPI manually.

In your sketch you need to:

```
    #include <SPI.h>

    void setup() {
        SPI.begin(); // this needs to be invoked before any SPI device gets initialized

        // initialize and use SPI devices
    }

```

---
Tags: ftdi
---


# Question
Title: Best practices for really long distance sensor deployments
I'm noob to Arduino and electronics, but here is a problem from life which I need to solve for myself:

We grow strawberries and early spring freezes can take most of the flowers from the plants. One way to protect this is to have some kind of heating in solar houses, but if you grow outside, your best option is to watering the flowers on the crops when the freezing comes.

I want to deploy at least 3-4 temperature sensors, which are placed at every parts of the land, which will send the data for an Arduino which will turn on the pump with a relay (for this part I also want to use a pre-built relay solution with socket plugs already built, I don't want to mess around with high electricity myself).

For a cable solution (like catKIT system) I need at least 100m cable for the farest part of the land, which can be managable, but later on, scaling the land lots of cables everywhere can be a problem.

So the best solution would be if every temperature sensor is a standalone station, data transmitted by wireless to the main Arduino which is triggering the pump. This way there will be lass cables on the land, less change to cable break by tractor, etc.

Also, with a wireless system, I don't have to deal with signal loss over the cable, just only wireless signal loss. Is it possible to correct this by middle wireless signal transmitter stations? Or even better, all of them connected to each other!?

Like if the farest sensor reading Celsius 0.8, middle sensor reading Celsius 1.2. Middle sensor have a variable to also consider any reading from the farest sensor, which is reading 0.8. If that reading under Celsius 1, than don't bother his own output, send 0.8 to the main Arduino which is triggering the pump.

These station's power input still need to be solved, but maybe solar panels can be an option? However I have a clue that night they will not work, most of them freezing comes at night.

I saw wireless shields for arduino which offering even a km range in ideal conditions. But how degrading when the conditions are not ideal, like a house wall, rain, fog, snow?

Is it possible to feed multiple wireless inputs too one arduino? 3-4-10-20 standalone stations which transmitting temperature reads for the main arduino. If one of them sends lower temperature than +1 Celsius, than the pump will be turned on. Is it possible to solve this?

Thank You for your answers!

# Answer
There's as many ways of solving your problem as there are of skinning a cat (those poor poor cats - always getting skinned... ;) )

As you have already noted there are two basic solutions: wired or wireless.

Wired does have one major advantage that you haven't really touched on (only mentioned in passing) and that is power. With a wired solution you can provide power over those same wires so you don't need to worry about solar panels, batteries, whatever. But wires can break, yes. So they're not ideal. But then what is?

With wireless you then introduce the major problem of power. Solar panels are one possible way of getting power, though they are expensive, and you need to "over spec" them to charge batteries so you continue to have enough power for the times when is little or no sun. Complementing them with wind power is also an option to boost the battery charge when its windy. It all adds up to very expensive sensors though.

A compromise might be to consider both options together. Turn the sensors into small clusters of sensors that are near by with a base station for those sensors that both gathers and stores the power needed for them, and performs the wireless communication. The sensors would then be wired to the base station. Your wires are then shorter, and your power is more centralised.

But what to then use for the wireless itself? Well, there it's really all down to frequency. There's two basic gropings here:

* High frequency - 2.4GHz - is great at unobstructed communication. That's the frequency your WiFi works on, and as you probably know it's great if there's no walls in the way. Add walls and the signal drops off considerably.
* Low frequency - 433MHz - Far far better at penetrating walls and things but much less bandwidth.

I have had distances of hundreds of meters using a 2.4GHz nRF24L01+ module with power amplifier and antenna. That's in open air with (pretty much) line of sight. Indoors the range is much much shorter. Put buildings in the way and your hundreds of meters drop down to tens of meters.

So if there are obstructions you're pretty much going to want to use the 433MHz range (there is another frequency, which is different depending on where in the world you are - 868MHz or 915MHz, so we'll ignore that for now).

There's plenty of modules around that run at 433MHz, some better than others. There is, however, a new standard emerging now that is designed specifically for this kind of thing - long range, low bandwidth, just for sensors (as part of the IoT bandwagon) called LoRa (short for **Lo**ng **Ra**nge) which aims at distances of 15km using very small amounts of power (tens of mA) which is ideal for solar powered operation. It also can use the 868/915MHz region as well.

The final option that you touched on without knowing it is that of a *mesh*. This is where all the nodes form a network and each node is capable of relaying data from other nodes to get to their destination. Kind of like how the internet works. There are some mesh libraries available for some radio modules on the Arduino, but I have no idea how good or reliable they are. The best ones would be completely self-healing with auto-discovery - add a node and the whole mesh works out how to route messages to the destination node; remove a node and the mesh works out new routes to pass the data around the hole it's created.

Creating a good mesh stack is not child's play, so you would want to research it properly and find the best modules with the best library support if you wanted to take this route. That's why LoRa is taking off - it's so much simpler to get wide coverage without the need of complex mesh systems.
> 2 votes

# Answer
Personally I wouldn't use an Arduino as a wireless sensor controller, I would use an ESP8226, which comes with WIFI interface built in. You can program this through the Arduino IDE in the same language, and its compatible with most Arduino sensors.

The ESP8266 also has the advantage that it can create a WIFI network of its own, because it can act as a WIFI client, a WIFI access point or both at the same time. So if you do have an issue with the range of the signals then you can program your own WIFI repeater, which could also measure the temperature at the same time. They come in many different shapes and sizes, I think you might be better having an external aerial capability, have a look around and see what you can find. They cost around $2 so they should break the bank.

As for powering it you could use solar or wind power to charge a battery. Probably the best sort of battery for this is a Lead Acid battery because they don't object to being trickle charged. Assuming you sensor station runs at 5V, you want at least a 6V battery. You charge a 6V battery at 7.2V, so your solar panel(s) should generate at least 7.2V in *average* sunshine. You also need to work out how much power you sensor station is going to need, factor in an extra for working in cold weather, etc and then multiply it by the number of hours per day want it to work (24?). This is the total power you need per day, so the output of you panels must be = (Required Power / Hours of Sun). At this point you are best looking for a COTs device to charge the batteries and achieve your needs.
> 2 votes

---
Tags: temperature-sensor, wireless, wires, solar
---


# Question
Title: Burn bootloader on custom ATmega 2560 board
I have developed and produced a custom board with a ATmega 2560 on it and a FT232RL for USB communication. I want to burn an Arduino bootloader onto the board without using an external Arduino as ISP. I can't seem to figure out how. When I just click "burn bootloader" from the arduino software it says:

> avrdude: stk500\_recv(): programmer not responding

What am I doing wrong and how can I correctly burn the bootloader?

# Answer
> 1 votes
To burn a bootloader you *have* to use some external device. That can either be another Arduino or a hardware programmer, like an USBASP or something similar.

You can't just magic the bootloader on there through the USB and a dose of wishful thinking. To use the USB you first have to have the bootloader on there.

---
Tags: bootloader
---


# Question
Title: How to do run time calibration for MPU9250?
Does anyone know how to do the run time calibration for MPU9250 ?

# Answer
I used this script to calibrate the MPU6050, which is the same as the MPU9250 minus the digital compass. This guide explains how to calibrate the MPU9250's magnetometer.
> 2 votes

---
Tags: arduino-uno, mpu6050
---


title: Grouping multiple pins to one variable

text:
# Question
Title: Grouping multiple pins to one variable
I'm new to all of this, but it's there a way to group a cluster of pins to one variable? I don't necessarily want the grouped pounds to be sequential.

# Answer
Only if you drop to low-level access, and only if the pins are on the same port.

```
#define pinset 0x55

 ...

PORTC |= pinset;
delay(1000);
PORTC &= ~pinset;

```
> 4 votes

# Answer
In the example of the constellations, consider using an array for each constellation where each element in the array corresponds to an LED output pin. You could simply put a 1 or a 0 in each array element to indicate if you want the corresponding LED output pin on or off. It would be easy then to create a function that you would pass a constellation array and would turn the LED output pins on or off based on the contents of the array.
> 0 votes

---
Tags: pins
---


# Question
Title: How can I get analog-in reading from Digital-PWM-out on the same board?
I have a wire going from `PWM4` to `A0` but I don't dare turn on my `Arduino Mega` in case this is incorrect.

`PWM4` will eventually go to an *analog* device but I want to make sure the read value is what I expect it to be. Am I okay to proceed with my current setup or do I need to throw in a `resistor` / conversion?

# Answer
> 3 votes
You are fine by doing that, but you won't get what you expect.

A PWM signal isn't an analog value. It's a series of pulses, the duration of those pulses is set by the (not accurately called) analogWrite. So sometimes the value is 5V and sometimes it's 0V. You need to get the average value by adding e.g. an RC-filter.

Another option is to add a proper DAC (digital to analog converter) chip to your circuit.

---
Tags: arduino-mega, pwm, analogread, digital
---


# Question
Title: How to calculate the needed voltage and current to supply for Arduino
I have Arduino MEGA and I'm connecting to it 5 servomotors.

```
{ 3 TowerPro M995
Basic Information

Modulation:  Digital
Torque:  4.8V: 130.5 oz-in (9.40 kg-cm)
6.0V: 152.8 oz-in (11.00 kg-cm)

Speed:  4.8V: 0.20 sec/60°
6.0V: 0.16 sec/60°

Weight:  1.94 oz (55.0 g)
Dimensions:
Length:
1.60 in (40.7 mm)

Width:
0.78 in (19.7 mm)

Height:
1.69 in (42.9 mm)
Motor Type:  3-pole
Gear Type:  Metal

2 Towerpro M996R

Basic Information

Modulation:  Digital
Torque:  4.8V: 130.5 oz-in (9.40 kg-cm)
6.0V: 152.8 oz-in (11.00 kg-cm)

Speed:  4.8V: 0.19 sec/60°
6.0V: 0.15 sec/60°

Weight:  1.94 oz (55.0 g)
Dimensions:
Length:
1.60 in (40.7 mm)

Width:
0.78 in (19.7 mm)

Height:
1.69 in (42.9 mm)
Motor Type:  3-pole

}

```

So how can I calculate the voltage and current needed to supply this Arduino?

# Answer
> 0 votes
Drive all your components simultaneously from an external supply at appropriate voltage. Measure current draw in series (set your multimeter's red cable on the 10A port and set it to 10A, and connect red to VOUT, black to ground). Don't hold the wires in your hands, use clip-ons. Let it run for a while, and pay attention to current fluctuations. Read the current requirements on the display. A power supply with a bit more amperage than necessary is a Good Thing(tm).

Edit: remember to get both normal load and stall measurements. It is wise to add some way of turning stalling motors off, since stalling is motor death. And sometimes power supply death - those segway-for-kids things come to mind (and make me snicker ... WHEN I WAS A CHILD WE HAD OUR FEET FOR TRANSPORTATION, AND SHOES, IF WE WERE LUCKY!).

# Answer
> 2 votes
Voltage is simple - a device has a requirement and that is what you have to provide. In the case of the servos that is a range of voltages that it can use. So 5V is a good voltage. The Arduino can take 5V if you feed it in to the 5V pin or the USB port, or 7-12V if you feed it in to the barrel jack.

The current you cannot calculate. You haven't provided enough information. The calculation, when you have the information, is quite simple: for all the devices on the same power supply add the currents requirements together. The supply has to be able to provide *at least* that amount of current.

---
Tags: arduino-mega, hardware, battery, electronics
---


title: RFID RF522 kit for access control

text:
# Question
Title: RFID RF522 kit for access control
I am trying the RFID RC522 reader kit with an Arduino UNO to built a controlled access system for a door.

Using the code below, I am able to read the UID of my card and light up an LED when the reader detects the card or the badge, however it will light up whatever card is presented to it even if the UID of this card is not entered as a String in my program.

My question is how can I enter hundreds of cards (depending on memory) that will unlock the door and have all the others set as unknown if not in my program.

Thank you very much for your help

```
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         //(or SDA) Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
// ===========================================================================
String read_rfid;
String ok_rfid_1 = "C5 12 E3 52"; // for the badge
String ok_rfid_2 = "9A 48 3A D5"; // for the card
// ==========================================================================
int led = 3;
// ===========================================================================
void setup() {
 Serial.begin(9600); // Initialize serial communications with the PC
 //while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
 SPI.begin(); // Init SPI bus
 mfrc522.PCD_Init(); // Init MFRC522
 mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
 Serial.println(F("Scan PICC to see UID, SAK, type, and data bleds..."));
  pinMode(led, OUTPUT);
}
// ===========================================================================
 void dump_byte_array(byte *buffer, byte bufferSize) {
  read_rfid="";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
 }
// ==========================================================================
void unlock() {
  digitalWrite(led, HIGH);
  delay(2000);
  digitalWrite(led, LOW);
}
// ======================================================================
void loop() {
 // Look for new cards
 if (! mfrc522.PICC_IsNewCardPresent())
 return;
 // Select one of the cards
 if (! mfrc522.PICC_ReadCardSerial())
 return;

  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println(read_rfid);

  if (read_rfid == ok_rfid_1 || ok_rfid_2) {
    Serial.println("Open");
    unlock(); // turns LED on
  }

  else {
    Serial.println("Stay Closed");
  }
}

```

# Answer
Your IF statement is the problem. `if (read_rfid == ok_rfid_1 || ok_rfid_2)` always evaluates to `True`. Your condition should be:

```
if (read_rfid == ok_rfid_1 || read_rfid == ok_rfid_2)

```

You also need to remove the spaces in the string literals if you want this condition to have the desired effect.

This approach isn't very good though, since you have to add more comparisons to the IF condition if you want to match more cards. You should use the byte arrays as they are, without converting to Strings; it can actually be a lot simpler to compare as well as memory-safe. Store all your allowed card UIDs in a 2-D array:

```
#define ALLOWED 2   // no of allowed cards
byte read_card[4];   // same purpose as before
bool found = false;  // to know when a valid card match occurs
byte cards[ALLOWED][4] = {{0xC5, 0x12, 0xE3, 0x52},
                         {0x9A, 0x48, 0x3A, 0xD5}};

```

Then you should get rid of `dump_byte_array()` and compare cards like this:

```
memcpy(read_card, mfrc522.uid.uidByte, 4); // copy UID into array with shorter name ;)

for (int i = 0; i < ALLOWED; i++){
  if (memcmp(read_card, cards[i], 4) == 0){

      found = true;
      break;
  }
}

if (found){
  Serial.println("Open");
  unlock(); // turns LED on
  found = false;
}
else {
  Serial.println("Stay Closed");
}

```
> 1 votes

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


# Question
Title: What speaker can you drive with output pin?
I'm wondering how to drive a speaker using an arduino output pin. I am using a pwm playback method with a sound data file. If you wire a speaker across an output pin and ground then how do you calculate what speaker power and impedence you can use without damaging the arduino? Is there a reference making these calculations?

Thanks

# Answer
The Arduino can supply 5V at max 20mA so 5/0.02 ⇒ 250Ω (if you can find such a beast).

NOTE you should use a capacitor to prevent DC flow if using a conventional speaker.

In general the larger the speaker the better. Tiny speakers are inefficient transducers. Hi-Fi speakers are not a good choice, as they are often inefficient, trading efficiency for linearity.

An alternative, if you are a scrounger, is to scavenge a transformer from an old transistor radio - this should give the best match.
> 2 votes

# Answer
Only very small ones with 20-30mA. Earbud-size and slightly larger. You can buy a 2x3W amplifier which runs on 5V, and gives you two audio channels - but it works fine for mono. It can drive my 4 ohm desktop speaker, and is probably too powerful for that. Read about signal voltage and resistance for speakers. IIRC small audio outputs (like from an mp3 player) switch from -2.5V to 2.5V, giving an RMS of 5V. Or perhaps that was just my player. The only way to know this is to measure it - I played a sine wave and got a circa value. Offhand I can't say how to drive negative voltages from an arduino without extra circuitry. Hope it helps (and show us your code :)
> 1 votes

---
Tags: speaker
---


# Question
Title: How to control a DC Motor with Hall Encoder using Arduino and Motor Driver?
I'm using a DC motor with Hall Encoder. I bought it from DX.

I have made all the connections to motor driver and arduino and I suppose all are correct. I've connected m1 and m2 pins of motor to that of motor driver, encoder A phase and B phase to arduino pins 3 and 11, and GND of motor to GND of Arduino and 3.3V pin of motor to 3.3V pin of Arduino. Also motor driver is also connected to arduino.

The problem is that I'm unable to run the motor but I can count the rotations made by the motor. Please help me with the working code. Thanks.

# Answer
What are the "m1" and "m2" pins you mention?

On the diagram I see on that link, the pins "1-M1 motor -" and "6-M1 motor +" should be connected to the motor driver. The other four pins should go to the Arduino only.

You can probably test the motor by disconnecting it and connecting pins 1 and 6 to a 9-12V battery or similar, to see if it turns.

By the way I guess the two Encoder Phase connections would be set up on the Arduino using PinMode setting "INPUT\_PULLUP". But as you can already read the positions, that part may not matter.
> 1 votes

---
Tags: arduino-uno, motor, l298n
---


# Question
Title: How does one use (specically the wiring) the OV7670 camera with the Arduino Uno?
If one could tell me where each of the pins on the back of the camera go to, that would be great. if someone added the code also that would be awesome.

# Answer
You need to connect A4 and A5 via pullup register to 3V and to I2C interface on Arduino Uno. And you need to connect A7 to XCLK signal via 2 registers.

You can find schema and code in my blog: How to connect Arduino Uno and OV7670
> 1 votes

---
Tags: arduino-uno, pins, wires
---


# Question
Title: not getting proper bitstream output in serial monitor using digitalRead
I am producing a data stream and feeding to a gpio pin. THe data is sampled at 2kbps. i want to dump this data into a file after a certain length of reading . how should i proceed with this ?

# Answer
Without seeing your code it's impossible to tell just what is happening, but I would guess you are reading and printing the *level* of the wave, not the *transitions from one level to another*.

For instance:

As you can see, just reading regularly and printing it (which itself is quite slow) results in 11001101 rather than the 10101 that you want. That's because the speed of your reading/printing and the frequency of your wave are completely separate things and out of step with each other. There's nothing to tie one to the other.

Instead you need to look for the transitions from LOW to HIGH and from HIGH to LOW. Only when the input *changes* should you look to see what the new level is and print that.

As you can see the 1 and 0 are *just after* the change in level, since it's impossible to do anything *during* a change, only *once the change has happened*.

You might code that as something like:

```
void setup() {
    Serial.begin(115200);
    pinMode(3, INPUT);
}

void loop() {
    static byte oldValue = LOW;     // Place to store the previous level
    byte newValue = digitalRead(3); // Read the current level
    if (newValue != oldValue) {     // The input has changed
        oldValue = newValue;        // Save the current level
        Serial.print(newValue);     // Print it.
    }
}

```
> 1 votes

---
Tags: arduino-uno
---


title: Informations lost in a string

text:
# Question
Title: Informations lost in a string
At first, I sorry if I make some English faults but I'm French.

So, I'm making a connection between a client and an Arduino Uno. I receive all data that I need but when I send a response to my client some characteres are lost. I receive this format : GET /?b=7&p=100$ (for exemple) And my Arduino sends this to my client : GET /?b=7&p=1d

This is the function where I get all data from my client :

```
void read_data(int *state, int *progress_program){
  // Check if there is a client
  EthernetClient client = server.available();
  if (client) {
    url = "";
    index = 0;
    Serial.println("\nnew client");
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.println(c);
       if(c != '$') { // if end of char
          url[index] = c;
          index++;
        } else {
          url[index] = '\0';
          int i;
         Serial.print("\n");
          for(i=0;i<index;i++)
            Serial.print(url[i]);
          if(interpret(state, progress_program)){
            action();
            delay(100);
          }
          answer(client);
          break;
        }
      }
    }
    url[0] = '\0';
    // give the web browser time to receive the data
    client.stop();
    delay(100);
    Serial.println("\nclient disconnected");
  }
}

```

And the response sent to the client :

```
void answer(EthernetClient client){
  Serial.print("\nResponse"); // debug
  delay(100);
  client.print(url);
  Serial.print("Response Sent");
  delay(100);
}

```

With client.write(url) there is the same problem.

Have you got a solution? thanks

# Answer
> 1 votes
So, the solution was very simple, My pointer "url" received a constant null string with url=""; at the beginning. To initialize a string as null we need to make this :

```
 url[0] = '\0';

```

thanks

---
Tags: arduino-uno, ethernet, c, string
---


# Question
Title: How can you speed up the ADC on an ATtiny85?
I'm reading input from a camera and trying to reach a fast frame rate. Problem is my ATtiny85 has a pretty slow conversion time (65 - 260 µs Conversion Time). Is there any way to make this faster? I heard that you can set-up a prescaler for the `analogRead()` method by doing the following:

```
#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

void setup()
{
  #if FASTADC
   // set prescale to 16
   sbi(ADCSRA,ADPS2) ;
   cbi(ADCSRA,ADPS1) ;
   cbi(ADCSRA,ADPS0) ;
  #endif

  /*Rest of the code goes here.*/
}

```

I can't really make sense of the code and I found it on a less then reliable website so I was wondering if any of the gurus on here could let me know if what I'm attempting is possible and if this is the proper way of achieving my goal.

Also, would this also work for the Arduino Mega? I'm currently using it to test and debug my project since the ATtiny84 doesn't have serial output.

Datasheet: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85\_Datasheet.pdf

# Answer
> 2 votes
The ADCs in the ATtiny85 and ATmega2560 (the chip powering the Arduino Mega 2560) are pretty similar, except for the Mega having more inputs. In particular, the way you set the clock prescaler is the same, namely the bits ADPS2:0 in the register ADCSRA. You could use the same code to set the prescaler on both chips, but you probably don't want to unless your ATtiny is clocked at 16 MHz, like your Mega. I would normally just *set* the control register to the value I want, rather than touching only a few bits, but that is a matter of personal preference. So, to set the ADC clock of the Mega to 1 MHz, I would

```
ADCSRA = _BV(ADEN)    // enable the ADC
       | _BV(ADPS2);  // clock at F_CPU / 16 = 1 MHz

```

The same code would do the same thing on an ATtiny clocked at 16 MHz. If the ATtiny runs at 8 MHz, I would instead

```
ADCSRA = _BV(ADEN)    // enable the ADC
       | _BV(ADPS1)   // clock at
       | _BV(ADPS0);  //     F_CPU / 8 = 1 MHz

```

If you want to be generic:

```
#if F_CPU >= 12000000
# define ADPS_SETTING _BV(ADPS2)                 // F_CPU / 16
#else
# define ADPS_SETTING (_BV(ADPS1) | _BV(ADPS0))  // F_CPU / 8
#endif

ADCSRA = _BV(ADEN)      // enable the ADC
       | ADPS_SETTING;  // clock somewhere near 1 MHz

```

As bigjosh explained in comments, the prescaler setting is a trade-off between speed and accuracy. I recommend you read the article on the Arduino ADC by Nick Gammon. He did some tests at various speeds which showed that you can get decent results with clock speeds up to 1 MHz, then it becomes pretty bad at 2 MHz and mostly useless beyond. You may want to run the same tests with your particular setup.

Except for the very first conversion, which takes longer, an ADC conversion takes 13 cycles of the ADC clock. If you run that clock at 1 MHz, that is 13 µs per reading. If you get the readings with `analogRead()`, you won't get one reading every 13 µs, because the CPU needs extra time to execute the code you have between successive calls of `analogRead()`. You can save time by having the CPU and the ADC work in parallel, maybe along these lines:

```
ADCSRA |= ADSC;     // start the first conversion
for (int i = 0; i < NB_READINGS; i++) {
    loop_until_bit_is_clear(ADCSRA, ADSC);  // wait for the ADC
    uint16_t reading = ADC;     // get the reading
    ADCSRA |= ADSC;             // start the next conversion
    process(reading);           // process the reading we have
}

```

This way you process one reading while the ADC is taking the next one. Or you can set the ADC to “free running mode” (where it takes one reading after another without ever stopping) and get the readings in an interrupt service routine. Whichever method works best depends on your particular application: the amount of works your CPU has to do while reading the ADC and whether you can afford to do the whole series of readings with interrupts disabled.

---
Tags: arduino-mega, programming, attiny, adc
---


# Question
Title: PCINT with my arduino UNO says redefinition of 'void __vector_4()'
So i'm working on a quadcopter controlled by the arduino UNO, and focusing in pin interrupts for the reciever. This is the code for the reciever.

```
unsigned long timer[4];
byte last_channel[4];
volatile int input[4];

void rx_initialize() {
  PCICR |= (1 << PCIE0);
  PCMSK0 |= (1 << PCINT0);
  PCMSK0 |= (1 << PCINT1);
  PCMSK0 |= (1 << PCINT2);
  PCMSK0 |= (1 << PCINT3);
  Serial.begin(9600);
}

ISR(PCINT1_vect) {

  timer[0] = micros();//Lire la valeur PWM en microsecondes

  //////////////////////////CHANNEL1/////////////////////////////
  if(last_channel[0] == 0 && PINB & B00000001){//vaut digitalRead(HIGH); mais en plus rapide
    last_channel[0] = 1;//le state est HIGH
    timer[1] = timer[0];//Lire combien de temps HIGH
  }
  else if(last_channel[0] == 1 && !(PINB & B00000001)){
    last_channel[0] = 0;//le state est HIGH
    input[0] = timer[0] - timer[1];
  }

  //////////////////////////CHANNEL2/////////////////////////////
  if(last_channel[1] == 0 && PINB & B00000010){//Rising
    last_channel[1] = 1;//le state est HIGH
    timer[2] = timer[0];//Lire combien de temps HIGH
  }
  else if(last_channel[1] == 1 && !(PINB & B00000010)){//Falling
    last_channel[1] = 0;//le state est HIGH
    input[1] = timer[0] - timer[2];
  }

  //////////////////////////CHANNEL3/////////////////////////////
  if(last_channel[2] == 0 && PINB & B00000100){//Rising
    last_channel[2] = 1;//le state est HIGH
    timer[3] = timer[0];
  }
  else if(last_channel[2] == 1 && !(PINB & B00000100)){//Falling
    last_channel[2] = 0;//le state est HIGH
    input[2] = timer[0] - timer[3];
  }

  //////////////////////////CHANNEL4/////////////////////////////
  if(last_channel[3] == 0 && PINB & B00001000){//Rising
    last_channel[3] = 1;//le state est HIGH
    timer[4] = timer[0];
  }
  else if(last_channel[3] == 1 && !(PINB & B00001000)){//Falling
    last_channel[3] = 0;//le state est HIGH
    input[3] = timer[0] - timer[4];
  }
}

```

I'm using various files for every other part of the quadcopter such as PID controlling and IMU Reading.

But avrdude tells me that I did a redefinition of 'void \__vector\_4()'. Itried to look into PinChangeInt.h in the Arduino library folder but still no solution to the problem.

Thank you for your help!

# Answer
`__vector_4()` is just another name for `PCINT1_vect()`. The error message simply means that you have defined that function twice. One definition is explicit in the code you are showing to us. I cannot see the other definition: obviously you are not showing **all** of your code. Most likely that other definition lies inside some library you are using in your program.

Since you cannot define an ISR twice, you will have to use another PCINT which is not already in use. Or you could modify the library and try to merge it's `PCINT1_vect()` with yours.

BTW, the error message does not come from avrdude, it comes from the linker.
> 1 votes

# Answer
You should use the ISR(PCINT0\_vect) instead of the ISR(PCINT1\_vect).

Or if you want to use PCINT1:

```
PCICR |= (1 << PCIE1);
PCMSK1 |= (1 << PCINT8);
PCMSK1 |= (1 << PCINT9);
PCMSK1 |= (1 << PCINT10);
PCMSK1 |= (1 << PCINT11);

```

But them you have to change every PINB to PINC too as it uses a different PORT
> 1 votes

---
Tags: arduino-uno, programming, interrupt
---


title: Audio sampling and serial communication

text:
# Question
Title: Audio sampling and serial communication
**tl;dr:** The sample rate of my code seems to be lower than what I expect it to be. How can I fix this?

**Director's cut:** I am trying to sample audio data and send it via serial. The setup consists of a guitar plugged into an amplifier (about 10x) + low-pass filter (second order, around 1kHz) + voltage divider (centered at 2.5V), that is then connected to and Arduino Uno Rev3. When the Arduino receives a 'cap' command via serial, it enables the interrupt-based function that takes samples and sends them via Serial. With the 10-bit resolution, it gives me a number between 1 and 4 digits. With a baud rate of 115200 and adding 1 byte for the '\n' character, the slowest rate is of 2880 values per second, but most likely around 3.6k values per second (3+1 characters).

From what I understood (not used to working with timer interrupts), I've set up timer1 so that it doesn't have any prescaling, and it should be running pretty close to 2048Hz. The interrupt sequence reads the data at the analog input and sends it via Serial (for now, to the computer; later, a smartphone via Bluetooth).

To check if it is working, I am copying the data received by the computer, putting it into Matlab and running the `sound(data, sampleRate)` function. If I run it with 2048 as `sampleRate`, I get a clearly higher pitched sound, which indicates that the sample rate is in fact lower. Testing different values, I found that it sounds close enough around 1900.

From what I've read, the serial and the timer interrupt work in parallel, and the serial is faster than the capture. Why am I getting this apparently lower sample rate? How can I fix this?

**Code:**

```
// Variables
const int sampleRate = 2048; // Sampling rate
const int numSamples = 2048; // Number of Samples
//volatile int samples[numSamples]; // Data array
int currentSample = 0;
boolean capturing = false; // flags if it is in capture mode
boolean done = false; // flags if the capture is done
char chrCommand; // holds current character read
String strCommand; // joins the complete command string

// Functions
void captureSample();
void readCommand();
void executeCommand();

void setup() {
  /****************
   * Timer Setup
   ****************/
  cli(); // stop interrupts
  // set timer1 interrupt at 2048Hz
  TCCR1A = 0; // set the entire TCCR1A register to 0
  TCCR1B = 0; // set the entire TCCR1B register to 0
  TCNT1  = 0; // initialize counter value to 0
  // set compare match register for 2048Hz increments
  OCR1A = 7811; // = (16*10^6) / (sampleRate) - 1
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // no prescaling
  TCCR1B |= (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  sei(); // allow interrupts

  /****************
   * Serial Setup
   ****************/
  Serial.begin(115200);

  pinMode(13,OUTPUT);
}

void loop(){
  if(!capturing){
    // Case: waiting for command
    if(!done){
      if(Serial.available() > 0){
        readCommand();
        executeCommand();
      }
    }else{
      done = false;
    }
  }
}

/************************
 * Function Definitions
 ************************/

// Timer function
ISR(TIMER1_COMPA_vect){
  if(capturing){
    captureSample();
  }
}

void captureSample(){
  //samples[currentSample] = analogRead(0);
  Serial.println(analogRead(0));
  ++currentSample %= numSamples;
  if(currentSample == 0)
  {
    done = true;
    capturing = false;
  }
}

void readCommand(){
  strCommand = "";
  while(Serial.available() > 0)
  {
    chrCommand = ((byte)Serial.read());
    if(chrCommand == '\n')
    {
      break;
    } else
    {
      strCommand += chrCommand;
    }
    delay(1);
  }
}

void executeCommand(){
  // Command cap = capture
  if(strCommand == "cap"){
    capturing = true;
    return;
  }
  // Command mov = move
  if(strCommand == "mov"){
    // get the motor movement in the following command
    readCommand();
    moveMotor();
    return;
  }
  if(strCommand == "clr"){
    done = false;
    capturing = false;
    for(int i = 0; i < 2; ++i){
      digitalWrite(13,HIGH);
      delay(50);
      digitalWrite(13,LOW);
      delay(50);
    }
    return;
  }
}

```

# Answer
You calculation of the data rate is wrong:

* `Serial.println()` adds CRLF (i.e. "\r\n") to terminate the line, That's 2 bytes, not one.
* Each byte is sent by the serial port as one start bit, followed by 8 data bits, followed by one stop bit. That's 10 bits in terms of timing.

In the worst case scenario (value ≥ 1000), you are sending 6 bytes, or 60 bits: the fastest possible rate is 1920 samples per second. In the arguably most common case (100 ≤ value \< 1000), you send 50 bits per sample at up to 2304 S/s.

**Edit**: Here are a few optimization tips, just to make sure your program is not CPU-bound:

* Declare `captureSample()` as `static`, this way the compiler can inline it and save the call overhead.
* Make `currentSample` unsigned, this way the compiler can optimize the modulo operation into a bitwise AND.
* Replace `analogRead(0)` with a direct read of the `ADC` register, and start the next ADC conversion right away. This way you do not have to wait for 104 µs while the ADC does its work.
* You may want to move the `Serial.println()` out of the ISR, otherwise you may be blocking interrupts for too long if the serial port cannot cope with the sampling rate.
* Make some kind of binary protocol instead of using plain ASCII.

You may also trigger the ADC directly from a timer instead of going through the timer ISR (see the datasheet for details). You would then use `ISR(ADC_vect)` to retrieve the ADC result. This way you get a very steady (hardware controlled) sampling rate.

**More about the binary protocol**: you could send only two bytes per sample and remain ASCII-compatible (which is often desirable) by using 32 printable characters to represent 5 bits. This is the same idea used in base64, but simplified to use consecutive characters:

```
uint8_t high_5_bits = sample >> 5;
uint8_t low_5_bits  = sample & 0x1f;
Serial.write('@' + high_5_bits);
Serial.write('@' + low_5_bits);

```

This gives a stream of characters in the range `@A-Z[\]^_`. Then your maximum sampling rate is 5760 S/s.
> 4 votes

---
Tags: serial, audio, analog-sampling
---


title: Single #include pulls in all libraries

text:
# Question
Title: Single #include pulls in all libraries
I am tracking down the memory usage of an Arduino-like project I am working on (not a real Arduino, but has same microcontroller and it uses the Arduino build environment, version 1.6.8). I have some modules that I am using and placed them in the Libraries directory in my sketch directory:

```
Encoder
LiquidCrystal
OneWire
TGPages
TGPro

```

Now, when I compile a minimal sketch...

```
#include <Arduino.h>

void setup()
{
}

void loop()
{
}

```

...the compiled size is 450 bytes Flash and 9 bytes RAM. So far, so good.

Now here's the weird part: when I include a single header file from anywhere in the Libaries folder, the compiled size increases dramatically.

```
#include <Arduino.h>
#include "pins.h"

void setup()
{
}

void loop()
{
}

```

"pins.h" is located in the TGPro directory and only contains #defines, not even code or other includes.

```
....
Using library TGPro in folder: C:\Users\User\Project\TG\libraries\TGPro (legacy)
Using library OneWire in folder: C:\Users\User\Project\TG\libraries\OneWire (legacy)
Using library Encoder in folder: C:\Users\User\Project\TG\libraries\Encoder (legacy)
Using library LiquidCrystal in folder: C:\Users\User\Project\TG\libraries\LiquidCrystal (legacy)
Using library EEPROM at version 2.0 in folder: C:\Users\User\Project\TG\hardware\arduino\avr\libraries\EEPROM
Using library Wire at version 1.0 in folder: C:\Users\User\Project\TG\hardware\arduino\avr\libraries\Wire

Sketch uses 2,266 bytes (7%) of program storage space. Maximum is 32,256 bytes.
Global variables use 230 bytes (11%) of dynamic memory, leaving 1,818 bytes for local variables. Maximum is 2,048 bytes.

```

And I'm like: WTF? I'm not even referencing any of the files, still they get pulled in, wasting space. There are a few global, static variables in there which explain the used space and referenced code.

So, my questions:

1. Is het normal for Arduino to pull in *all* files in the Sketch\Libraries directory, regardless if they are referenced or not? It doesn't seem to do this with the 'core' libraries.
2. How can you prevent this? Suppose I have a large collection of modules that I use in various projects, but not all modules are used all the time. It would be a waste to include code that is never actually used.
3. How can I find out more about the code that is compiled in; I know the linker will leave out unreferenced code, but I want to make sure this is due to the statically defined variables.

# Answer
> 1 votes
What you are experiencing is due to the fact that your use case does not match with the Arduino foreseen use cases of "importing a library".

Basically you want the use case "include a file" and you get "import a library". The use case "import file" is simply not foreseen in the Arduino IDE. Because the Arduino IDE add the library to your code it also adds the source doe files to your code. When these source codes contain global variables (which is very common and not a bad practise in embedded world) these will be part of your final code. As such your sketch will increase size even if you do not use these global variables.

To answer questions
1) yes it is normal because the use case "include file" is translated into "include library" in .ino files in the Arduino IDE.
Why this does not happen for the core? The core is first linked into a archive and then linked to the sketch. This leaves the linker more options to remove stuff.

2) I think the easiest is to copy the pins.h file in your sketch work folder (and you probably will need to restart the Arduino IDE).
Another option is to go for a real IDE like the arduino eclipse plugin called sloeber (which I develop)
In sloeber you could link to the pins.h file instead of copying. You could also reference the pins.h with a (partial/full) path avoinding the library include.

3) All global variables, static and similar stuff in the source code of the "imported libraries"

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


# Question
Title: Making two points on a tm1637 display blink [ Solved ]
Hello! In my project, using a display controlled by a TM1637, I want to make the two points on the middle of the screen blink (as every clock does).

The following example, provided by the library I'm using, makes the two points blink as I want (`tm1637.point(POINT_ON/POINT_OFF);` is what enables/disbales the point):

```
#include <TimerOne.h>
#include "TM1637.h"
#define ON 1
#define OFF 0

int8_t TimeDisp[] = {0x00,0x00,0x00,0x00};
unsigned char ClockPoint = 1;
unsigned char Update;
unsigned char halfsecond = 0;
unsigned char second;
unsigned char minute = 0;
unsigned char hour = 12;

#define CLK 2//pins definitions for TM1637 and can be changed to other ports
#define DIO 3
TM1637 tm1637(CLK,DIO);

void setup()
{
  tm1637.set();
  tm1637.init();
  Timer1.initialize(500000);//timing for 500ms
  Timer1.attachInterrupt(TimingISR);//declare the interrupt serve routine:TimingISR
}
void loop()
{
  if(Update == ON)
  {
    TimeUpdate();
    tm1637.display(TimeDisp);
  }

}
void TimingISR()
{
  halfsecond ++;
  Update = ON;
  if(halfsecond == 2){
    second ++;
    if(second == 60)
    {
      minute ++;
      if(minute == 60)
      {
        hour ++;
        if(hour == 24)hour = 0;
        minute = 0;
      }
      second = 0;
    }
    halfsecond = 0;
  }
 // Serial.println(second);
  ClockPoint = (~ClockPoint) & 0x01;
}
void TimeUpdate(void)
{
  if(ClockPoint)tm1637.point(POINT_ON);
  else tm1637.point(POINT_OFF);
  TimeDisp[0] = hour / 10;
  TimeDisp[1] = hour % 10;
  TimeDisp[2] = minute / 10;
  TimeDisp[3] = minute % 10;
  Update = OFF;
}

```

I tried to do it as it was the famous "blink", but nothing works.

Here's what I have done:

```
#include "TM1637.h" // Library for the 4-Digit Display
#include "RTClib.h" // Library for the RTC
#include <SoftwareSerial.h>

#define CLK 6
#define DIO 7

TM1637 tm1637(CLK,DIO);
RTC_DS1307 RTC;

const int fotoRes = 2;

SoftwareSerial mySerial(10, 11);

void setup()
{
  pinMode(fotoRes, INPUT);

  RTC.begin();
  RTC.adjust(DateTime(__DATE__, __TIME__));

  tm1637.init();
}
void loop()
{
  DateTime now = RTC.now();

  tm1637.display(0,now.hour()/10);
  tm1637.display(1,now.hour()%10);
  tm1637.display(2,now.minute()/10);
  tm1637.display(3,now.minute()%10);

  tm1637.point(POINT_ON); //Like blink example.
  delay(500);
  tm1637.point(POINT_OFF);
  delay(500);
}

```

**EDIT: `tm1637.set(0-7)` ONLY set the brightnes of the screen. What makes the two pints appear is `tm1637.point(POINT_OFF/POINT_ON)`. I'm asking how can I do to make these two points blink. Thanks.**

*Arduino UNO R3, DigitalTube library by Grove*

# Answer
Calling the `point()` method only updates a flag; you see the effect the next time you try to display a number. You can use something like this:

```
void show_time(DateTime &t){
  tm1637.display(0,t.hour()/10);
  tm1637.display(1,t.hour()%10);
  tm1637.display(2,t.minute()/10);
  tm1637.display(3,t.minute()%10);
}

void loop() {
  DateTime now = RTC.now();

  tm1637.point(POINT_ON);
  show_time(now);  // changes take effect here
  delay(500);
  tm1637.point(POINT_OFF);
  show_time(now);
  delay(500);
}

```
> 1 votes

# Answer
I haven't used the TM1637 code, but I (think I) understand how it works.

In the original code is the following:

```
void setup()
{
    tm1637.set();
    tm1637.init();

```

But in your code you only do the following:

```
void setup()
{
    ...
    tm1637.init();

```

Have you tried adding the `tm1637.set();` line in?
> 0 votes

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


title: Arduino Audio Shield Problems

text:
# Question
Title: Arduino Audio Shield Problems
I recently bought a Velleman KA02 Arduino Audio Shield (http://www.velleman.co.uk/contents/en-uk/p579\_ka02.html), which uses an ISD1760PY audio chip and soldered it together. The first time I fired it up, it worked fine, I had freshly soldered it together. But from the next time up to now, if I press any button but the reset button, the onboard LED blinks 7 times and it doesn't record or do anything. I checked the solder joints and nothing fell out and I also checked the ISD1760PY datasheet but found nothing about my problem. Is there a way to fix this and why it it happening? Please note that I am not controlling the shield with SPI or with the Arduino.

This question was put on hold in the EE section so I an posting it here because the reason was that it has something to do with Arduino.

# Answer
> 2 votes
Look at page 35 of winbond datasheet. If the LED is blinking 7 times either the chip is in isp mode or in an unstated mode. This can happen after power off during erase function. I held erase button for about 20 seconds and after that I was able to record messages.

---
Tags: shields, audio
---


title: Complete Bread board arduino

text:
# Question
Title: Complete Bread board arduino
I bought a ATmega328 microcontroller and burn the bootloader. Now I want to upload code directly from pc to the microcontroller on bread board. I have max232 ic for the communication but I recently knew that I need a serial port rather usb to connect max232 to pc. There are many usb to serial converter available on the market but can I make my own? One more thing is there any other way burn program from arduino ide to microcontroller via USB on bread board without having the arduino board. Or can I burn program to microcontroller on the bread board from arduino board without removing the on board ic.

# Answer
> There are many usb to serial converter available on the market but can I make my own?

Yes, but if you need to ask how then you're not ready to undertake the task.

> One more thing is there any other way burn program from arduino ide to microcontroller via usb on bread board without having the arduino board.

Yes. The IDE doesn't care how you connect to the MCU, only that it has the appropriate bootloader for the programming method.

> Or can I burn program to microcontroller on the bread board from arduino board without removing the on board ic.

ArduinoISP will let you use an existing Arduino as an AVR ISP programmer. ISP does not require a bootloader, nor does it require a serial (UART) connection.
> 3 votes

---
Tags: avr
---


# Question
Title: Code example SPI multiple slaves Arduino DUE
I'm trying to get 2 devices (camera and sd card)to work on the SPI interface with an Arduino DUE. I'm having trouble finding example code online showing how to communicate with multiple slaves on the DUE as I know it is slightly different than with the UNO.
Questions I have include: How do you indicate you want to talk to a slave on pin 4? Instead of digitalWrite(4,LOW) do you call SPI.begin(4)? etc..

Can someone post some example code?

# Answer
Everything you need is given here - you just need to know how to put it together:

There are variants of all the major methods that take an extra parameter - that parameter is the first parameter in the parameter list and defines the SS Pin to use for that function. That includes the `.transfer()` function.

To use it you have to `begin()` all the pins you want to use SPI with. Then you can use `.transfer()` with those pins:

```
void setup() {
    SPI.begin(10);
    SPI.begin(4);
}

void loop() {
    // Receive using pin 10 as SS
    byte byteFromTen = SPI.transfer(10, 0x00);
    // Transmit 123 using pin 10 as SS
    SPI.transfer(10, 123);
    // Both directions:
    byte otherByteFromTen = SPI.transfer(10, 123);

    // Receive using pin 4 as SS
    byte byteFromFour = SPI.transfer(4, 0x00);
    // Transmit 123 using pin 4 as SS
    SPI.transfer(4, 123);
    // Both directions:
    byte otherByteFromTen = SPI.transfer(4, 123);
}

```

Doing multi-byte transfers is slightly more complex since you don't have control over the SS pin, so you have to use yet another version of the `transfer()` function that tells it to "continue" the transaction:

```
// Receiving 3 bytes using pin 4:
byte firstByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
byte secondByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
byte thirdByte = SPI.transfer(4, 0x00);

```

Of course, mixing reading and writing is pretty much the same as usual. For instance, to read the port A values from an MCP23S17 would look like:

```
SPI.transfer(4, 0x41, SPI_CONTINUE); // Address 0, read bit set
SPI.transfer(4, 0x12, SPI_CONTINUE); // Select register 0x12 (GPIOA)
byte porta = SPI.transfer(4, 0x00);

```

The `SPI_CONTINUE` tells the SPI system to keep the SS pin LOW. It is only then raised once it gets a `.transfer()` without the `SPI_CONTINUE`. This is the same as the traditional way of using `digitalWrite()` to lower SS before the first transfer and raise it after the last transfer.
> 2 votes

---
Tags: arduino-due, spi
---


title: Receiver Module Second Data Pin

text:
# Question
Title: Receiver Module Second Data Pin
Many of the receiver modules (MX-05V) working with the Virtual Wire library (*I would like to add a link here but it requires 10 reputation, so I'll do that later)* have two data pins. However only one of them is used in the examples I have seen so far.

This picture shows a transmitter (top left) and a receiver (bottom right). Apparently the receiver has four pins - two of them are data pins.

Image source

**What is the purpose of the second data pin on the receiver module and how to use it?**

# Answer
> 0 votes
I would expect only one data line output from the receiver.

Looks like the manufacturer might have just connected the 2 data pins together. You could try using either pin to confirm that the two data output pins are simply connected together.

---
Tags: wireless
---


title: send mixed data over serial

text:
# Question
Title: send mixed data over serial
I want to launch a communication between two Arduinos, in which case the first Arduino *(S)* sends data to the second one *(R)*. The type of the data is mixed, consisting of integers, longs, floats and maybe some text. For example:

```
{125, 1250, 12500, 125000, 1.25, 12.5, 125.0, "some text"}

```
* I thought about converting each one value to string, adding up all strings to a big one, and send the final string with `Serial.print(Big_string)`. In that case I reckon that it would be difficult for the Receiver to extract the string to the exact substrings and convert them to real values.
* A second thought was to convert all values to bytes and create a byte *(or char)* array, but each value would be limited to 0-255 *(let alone floats and text)*
* A third thought was to convert them to word type *(let alone the text)*, but I think that `Serial.print( )` sends only bytes, not words.

**In any case, which is the best way to send mixed data over serial?**

Any thoughts would be appreciated.

# Answer
I think the easiest way to solve your problem is using a separator and transmit the array values one after the other. That means having a `for` loop and in every iteration sending one value of the array with

`Serial.println(array[i])`.

The function will

* convert numbers into Strings so you will get "125", "1250", ...
* append a carriage return character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n')

On the receiver side you can simply wait for `Serial.read()` to equal the number `13` and (immediately afterwards) `10` and split the messages there. That works unless your transmitted strings contain new lines.

The disadvantage is, that numbers are of course transmitted in an *unefficient* way. If you want to transmit them as *real numbers* instead of strings you have to write your own protocol. This video "Wireless Module Multiple Receivers" goes into that direction, it's using a fixed packet length but it gives an idea of how such a thing works.
> 4 votes

# Answer
I have a library that does exactly what you want. It can also work with RS-485 and RS-422 multi-drop networks.

You can even get it communicating with a Linux computer (such as a Pi or BeagleBone Black) with the Linux library:

You can use it to send data of any kind between nodes and trigger specific functions to be executed (like RPC) at the remote end.
> 3 votes

# Answer
If you want to communicate between 2 arduino's with similar cpu (for instance uno and mega) I would go for binary data in a struct. When using a struct you can not use the String class but you can use a char array. Consider this struct as example

```
struct SerialDataPacket
{
        int someIntegerData;
        long someLongData;
        int someMoreIntegerData;
        char aString[20];
};

```

You can send this struct as follows:

```
String myString;
SerialDataPacket transmissionPacket;
transmissionPacket.someIntegerData=1;
transmissionPacket.someLongData=millis();
transmissionPacket.someMoreIntegerData=2;
strncpy(transmissionPacket.aString,myString.c_str(),min(20,myString.length()));
Serial.write((uint8_t *) &transmissionPacket, (uint16_t) sizeof(SerialDataPacket));

```

you can receive the struct at the other side as follows:

```
Serial.readBytes((uint8_t *) &transmissionPacket, (uint16_t) sizeof(SerialDataPacket));
myString=transmissionPacket.aString;

```

Again this method will only work if you have possessors with the same memory byte order. If the processors have a different bit (8 16 32 bit) you lust use processor independent types for it to work.
> 2 votes

# Answer
If your primary concern is transmission speed, you might consider turning everything into bytes and reversing the process at the other end. If speed is not important, you can use sprintf() to create a character string and sscanf() to parse out the character string at the other end.

Turning everything into bytes is a very custom / specific approach. A character would turn into 1 byte, an integer into 2 bytes, ect. You would have to write custom code to encode this and remember to write code at the other end to do exactly the reverse process. The advantage is that you would only be sending your data and no other information. But this approach is not vary flexible. If you were able to fit your data into 1 byte then suddenly needed 2 bytes (for example, a value once always less than 255 was now 300), you would have to re-write your code at both ends of the connection.

Turning everything into a string with sprintf() is very similar to printing out all your data. You will be including extra characters like commas and / or space for delineation. At the other end sscanf() is used to parse out the character string. At both ends, if done properly, all string assembly and parsing should be done by only these 2 calls. And some issues are taken care of automatically. For instance, the number 100 is 3 characters long and the number 10 is 2 character long. But the sprintf() and sscanf() calls automatically compensate for these (reasonable) variations and continue to work as expected.

added later...

FYI: Even though sscanf() is available for the Arduino, it is not clear to me if it is well supported. You might try testing (create and parse a string in the same sketch) what you want to send / receive before actually committing to this method.
> 1 votes

---
Tags: serial
---


# Question
Title: serial.write() five sensors and Processing
To all of this, hope to formulate the question right.

In my project I have 5 sensors connected to Arduino, which I want to interpret via Seria.write() --\> Processing.

Arduino:

```
firstSens = 100 + (155 * digitalRead(8));
secondSens = analogRead(A1)/4;
thirdSens = analogRead(A2)/4;
fourthSens = humData;
fifthSens = tempData;
int sensData[6] = {firstSens, secondSens, thirdSens, fourthSens, fifthSens};

int i;
for (i = 0; i < 5; i = i + 1) {
  Serial.write(sensData[i]);
}

```

Processing:

```
serialInArray[serialCount] = inByte;
    serialCount++;

if (serialCount > 4 ) {
  firstSens = serialInArray[0];
  secondSens = serialInArray[1];
  thirdSens = serialInArray[2];
  fourthSens = serialInArray[3];
  fifthSens = serialInArray[4];

  // print the values (for debugging purposes only):
  println(firstSens + "\t" + secondSens + "\t" + thirdSens + "\t" + fourthSens + "\t" + fifthSens);

  // Send a capital A to request new sensor readings:
  myPort.write('A');
  // Reset serialCount:
  serialCount = 0;

```

My problem is that sensors find their place in Processing's array randomly, so for example arduino's *firstSens* could be Processing's *secondSens* or *fifthSens*

Why is this happening and how can I control it?

# Answer
What is happening is you are just spewing out a list of numbers:

```
4132
132
1928
3240
1239
238
3048
391
... etc ...

```

There is nothing anywhere to say what anything is.

You need to add that kind of information. Either as a "start of data" tag before each block, or with each line. For instance:

```
---START OF DATA---
4132
132
1928
3240
1239
---START OF DATA---
238
3048
391
... etc ...

```

Or:

```
0:4132
1:132
2:1928
3:3240
4:1239
0:238
1:3048
2:391

```

It is then up to your processing application to interpret the data and work out what is what.

Personally I like using the second method since it means you don't have to send all the data every time - you can send different values at different speeds of update and maintain a "current value" at the Processing end. For instance if you have one value that updates frequently and others that don't:

```
3:4132
1:132
3:1928
3:3240
3:1239
2:238
3:3048
0:391

```

You don't even have to use numbers, you could use words:

```
pressure:4132
temperature:132
pressure:1928
pressure:3240
pressure:1239
humidity:238
pressure:3048
rainfall:391

```
> 1 votes

# Answer
I have done similar code for our car project dash display

you're looking for something like this on your Arduino side:

```
  Serial.print("U*"); //A header
  Serial.print("A");  //a token to indicate the message payload
  Serial.print(avgRPM);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("B");  //a token to indicate the message payload
  Serial.print(avgVoltage);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("C");  //a token to indicate the message payload
  Serial.print(avgCurrent);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("D");  //a token to indicate the message payload
  Serial.print(avgThrottle);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("E");  //a token to indicate the message payload
  Serial.print(avgBrake);
  Serial.println("");

```

and something like this on processing side:

```
 if (port.available() > 0) {
    data = port.readStringUntil('\n');
  }
  String payload = "";
  if (data != ""){
    int offset = data.indexOf("U*"); //this is our Header (0x552A)
    if(offset>=0){
      payload = data.substring(offset+3, data.indexOf('\n'));
      switch(data.substring(offset+2, offset+3)){
        case "A":
          RPM = payload;
          break;
        case "B":
          voltage = payload;
          break;
        case "C":
          current = payload;
          break;
        case "D":
          throttle = payload;
          break;
        case "E":
          brake = payload;
          break;
        case "F":
          telemBits = payload;
          break;
        default:
          //packet not recognised
      }
    }
}

```
> 0 votes

---
Tags: serial, sensors, processing-lang
---


title: Trouble reading analog (PWM)

text:
# Question
Title: Trouble reading analog (PWM)
I'm trying to test my `analog` signal before I send it to an actual `analog` device. I've written some code and considering the `analog` square I have expected to see a `digital` **ON** *or* **OFF** during a single `duty cycle` but I'm either seeing all **OFF** for `analog` values 0-127 and all **ON** for values 128-255.

My expectation is that I would see 51 **ON** and 49 **OFF** thus getting a value closer to 128 of 255.

**What am I missing? Is this even possible?**

```
int OUTPUT_PIN = 2; // digital 2 (PWM)
int INPUT_PIN = A0; // analog 0

void setup() {
  pinMode(OUTPUT_PIN, OUTPUT);
  pinMode(INPUT_PIN, INPUT);

  Serial.begin(9600);
}

void loop() {

  analogWrite(OUTPUT_PIN, 128);

  float j = 0;
  for(int i = 0; i < 100; ++i) { // get 100 reads per duty cycle
    float v;
    v = digitalRead( INPUT_PIN );
    if(v >= 1) Serial.println("ON");
    if(v <= 0) Serial.println("OFF");
    j += v;

    delay(12); // trying to match the duty cycle
  }
  j /= 100; // average out the 100 reads

  Serial.println(j);

}

```

# Answer
Seeing all on for 128+ and all off for 127- is indicative that you are using a pin that can't do PWM.

If you use a non-PWM pin with analogWrite it goes "Is this less than 128? Yes? Then I will turn it off. Otherwise I will turn it on.".

```
case NOT_ON_TIMER:
default:
    if (val < 128) {
        digitalWrite(pin, LOW);
    } else {
        digitalWrite(pin, HIGH);
    }

```

Since you don't mention what board you are using I can only assume that you have picked a pin that can't do PWM. Change to a pin that *can* do PWM and you should get a PWM signal.
> 2 votes

---
Tags: pwm, digital-analog-conversion
---


# Question
Title: Using an external interrupt alongside serial
I want to read data from an accelerometer sensor, which pushes its data to the Arduino via an external interrupt. I then want the Arduino to relay this data to a host computer via the serial connection.

Will the external interrupt interfere with the serial connection? If the Arduino's in the middle of transmitting via serial, and the accelerometer triggers the interrupt, won't that potentially break the serial connection?

# Answer
> 2 votes
Transmitting a single character via UART on the ATmega328P (and all other AVRs with a dedicated USART) cannot be interrupted since it is independently clocked. Loading the next character into the transmit buffer can be (since the `INTx` interrupts have priority over the `USART,xxx` interrupts), but this will not actually break communications, just slow it down.

---
Tags: arduino-uno, serial, interrupt
---


# Question
Title: NodeMCU Arduino set PWM Frequency to specific frequency
I am using NodeMCU and I program it using Arduino IDE, I need to change the PWM frequency of a port, in Arduino I used to change the frequency using timers registers like that:

```
TCCR1B = (TCCR1B & 0xF8) | 1 ;

```

How can I change the frequency of a digital pin using some function like that:

```
analogWriteFrequency(pin, 31250);

```

So that the code will looks like that:

```
#ifdef __AVR__
TCCR1B = (TCCR1B & 0xF8) | 1 ; //generates the MCKL signal
#else
analogWriteFrequency(pin, 31250);
#endif
analogWrite(pin, 128) ;

```

Thanks.

# Answer
> 1 votes
> PWM frequency is 1kHz by default. Call `analogWriteFreq(new_frequency)` to change the frequency.

source

---
Tags: arduino-ide, pwm, timers, nodemcu
---


title: Arduino Dim RGB LED

text:
# Question
Title: Arduino Dim RGB LED
I have an RGB led and I (just) would like to dim is brightness programmatically.

I searched Google thoroughly without any interesting code. Some of them present only "how to" fade from on to another color.

If I change PWM value from 0 to 255, I can easily change color, but, my need is to change the brightness value from potentiometer (through read from analog pin).

# Answer
To control the brightness of an LED with a POT read the pot position using the ADC, convert the range of values from 0 - 1024 to 0 - 255 then write that to the PWM controlling the LED.

This segment of code came from this discussion:

```
void loop()
{
  knobvalue = analogRead(potpin);
  knobvalue = map(knobvalue, 0, 1023, 0, 255);
  analogWrite(11, knobvalue);
}

```

This is just for 1 LED. If you have 3 LEDs connected to 3 Arduino PWM pins, you will have to write the same value to all 3 pins.

If this is 1 RGB LED and you are controlling each of the 3 LEDs with 3 Arduino PWM pins, this will (for most RGB LEDs) cause the RGB LED to always appear White as you are varying all colors by the same amount.

If you are trying to vary the brightness of an RGB LED that is set to an arbitrary color... this is more difficult:

Using 3 variables ranging from 0 to 255 pick your color. Before writing these to the 3 PWMs which control the RGB LED, multiply each by the value read from the ADC connected to the POT. Now divide each by the maximum possible ADC value. Take care you do not exceed the range of your variables! Write these new values to the 3 PWMs which control the RGB LEDs.
> 1 votes

---
Tags: pwm, rgb-led, potentiometer
---


# Question
Title: ACS712 Not working correctly with Arduino
So I have the basic setup ready with one relay that is controlling a 200W bulb. The Phase of this bulb is passed through a current sensor acs712. While running a simple analog read example sketch, I get output 511 from ADC, which is as expected. Then I subtracted this 511 from my measurement and observed the results while turning on/off the bulb.

```
int sensorValue;

void setup()
{
  Serial.begin(9600);  // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);       // read analog input pin 0
  Serial.println((511-sensorValue), DEC);  // prints the value read
  delay(100);                        // wait 100ms for next reading
}

```

Here is the output graph;

While the bulb is off, the current remains 0, but when I turn on the bulb, the voltage fluctuates over positive and negative side. Why is the sensor showing this behavior ?, I am not using any additional capacitor for noise reduction. Do I need to ? but I guess this is not noise. Is it ?

# Answer
You are seeing that because that is what the current is doing. It's called AC - Alternating Current. It's what the mains current is.

To work with AC you have to rapidly sample over a short period to get the maximum and minimum values. Subtract one from the other and that gives you the *peak-to-peak* current. You can then use that to calculate the *RMS* current which is what you are (most likely) interested in.
> 0 votes

---
Tags: arduino-uno, sensors, relay, current
---


title: serialEvents within a class

text:
# Question
Title: serialEvents within a class
My .ino looks roughly like this

```
#include "command.h"

Command command;
void setup() {
}

void loop() {
}

```

command.h

```
class Command
{
    public:
        Command();
};

```

command.cpp

```
#include <Arduino.h>
#include "command.h"

Command::Command() {
  Serial.begin(9600);
}

void serialEvent() {
  while (Serial.available() > 0) {
    char inChar = (char)Serial.read();
    Serial.print(inChar);
  }
}

```

The serial events don't seem to be happening. It works normally if I move the code out of the class.

# Answer
> 4 votes
When you put the `Serial.begin` in the constructor and declare the `Command` object at file scope, the `Serial.begin` will occur *before* `setup()`. Not recommended, perhaps not allowed.

If you do that, the compiler has to figure out that the `Serial` instance must be constructed before the `Command` instance is constructed. It can't always figure out the correct order.

In general, this is why you see many classes with a `begin` or `init` method. This allows the construction of file-scope instances to take place in any order, before `setup`. Then `setup` does the `Command.begin()`, which finally calls `Serial.begin`, long after `Serial` has been constructed.

Also, using `SerialEvent` is no better than doing the polling in `loop()`. If you're busy doing something else, `SerialEvent` does not get called. If you need to handle characters in the background, in the RX interrupt, you might want to take a look at a modified version for the `Serial` object(s) I posted, NeoHWSerial. You can attach a routine to be called whenever a character is received.

# Answer
> 0 votes
@slash-dev "...Also, using SerialEvent is no better than doing the polling in loop()." Are you sure about that? SerialEvent (and especially the ones on Teensy3) use hardware interrupts which can be handled in the midst of other operations; even delay() does not block interrupts (http://playground.arduino.cc/Code/AvoidDelay). It's hard to imagine multiple serial streams running at 100 kbaud or better (test reported in PJRC forum) and handling each character in the main loop even if that was all your program did. And why would you want to? There are good reasons interrupts exist.
**Update**: I'm not allowed to "comment" without 50 reputation. Thanks for the commit link... I can't imagine why HardwareSerial would not use interrupts... that is the default on all other platforms we've used for years.

---
Tags: serial, class
---


title: Serial Monitor listing rapidly

text:
# Question
Title: Serial Monitor listing rapidly
I am using an infrared sensor and a flex sensor to read values from the serial monitor in arduino, however after maybe ten seconds or so it seems the serial monitor breaks and the printed values start to print out rapidly. Does anyone have any suggestions on why this might occurring. Any information would be highly appreciated.

Thanks.

```
int previousMillis = 0;

long interval1 = 300;
long interval2 = 350;

void setup() {

    Serial.begin(9600);
}

void loop() {

    unsigned long currentMillis = millis();

    if ( currentMillis - previousMillis >= interval1 ) {
        previousMillis = currentMillis;

        Serial.println( "TIMER IS DONE!" );

        int val1 = analogRead(0);
        Serial.print("Sensor Value 1 is ");
        Serial.println(val1);
        delay(5);
    }
    if ( currentMillis - previousMillis >= interval2 ) {
        previousMillis = currentMillis;

        int val2 = analogRead(1);

        Serial.print("Sensor Value 2 is ");
        Serial.println(val2);
    }
    delay(10);
}

```

# Answer
I hate to start with "I hate delays", but I hate delays :)

Why have you included them? If you want your outputs to be slower, increase your intervals.

Use a state machine instead:

```
unsigned long previousMillis = 0;
unsigned long currentMillis = 0;

unsigned long interval1 = 300;
unsigned long interval2 = 350;

#define LEDPIN  13

int state = 0;
// 0 = waiting for sensor one interval
// 1 = another 50ms for sensor two

void setup() {
    currentMillis=millis();
    previousMillis=currentMillis;
    Serial.begin(9600);
    pinMode(LEDPIN, OUTPUT);
    digitalWrite(A0, HIGH); // internal pullups
    digitalWrite(A1, HIGH); // internal pullups

}

void loop() {
    currentMillis = millis();
    if ( state == 0 )
    {
        if ( currentMillis - previousMillis >= interval1)
        {
            int val1 = analogRead(0);
            Serial.print( currentMillis );
            Serial.print(" Sensor Value 1 is ");
            Serial.println(val1);
            digitalWrite(LEDPIN, HIGH);
            state = 1;
        }
    }
    else
    {
        if ( currentMillis - previousMillis >= interval2)
        {
            int val2 = analogRead(1);
            Serial.print( currentMillis );
            Serial.print(" Sensor Value 2 is ");
            Serial.println(val2);
            digitalWrite(LEDPIN, LOW);
            state = 0;
            previousMillis = currentMillis;
        }
    }
}

```

This way, test 2 will only be conducted 50ms after test 1 and then previous millis is reset

edit: I fixed the interval test regarding overflow (which you had correctly in the first place)

edit2: (I'm having too much fun with this) assuming you want each test conducted at specifically the interval requested (ie sensor 1 every 300ms and sensor 2 every 350ms), I have come up with v2 (and removed the state machine, since it's just not needed)

```
unsigned long previous1 = 0;
unsigned long previous2 = 0;
unsigned long currentMillis = 0;

unsigned long interval1 = 300;
unsigned long interval2 = 350;

const int LEDPIN = 13;

void setup() {
    currentMillis=millis();
    previous1=currentMillis;
    previous2=currentMillis;
    Serial.begin(9600);
    pinMode(LEDPIN, OUTPUT);
    digitalWrite(A0, HIGH);
    digitalWrite(A1, HIGH);
}

void loop() {

    currentMillis = millis();
    if ( currentMillis - previous1 >= interval1)
    {
        previous1 = currentMillis;

        int val1 = analogRead(0);
        Serial.print(currentMillis);
        Serial.print(" Sensor Value 1 is ");
        Serial.println(val1);
        digitalWrite(LEDPIN, HIGH);
    }
    if ( currentMillis - previous2 >= interval2)
    {
        int val2 = analogRead(1);

        Serial.print(currentMillis);
        Serial.print(" Sensor Value 2 is ");
        Serial.println(val2);
        previous2 = currentMillis;
        digitalWrite(LEDPIN, LOW);
    }
}

```

edit: including some sample output to indicate a working state:

```
188609 Sensor Value 1 is 15
188659 Sensor Value 2 is 14
188959 Sensor Value 1 is 14
189009 Sensor Value 2 is 15
189309 Sensor Value 1 is 15
189359 Sensor Value 2 is 14
189659 Sensor Value 1 is 14
189709 Sensor Value 2 is 1017
190009 Sensor Value 1 is 15
190059 Sensor Value 2 is 1002
190359 Sensor Value 1 is 14
190409 Sensor Value 2 is 1013
190709 Sensor Value 1 is 14
190759 Sensor Value 2 is 1019
191059 Sensor Value 1 is 15
191109 Sensor Value 2 is 1004
191409 Sensor Value 1 is 14
191459 Sensor Value 2 is 1019
191759 Sensor Value 1 is 15
191809 Sensor Value 2 is 15
192109 Sensor Value 1 is 14
192159 Sensor Value 2 is 15
192459 Sensor Value 1 is 14
192509 Sensor Value 2 is 14
192809 Sensor Value 1 is 15
192859 Sensor Value 2 is 15
193159 Sensor Value 1 is 14
193209 Sensor Value 2 is 16
193509 Sensor Value 1 is 14
193559 Sensor Value 2 is 15
193859 Sensor Value 1 is 1005
193909 Sensor Value 2 is 1021
194209 Sensor Value 1 is 1021
194259 Sensor Value 2 is 1003
194560 Sensor Value 1 is 1004
194609 Sensor Value 2 is 1020
194909 Sensor Value 1 is 1020
194959 Sensor Value 2 is 1004
195259 Sensor Value 1 is 15
195309 Sensor Value 2 is 1001
195609 Sensor Value 1 is 14
195659 Sensor Value 2 is 1022
195959 Sensor Value 1 is 15
196009 Sensor Value 2 is 998
196310 Sensor Value 1 is 15
196359 Sensor Value 2 is 1019
196659 Sensor Value 1 is 15
196709 Sensor Value 2 is 1002
197009 Sensor Value 1 is 14
197059 Sensor Value 2 is 15
197359 Sensor Value 1 is 14
197409 Sensor Value 2 is 15
197709 Sensor Value 1 is 15
197760 Sensor Value 2 is 13
198060 Sensor Value 1 is 14
198110 Sensor Value 2 is 15
198410 Sensor Value 1 is 15
198460 Sensor Value 2 is 14

```
> 1 votes

# Answer
You are doing math with 2 different types. One is long and the other is an int. So, eventually the long will always be lager than the int and the test will always be true. (A 32 bit long can count up to over 2 billion. A 16 bit int can only count up to about 32 thousand.)

Also, the method millis() is of type "unsigned long". So change all your variables to match this type.

Also note that when the millis() timer overflows and start over your program may perform unexpectedly. Since this rarely happens it may not concern you.
> 1 votes

---
Tags: arduino-uno, serial, sensors
---