# Question
Title: Can I use micros() to analyze TX23 anemometer signal?
I'm very new to Arduino, and I'm trying to read data from a LaCrosse TX23 V02(X) anemometer. It's supposed to behave like this https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/, but it's not...

I don't have an oscilloscope, so I made this code, using micros() to try to trace the output from the TX23:

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

int collectData(void){
   if (bitLength < 0){
      bitLength = 1200;// length of bit is equal to approx 1230 micro seconds;
   }
  // init sequence
  pinMode(dataPin, OUTPUT);
  Serial.print("Send LOW\n");
  digitalWrite(dataPin, LOW );
  Serial.print("Send HIGH\n");
  digitalWrite(dataPin, HIGH);
  delay(100);
  Serial.print("Send LOW\n");
  digitalWrite(dataPin, LOW );
  delay(500);

  Serial.print("Begin input mode\n");
  pinMode(dataPin, INPUT);

  int state = 0;
  int oldstate = 0;
  unsigned long oldmicros = micros();
  for (int i = 1; i<5250 ; i++) {
    state = (digitalRead(dataPin) == LOW)? 0:1;
    if (i%10 != 0) {
      Serial.print("-");
    } else {
      Serial.print("+");
    }

    delayMicroseconds(10);
    if (state != oldstate) {
      oldstate = state;
      i = 1;
      Serial.print(oldstate);
      Serial.print(" @");
      Serial.print(micros() - oldmicros);
      oldmicros = micros();
      Serial.print("\n");
    }
  }
  Serial.print(state);
  Serial.println(micros()-oldmicros);
}

```

Does it have a chance to provide a quite accurate monitoring of the TX23 output? (eg is using micros() or delayMicroseconds(10) accurate ?)

# Answer
You should really make use of `pulseIn()` to work out the bit rate of the signal. The first HIGH pulse in the header is there for timing so you know how often to poll the input.

Step one, after sending your outgoing initiation pulse, should be to wait for that first pulse (you might need a slight delay first before it starts transmitting - wait for the line to be low first):

```
while (digitalRead(dataPin) == HIGH); // Wait for TX start
uint32_t pulseWidth = pulseIn(dataPin, HIGH); // Get first pulse

```

That gives you the width of the first pulse in microseconds.

Now you can read 45 times at that period. If you first delay by half that amount before your first sample you will be roughly in the middle of the bit so you can cope with a slight amount of drift.

```
// Wait for the middle of the first bit
delayMicroseconds(pulseWidth / 2);

uint32_t highBlock = 0;
uint32_t lowBlock = 0;
for (int i = 0; i < 45; i++) {
    // Shift the high 32-bits left one bit
    highBlock <<= 1;
    // Place in the highest bit of the low block as the lowest
    // bit of the high block
    highBlock |= (lowBlock & 0x80000000UL ? 1 : 0);
    // Shift the low 32-bits left one bit
    lowBlock <<= 1;
    // Add in the value of the bit from the data pin
    lowBlock |= digitalRead(dataPin);
    // Wait for the next bit
    delayMicroseconds(pulseWidth);
}

```

You should now have two 32-bit words which, when put together, form the entire datagram. You can now use bitwise operators to pull out the parts you are interested in.

A better, though more complex, method of doing it would be to employ a timer with an overflow period equal to the pulse width. That will afford you much more accurate timing than a simple loop with delays.
> 1 votes

# Answer
Majenko showed a method for digitally recording the waveform, after measuring `pulseWidth` at the outset, and mentioned use of a timer for delays. I'll address the part of your question about using `micros()` while tracing TX23 output: “Does it have a chance to provide a quite accurate monitoring of the TX23 output?”

Some of the serial output that your method produces as it goes along will affect evenness of timing. For example, the `Serial.print()` of + after every tenth reading introduces a small timing irregularity (the two branches of the `if` may differ a few cycles in execution time).

More seriously, your double-read of `micros()` (after you print `oldstate`, you print `micros() - oldmicros` and then read `micros()` again) introduces a few cycles of timing error. It probably amounts to a few microseconds total over the course of recording the pulse train. Instead of reading `micros()` twice, say something like `newmicros = micros()` directly after detecting a state change, before doing any serial printing, then use `newmicros` in place of other `micros()` calls. Having serial prints before `oldmicros = micros();` causes an offset error, which will be microseconds or milliseconds depending on the data rate you set in `setup()`. It mostly affects the reported length only of the first pulse.

What I would do for debug monitoring of the pulse train is along the following lines:

```
enum { timelen=44, maxpause=50000 };
unsigned long int times[timelen];

int collectData() {
  byte ntimes = 0, state=LOW;
  unsigned long int prevtime;
  pinMode(dataPin, OUTPUT);
  digitalWrite(dataPin, LOW ); // Pull DTR low to trigger conversion
  delay(500);
  pinMode(dataPin, INPUT_PULLUP); // Release DTR and set pullup
  delay(1);           // Let TX23U pull DTR low
  prevtime = micros();
  while (micros() - prevtime < maxpause && ntimes < timelen) {
    if (digitalRead(dataPin) != state) {
      times[ntimes++] = prevtime = micros();
      state = 1-state;
    }
  }
  return ntimes;
}

```

This code is intended to record times at which state changes occur. After `loop()` calls `collectData()`, it can call a `reportData()` routine that will print out pulse lengths by subtracting adjacent entries of `times[]`. Even-indexed array entries are times of rising edges in the pulse train; odd-indexed entries are times of falling edges. Because the `if (digitalRead(dataPin) != state) {...}` statement isn't executed atomically, the data pin can change after being tested but before being recorded a couple of lines later. Using `state = 1-state;` instead of `state = digitalRead(dataPin);` guarantees that even indexes are for rising edges, but does not guarantee that adjacent entries correspond to the same pulse edge. That is, a noisy signal can produce misleading results.
> 1 votes

# Answer
I'm going to present a third way of working on this. :)

First, since I don't have a TX23 I wrote a TX23-simulator:

```
const byte TESTPIN = 2;

const byte test [6] = {
    0b00000011,
    0b01111011,
    0b01010100,
    0b00010100,
    0b01001010,
    0b10111111 };

void setup ()
  {
  pinMode (TESTPIN, INPUT);
  delay (100);
  }  // end of setup

void loop ()
  {
  // wait for host to pull pin low
  while (digitalRead (TESTPIN) == HIGH)
    { }
  // wait for host to release it
  while (digitalRead (TESTPIN) == LOW)
    { }
  digitalWrite (TESTPIN, HIGH);
  pinMode (TESTPIN, OUTPUT);
  for (byte i = 0; i < 6; i++)
    for (byte j = 0; j < 8; j++)
      {
      delayMicroseconds (1100);
      digitalWrite (TESTPIN, test [i] & bit (7 - j));
      }
  pinMode (TESTPIN, INPUT);
  }  // end of loop

```

Based on your linked page about the TX23 it outputs a series of low/high pulses corresponding to the example on that page, like this:

Note that you need a 10 k pull-up resistor for this to work properly.

---

Now the reading code uses interrupts to detect state changes:

```
const byte READ_PIN = 2;
const byte NUMBER_OF_CHANGES = 48;

volatile unsigned long bitTime [NUMBER_OF_CHANGES];
volatile byte state [NUMBER_OF_CHANGES];
volatile byte count;

void stateChange ()
  {
  unsigned long now = micros ();
  if (count >= NUMBER_OF_CHANGES)
    return;  // array full
  state [count] = digitalRead (READ_PIN);
  bitTime [count++] = now;
  } // end of stateChange

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  }  // end of setup

void takeReading ()
  {
  count = 0;
  digitalWrite (READ_PIN, LOW);  // start reading
  pinMode (READ_PIN, OUTPUT);
  delay (20);  // pulse width
  pinMode (READ_PIN, INPUT);     // release line
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  attachInterrupt (0, stateChange, CHANGE);
  delay (55);  // let readings fill up array
  detachInterrupt (0);
  }  // end of takeReading

void loop ()
  {
  takeReading ();
  if (count == 0)
    return;  // nothing!

  delay (500);
  for (byte i = 0; i < count; i++)
    {
    Serial.print ("count: ");
    Serial.print ((int) i);
    Serial.print (" = ");
    Serial.print (bitTime [i]);
    Serial.print (", state = ");
    Serial.print (state [i]);
    if (i > 0)
      {
      Serial.print (", width = ");
      unsigned long width = bitTime [i] - bitTime [i - 1];
      Serial.print (width);
      Serial.print (" (");
      int bits = width / 1000;
      for (byte k = 0; k < bits; k++)
       Serial.print (state [i - 1]);
      Serial.print (")");
      }
    Serial.println ();
    }
    Serial.println ();
  }  // end of loop

```

---

Results were:

```
count: 0 = 10952804, state = 1
count: 1 = 10953928, state = 0, width = 1124 (1)
count: 2 = 10960616, state = 1, width = 6688 (000000)
count: 3 = 10962844, state = 0, width = 2228 (11)
count: 4 = 10963960, state = 1, width = 1116 (0)
count: 5 = 10968412, state = 0, width = 4452 (1111)
count: 6 = 10969524, state = 1, width = 1112 (0)
count: 7 = 10971752, state = 0, width = 2228 (11)
count: 8 = 10972876, state = 1, width = 1124 (0)
count: 9 = 10973988, state = 0, width = 1112 (1)
count: 10 = 10975104, state = 1, width = 1116 (0)
count: 11 = 10976216, state = 0, width = 1112 (1)
count: 12 = 10977328, state = 1, width = 1112 (0)
count: 13 = 10978440, state = 0, width = 1112 (1)
count: 14 = 10984012, state = 1, width = 5572 (00000)
count: 15 = 10985124, state = 0, width = 1112 (1)
count: 16 = 10986244, state = 1, width = 1120 (0)
count: 17 = 10987356, state = 0, width = 1112 (1)
count: 18 = 10990700, state = 1, width = 3344 (000)
count: 19 = 10991812, state = 0, width = 1112 (1)
count: 20 = 10994040, state = 1, width = 2228 (00)
count: 21 = 10995156, state = 0, width = 1116 (1)
count: 22 = 10996268, state = 1, width = 1112 (0)
count: 23 = 10997380, state = 0, width = 1112 (1)
count: 24 = 10998500, state = 1, width = 1120 (0)
count: 25 = 10999616, state = 0, width = 1116 (1)
count: 26 = 11000728, state = 1, width = 1112 (0)

```

This seems to agree with the test data.
> 1 votes

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


title: Light sensor always getting max value

text:
# Question
Title: Light sensor always getting max value
I have build a simple voltage divider with a light resistor and a 5.6k resistor. I am reading the input on A0 on my arduino board but it is almost always at 1023, independent of light. If I cover it it might go down to 1020 but not more than that.

Do I have to use a greater resistor than 5.6k to achieve more difference in the sensor?

The light sensor is similar to this: http://www.ebay.com/itm/20x-5549CDS-Photo-Light-Dependent-Sensitive-Resistor-Photoresistor-LDR-Photocell-/281425650814?pt=LH\_DefaultDomain\_0&hash=item418646a47e

I think that the resistance is pending between 1k-10k.

The circuit is like this image:

Where Vin is 5V from the arduino. R1 is the light sensor, R2 is 5.6k and Vout is connected to A0.

# Answer
> 2 votes
What have you selected as the analog reference? And if 'external', what is connected to the Vref pin?

For the LDR resistances of 10K and 1K, you Vout should be ~ 1.8v at 10K, and ~ 4.2v at 1K, and giving A/D readings of somewhere around 370 counts and 860 counts, respectively, *with a 5v analog reference*.

If your analog reference selected to the 1.1v internal reference, either LDR resistance should give you the max reading, but an LDR = 20K could give just over a volt and pretty close to the reading you're getting.

# Answer
> 2 votes
Judging by a datasheet (that I found on the web) that has a resistance of:

* 100 k to 200 k in the light
* 1 M in the dark

Given that Vout = Vin * R2 / (R1 + R2) we can work out:

Light:

```
Vout = 5 * 200000 / (200000 + 5600) = 4.86 V

```

Dark:

```
Vout = 5 * 1000000 / (1000000 + 5600) = 4.97 V

```

> Do I have to use a greater resistor than 5.6k to achieve more difference in the sensor?

Yes, I would measure the resistance in the light, and choose a similar resistor for the other side of the voltage divider. So if you measure 100 k on the sensor, another 100 k will at least divide the voltage in two nicely.

---
Tags: arduino-mini
---


# Question
Title: Wirelessly communicate between two Arduinos without router
I want to "connect" two Arduinos, without using wires. The range is ~0.2 miles (300 meters). Using Google, I saw too many options.

The idea is to build something like a beacon, so the bandwidth can be small. I want to send 32 or 64 bits/second of data (32 bits for the application + 32 bits for checksum if the module does not guarantee consistency of data). The communication between Arduinos is bi-directional, and I'm looking for something cheaper than 50 US dollars per module.

Can I use a serial WiFi module for this, without using a router? Do you recommend a 2.4GHz module? Or a RF module?

# Answer
I can highly recommend these cheap little 433Mhz radios. You can get them on amazon, ebay, etc. and they work pretty well for me. Your distances are a bit longer than my situation but I have to go through several walls.
> 3 votes

# Answer
It's a bit unorthodox solution, but have you considered toy walkie-talkies? They cover the distance you reported, even if some obstacles are in the path and they are relatively cheap, if you go for some sales. It requires a bit of hacking to connect the arduino to the mic/speaker and the push button, but it shouldn't be too difficult.
> 0 votes

---
Tags: wifi, rf, remote-control
---


# Question
Title: Using C# Program to Interpret Keystrokes
I am in the process of developing an Arduino application that can read keystrokes from a PS/2 keyboard. I was wondering if it would be possible to upload a C# program onto the Arduino to interpret the keystrokes from the keyboard and write an Arduino program to perform operations based on the keystrokes.

# Answer
> 1 votes
The answer is actually, surprisingly, yes! C# requires `.NET CLR` for execution, I had assumed that `.NET` exists only in microsoft desktop land, but it has in fact been ported to microcontrollers and released open source as `.NET micro`, it can even run baremetal with no OS.

However this is not possible on an 8 bit regular arduino, it requires one of the larger 32 bit models. There is a prebuilt clone that has the `.NET micro CLR` framework ported to it on an STM32F4 cpu called the netduino

Unfortunately the footprint for .Net Micro is too large to run on a regular 8bit arduino and probably hasn't been built for 8bit systems. It is possible with the arduino Due (in theory) and on other micrcontroller platforms that support `.NET micro` to run C# code outside of the windows platform.

# Answer
> 0 votes
I hope this answer doesn't get voted down just because it addresses the generic need (do something upon input from a PS/2 keyboard), rather than the (too) specific question that was asked (use c# on Arduino), but here it comes ...

If you use a PS/2 to USB adapter for the keyboard, you can select a much easier solution, based, for example, on raspberry PI (or anything that runs linux and has a USB master port) and use any simple scripting language - even shell. The overall cost would not be much higher and the ease of implementation would be definitely more likely to succeed. And in a short time.

---
Tags: c++, keyboard
---


# Question
Title: Arduino Serial.write sending more than 64 bytes
I am using an Arduino Due to collect a large amount of data from an encoder (about 1kb). Afterwards I need to send the collected data to a C# application I wrote over the serial port. I serialized my tx data into a byte buffer and simply used this code to transmit:

```
void sendEncoderData()
{
  byte buffer[1024];

  /*** some code that populates buffer ***/

  int bytesToSend = 1024;
  Serial.write(buffer, bytesToSend);
}

```

When I run the code, nothing seems to get received by the C# application. In fact, I never see the Tx LED light up. However, if I change `bytesToSend` to a value smaller than 64 bytes everything works. Is this a limitation of `Serial.write()` or is it something else? What are ways I can work around this limitation?

More information： `sendEncoderData()` is called by an interrupt service routine. However prior to the call, I made sure to 'detachInterrupt()\` on all pins including the pin associated with said ISR.

# Answer
Here's the problem:

> sendEncoderData() is called by an interrupt service routine.

There is an internal 64 byte serial transmit buffer that is filled by Serial.write(). That buffer is empted by sending the data a byte at a time using an interrupt.

If you are in an interrupt (at a higher priority than the serial interrupt) then the interrupt that sends the data can never happen, so the buffer just fills up and stops when it gets to 64 bytes. It will hang until there is room for more bytes in the buffer, and that will never happen because you're not allowing the data to be sent.

The answer (as I and others have said many times in the past): **Never use Serial in an interrupt.**
> 2 votes

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


# Question
Title: What makes a board "Arduino Compatible"?
There are all sorts of Arduino and Arduino-compatible boards out there. They come in all form factors and they come with all sorts of different I/O. They even come with memory specs and different kinds of microcontrollers, from the ATmega328P to Intel-based.

So what is it that imbues a board to become "Arduino Compatible" ? Must it be pin-compatible? Must it be possible to compile Arduino source code for the board? Or must the board be binary-compatible? Must it emulate some specific processor instruction set?

Very curious. Please reference specifications if possible. Thank you.

# Answer
> 1 votes
The problem here is that "compatible" can mean so many things in different contexts and to different people. For instance, it may mean any of the following:

1. Can be used with the Arduino IDE without any need for additional board installation of other modifications
2. Can be used with the Arduino IDE after modification (boards installed)
3. Uses the same (or very similar) API to the Arduino system
4. Has the same footprint as an existing official Arduino board
5. Is a device which will work with an Arduino board and has software available to operate it

All very different meanings.

Point 1 could be a board that is based on the design of an existing Arduino board (say the Uno) but built into a new form factor, maybe with additional hardware and peripherals added. It is still treated as if it was the board the design was based on though.

Point 2 would be a board that is similar, though not the same, as an existing board. A different board definition may be required to map the IO pins properly, for instance. It could use a slightly different chip in the same supported family. You still use it as an Arduino, but it's not the same as an existing Arduino board.

Point 3 may mean it's based on a completely different chip. The programming environment may be almost the same, but it's hard to get 100% API compatibility. Arduino sketches and libraries *may* work out of the box, or may not.

Point 4 could be a board that, internally, is completely different to the Arduino, uses a different programming language, IDE, etc, yet the layout of the board is the same as, say, an Arduino Uno. A good example is the Mecanique Firewing - an Uno footprint, but a PIC32 chip instead of an Atmel, and Basic instead of C++. Most Arduino shields would just plug in and work though, software permitting.

Point 5 is from the completely opposite direction. This is a device which "is compatible with" in that "it will work with" and Arduino. That could be on an electrical level (it's a 5V device and will connect to the Arduino) or that it has full software support (*"Download our Arduino library..."*). It has nothing to do with how the device works or what it is though.

I prefer to use specific terms, respectively:

1. Based on the Ardino UNO
2. Programmable with the Arduino IDE
3. Compatible with the Arduino API
4. Footprint compatible with the Arduino UNO
5. Suitable for use with Arduino boards

That way it states exactly in what way this device relates to the official Arduino boards.

# Answer
> 0 votes
I think the practical answer is: it is not defined.

In practice:

For peripherals, it seems to mean that it can interact with an Arduino compatible board.

For boards, as far as I can tell, it has to be: instruction-set compatible, OR pin (layout) compatible with another board which was previously defined as Arduino compatible.

# Answer
> 0 votes
I think you could say it is **Arduino-compatible** if it contains a processor found on an Arduino board. For example:

* The Atmega328P (found on the Uno, Duemilanove, Pro Mini, amongst others)
* The Atmega32U4 (found on the Leonardo, Micro, amongst others)
* The Atmega2560 (found on the Mega2560)
* Other processors used by Arduinos such as the Atmel SAM3X8E ARM Cortex-M3 CPU used on the Arduino Due.

With a processor used on an Arduino, you will find that you can almost certainly compile code using the Arduino IDE, and the Arduino libraries, that will work on such chips.

---

You could say it is **Arduino-Uno-compatible** if the board physically was compatible with the Arduino Uno (ditto for other boards). In other words, if it was possible to plug a shield, designed for the Uno, onto such a board. That could be called "plug compatible" I suppose.

---

As for other boards, like sensors, relay boards, etc., I have seen a lot of those on eBay advertised as "Arduino compatible", but of course they would also be compatible with other micro-controllers as well. I'm waiting for the day someone advertises "Arduino compatible" resistors.

---
Tags: clones
---


# Question
Title: Low Power library messing up serial text
I noticed something unusual using the Low Power library today. When printing text in the loop and using `LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);` to sleep for one second, all the text in the loop gets messed up in the Serial Monitor as if you chose the wrong baud rate.

Example code:

```
#include "LowPower.h"

void setup() {
  Serial.begin(9600);
  Serial.println(F("HELLO"));
  Serial.println(F("HELLO"));
}

void loop() {
  Serial.println(F("HELLO"));
  LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);
}

```

This code just prints

```
����11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=

```

even when using different baud rates. (I used the same baud rate on both the arduino and the monitor). Replacing the low power command with `delay(1000);` works fine

# Answer
The problem is most likely that the system is going to sleep *while* it's still sending the serial data.

Forcing all the serial data to be sent before you go to sleep should fix the problem (serial data is sent in the background using an interrupt so as to keep sketch slowdown to a minimum):

```
Serial.flush();
LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);

```
> 12 votes

---
Tags: serial, power, baud-rate
---


# Question
Title: Increasing the numbers of I/O pins on Arduino Uno
I want to make a game of Tic-tac-toe using an Arduino, LEDs and bouncy buttons. Hence I need nine inputs and nine outputs. But you see that an Arduino only has 13 I/O pins. So is there a way I can use the analog pins or a way to reduce the number of I/O pins using an ingenious way?

# Answer
> 4 votes
Yes, just use the analog pins. The analog pins are both analog inputs and digital I/O pins. The functions happen to be shared on the pins, in the same way that the interrupt pins are shared with digital I/O, the TX and RX pins are shared with digital I/O and the SPI pins are shared with digital I/O.

Every I/O pin (analog or digital, etc.) can be used as digital I/O.

You can also reduce your required number of I/O pins by using a technique known as *multiplexing*.

For instance, to read nine buttons you could have them arranged (as in Tic-tac-toe) in three rows of three buttons. You then have three I/O pins for the columns and three I/O pins for the rows - that's just six I/O pins for nine buttons.

The technique is widely used for keypads, but they are just buttons, so the same technique can be applied to any buttons.

The same can go for LEDs. There are various specialist LED multiplexing techniques that allow for many LEDs to be driven from just a handful of I/O pins.

# Answer
> 2 votes
If multiplexing is too complicated for you, you can wire all buttons to one analog pin using resistors. This way you only need 9 pins for LEDs and 1 analog pin for buttons.

---
Tags: arduino-uno
---


# Question
Title: Controlling a sliding tray - beginners project
I have a small light metal platform about 30 cm square mounted on horizontal rails. It is well lubricated and slides easily from side to side. I would like to build a device to connect to the underside of the platform that will allow me to programatically move the platform left or right by a defined distance at the touch of a button.

While I've never used an Arduino, I've been aware of its existence for a while and felt this might be a good project to begin experimenting with it. For context, I'm a computer programmer by trade, but have limited exposure to electronics in general.

Where would be a good place to start? Are there books that are considered the "bible" of Arduino development? Are there existing projects that basically do what I'm hoping to achieve? Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino? Any input would be greatly appreciated.

# Answer
> 1 votes
> Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino?

Not at all. For example see Reprap \- a 3D printer using an Atmega1280 as the controller. As it says here:

> Arduino is an open source project that has created an easy and powerful microcontroller board based on the Atmel ATmega168. It is the brain of the RepRap electronics.

If you can make a 3D printer with an Arduino, then you can make your sliding platform gadget, which sounds simpler if anything.

---

> Are there existing projects that basically do what I'm hoping to achieve?

Reprap, for one.

---

> Are there books that are considered the "bible" of Arduino development?

This is a broad question, and your original question already has a couple of "flags" that it is *too* broad. I suggest you narrow it down a bit.

There are a number of books about learning Arduino. My advice is to start doing some simple projects (simpler than the platform initially) to get the hang of compiling, uploading, and generally working with microcontrollers.

---

Also try Google and YouTube. There are a **lot** of Arduino projects out there.

---
Tags: motor
---


# Question
Title: Venus GPS + Arduino. Kill 3.3V TX during sketch upload
I am playing around with the Sparkfun Venus GPS. I followed this tutorial to get started. In here the author states that you should

> Upload the following sketch to your Arduino BEFORE making any connections. 5V from an IO pin left high on the Arduino may well kill the 3.3V output from the Tx pin on the GPS module.

However, I am using the Sparkfun bi-directional logic level converter in between the Arduino and the Venus GPS (because I'm using the 5V Arduino GSM shield stacked on top of the Arduino). In that case, would the above statement still apply?

# Answer
> 0 votes
If you have a logic-converter between the Arduino and the GPS then you won't have any problems.

The warning was about having the output from the Tx pin on the GPS possibly being damaged by +5 V from the Arduino, if a previously loaded sketch made it an output and HIGH.

However you could just as easily upload a "do nothing" sketch like this:

```
int main () { }

```

That is sound practice anyway, if you are connecting up new hardware and are not sure what the currently-loaded sketch does.

---
Tags: gsm, gps
---


# Question
Title: USART RX Interrupt on an ARDUINO PRO MINI containing factory bootloader
Is it possible to use **RXC Interrupt vector** with the factory programmed **bootloader** still **existing** in the **arduino pro mini**?

I've written a simple echo program using RXC interrupt vector, the program prints "*READY*" on startup but as soon the chip receives the first character it goes into a **repetitive reset loop** i.e. I keep receiving `READY READY READY..` so on.

I've checked the program multiple times and I think its the bootloader, I think the bootloader has shifted the interrupt table to the boot section before executing the application. Is that so?

Thanks in advance.

# Answer
Once the bootloader transfers control to the main code (sketch) it may as well not exist any more. It does **not affect** the way the sketch runs.

---

> I've written a simple echo program using RXC interrupt vector ...

Please post this code. For you to print "READY" you are (presumably) using the Serial port, in which case the HardwareSerial interrupt vectors are being used. I don't know how you managed to take over those vectors. Seeing your code might answer that.
> 1 votes

---
Tags: bootloader, interrupt, arduino-pro-mini
---


# Question
Title: Send one bit out per clock pulse received using direct port manipulation?
I want to send one bit of a byte out per 'rising edge' received to an Arduino digital input. I am addressing the outputs using direct port manipulation (to achieve maximum speed), and I would like to do the same for input.

So I'm calling a function called bitBang in my main loop, sending the ready line high before moving into the function:

```
//Send control
PORTB |= _BV(PORTB2);
bitBang(controlByte);
PORTB &= ~_BV(PORTB2);

```

What I would like to do upon entering the function is listen for a rising edge to appear on the digital input port using the direct port syntax and iterate through the byte setting the data line high or low depending on the bit's value.

**How can I achieve this in the most efficient way possible?**

# Answer
Example bit-banged SPI using port manipulation:

---

**bitBangedSPIfast.h** :

```
#include <Arduino.h>

class bitBangedSPIfast
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const mosiPort_;
  volatile byte * const misoPin_;
  volatile byte * const sckPort_;

  // bit masks for above
  const byte mosiBit_;
  const byte misoBit_;
  const byte sckBit_;

  // addresses of data direction register ports
  volatile byte * const mosiDDR_;
  volatile byte * const misoDDR_;
  volatile byte * const sckDDR_;

  // bit masks for above
  const byte mosiDDRBit_;
  const byte misoDDRBit_;
  const byte sckDDRBit_;

  // delay for clock being high
  unsigned long delayUs_;

  public:
    // constructor
    bitBangedSPIfast (
          // output ports
          volatile byte & mosiPort,
          const    byte mosiBit,
          volatile byte & misoPin,
          const    byte misoBit,
          volatile byte & sckPort,
          const    byte sckBit,

          // data direction register ports
          volatile byte & mosiDDR,
          const    byte mosiDDRBit,
          volatile byte & misoDDR,
          const    byte misoDDRBit,
          volatile byte & sckDDR,
          const    byte sckDDRBit,

          const unsigned long delayUs = 1)
       :
         mosiPort_ (&mosiPort),
         mosiBit_  (1 << mosiBit),
         misoPin_  (&misoPin),
         misoBit_  (1 << misoBit),
         sckPort_  (&sckPort),
         sckBit_   (1 << sckBit),

         mosiDDR_     (&mosiDDR),
         mosiDDRBit_  (1 << mosiDDRBit),
         misoDDR_     (&misoDDR),
         misoDDRBit_  (1 << misoDDRBit),
         sckDDR_      (&sckDDR),
         sckDDRBit_   (1 << sckDDRBit),

        delayUs_ (delayUs) { }

    void begin ();
    byte transfer (byte input);

  };  // end of bitBangedSPIfast

```

---

**bitBangedSPIfast.cpp** :

```
#include <bitBangedSPIfast.h>

void bitBangedSPIfast::begin ()
  {
  if (mosiPort_)
    *mosiDDR_ |= mosiDDRBit_;    // output
  if (misoPin_)
    *misoDDR_ &= ~misoDDRBit_;   // input
  *sckDDR_ |= sckDDRBit_;        // output
  }   // end of bitBangedSPIfast::begin

// Bit Banged SPI transfer
byte bitBangedSPIfast::transfer (byte c)
{
  // loop for each bit
  for (byte bit = 0; bit < 8; bit++)
    {
    // set up MOSI on falling edge of previous SCK (sampled on rising edge)
    if (mosiPort_)
      {
      if (c & 0x80)
        *mosiPort_ |= mosiBit_;
      else
        *mosiPort_ &= ~mosiBit_;
      }

    // finished with MS bit, get read to receive next bit
    c <<= 1;

    // read MISO
    if (misoPin_)
      c |= (*misoPin_ & misoBit_) != 0;

    // clock high
    *sckPort_ |= sckBit_;

    // delay between rise and fall of clock
    delayMicroseconds (delayUs_);

    // clock low
    *sckPort_ &= ~sckBit_;

    // delay between rise and fall of clock
    delayMicroseconds (delayUs_);
    }  // end of for loop, for each bit

  return c;
  }  // end of bitBangedSPIfast::transfer

```

---

**Example usage**:

```
#include <bitBangedSPIfast.h>

bitBangedSPIfast bbSPI (PORTD,  5, PIND,  6, PORTD, 7,    // MOSI port (D5), MISO pin (D6), SCK port (D7)
                        DDRD,   5, DDRD,  6, DDRD,  7);   // MOSI ddr  (D5), MISO ddr (D6), SCK ddr  (D7)
const byte mySS =  8;  // slave select

void setup (void)
  {
  bbSPI.begin ();
  pinMode (mySS, OUTPUT);
  }  // end of setup

void loop (void)
  {
  char c;

  // enable Slave Select
  digitalWrite(mySS, LOW);

  // send test string
  for (const char * p = "Hello, world!" ; c = *p; p++)
    bbSPI.transfer (c);

  // disable Slave Select
  digitalWrite(mySS, HIGH);

  delay (100);
  }  // end of loop

```

---

### Reference

SPI - Serial Peripheral Interface - for Arduino
> 1 votes

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


# Question
Title: "variable must be const" fix for Arduino progrem
I am trying to upload to my nano the code attached. It is giving me an error saying variable must be const about something I am trying to put in progrem. I learned that installing a older version of the compiler worked. However I was wondering is there a way to just edit the code to make it work. I tried putting const before it but it didn't work. It is on line 78 and 79 of the first file.

const extern PGM\_P \*NApowerCodes\[\] PROGMEM;

const extern PGM\_P \*EUpowerCodes\[\] PROGMEM;

# Answer
Using the source from this link I got it to compile following these steps.

---

* Before opening the sketch in the Arduino:
    + Rename TVB.pde to TVB.ino
    + Rename WORLDcodes.cpp to WORLDcodes.h

---

* Open the sketch (TVB.ino) in the Arduino IDE

---

* Edit main.h and change:

```
// The structure of compressed code entries
struct IrCode {
  uint8_t timer_val;
  uint8_t numpairs;
  uint8_t bitcompression;
  uint16_t const *times;
  uint8_t const*codes;
};

```

to:

```
// The structure of compressed code entries
struct IrCode {
  uint8_t timer_val;
  uint8_t numpairs;
  uint8_t bitcompression;
  uint16_t const *times;
  uint8_t const*codes PROGMEM;
};

```

That is, add `PROGMEM` to the `codes` line.

---

* Edit TVB.ino and change:

```
extern PGM_P *NApowerCodes[] PROGMEM;
extern PGM_P *EUpowerCodes[] PROGMEM;
extern uint8_t num_NAcodes, num_EUcodes;

```

to:

```
#include "WORLDcodes.h"

```

This avoids some linker problems in the original code.

---

* Edit WORLDcodes.h and delete the line:

```
 #include "main.h"

```

---

* Continue editing WORLDcodes.h and change:

```
const struct IrCode *NApowerCodes[] PROGMEM = {

```

to:

```
const struct IrCode * const NApowerCodes[] PROGMEM = {

```

---

And also change:

```
const struct IrCode *EUpowerCodes[] PROGMEM = {

```

to:

```
const struct IrCode * const EUpowerCodes[] PROGMEM = {

```

It should now compile OK.
> 0 votes

---
Tags: compile
---


title: Sine Wave Inverter

text:
# Question
Title: Sine Wave Inverter
I am working on building a pure sine wave inverter using an Arduino Uno to output two PWM signals for the top and bottom half of the wave. Currently I am outputting pre-calculated values with an interrupt as PWM. This seems to be working but I was wondering if anyone had any feedback on my design, and whether there is a better way to go about doing this. I will also need to incorporate feedback into this to vary the max PWM duty cycle, and I am worried the ATMEGA will not be able to keep up do this fast enough.

Please let me know if you want any more details, thanks in advance!

Olls

The spreadsheet I'm using to calculate the values.

```
#include "TimerOne.h"

int duty_cycle;
int x = 0;

// sin_table is made up of sin(0-400) values multiplied by PWM_PERIOD
// https://docs.google.com/spreadsheets/d/1iyveHnOxIzqg907T6pu4znsJE-6tg40juMihDvU8Tbg/edit?usp=sharing
uint8_t _sin[] = { // Calculated for 50Hz at 200 pulses per half wave.
    0,0,0,1,1,1,2,2,3,3,3,4,4,5,5,5,6,6,6,7,7,8,8,8,9,9,9,10,10,10,11,11,12,12,12,13,13,13,14,14,14,15,15,15,15,16,16,16,17,17,17,17,18,18,18,19,19,19,19,19,20,20,20,20,21,21,21,21,21,22,22,22,22,22,22,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,23,23,23,23,23,23,23,22,22,22,22,22,22,21,21,21,21,21,20,20,20,20,19,19,19,19,19,18,18,18,17,17,17,17,16,16,16,15,15,15,15,14,14,14,13,13,13,12,12,12,11,11,10,10,10,9,9,9,8,8,8,7,7,6,6,6,5,5,5,4,4,3,3,3,2,2,1,1,1,0,0,0,0,0,1,1,1,2,2,3,3,3,4,4,5,5,5,6,6,6,7,7,8,8,8,9,9,9,10,10,10,11,11,12,12,12,13,13,13,14,14,14,15,15,15,15,16,16,16,17,17,17,17,18,18,18,19,19,19,19,19,20,20,20,20,21,21,21,21,21,22,22,22,22,22,22,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,23,23,23,23,23,23,23,22,22,22,22,22,22,21,21,21,21,21,20,20,20,20,19,19,19,19,19,18,18,18,17,17,17,17,16,16,16,15,15,15,15,14,14,14,13,13,13,12,12,12,11,11,10,10,10,9,9,9,8,8,8,7,7,6,6,6,5,5,5,4,4,3,3,3,2,2,1,1,1,0,0,0
};

void setup() {
    // Pin mode, and set low.
    DDRD = DDRD | B00011000;
    PORTD = B00000000;

    Timer1.initialize(47);
    Timer1.attachInterrupt(pwm);
}

void pwm() {
    if (PIND & B00000100) { // Inhibit switch

        // Lower half or upper half of wave, start PWM pulse
        if (x > 200) {
            PORTD = B00010000;
        } else {
            PORTD = B00001000;
        }

        duty_cycle = _sin[x];
        if (duty_cycle > 3) {
            delayMicroseconds(duty_cycle);
        }

        PORTD = B00000000;

        x++;
        if (x > 400) {
            x = 0;
        }
    }
}

void loop() {}

```

# Answer
> 1 votes
*Comment by olls converted to an answer*:

I did get it working. The schematic isn't mine to share unfortunately, but it consisted of some transistors to shift the PWM up to 20v, which then went into an inverter circuit (not made by me, quite complex) which merged the two PWM signals together into a AC signal. Then there was a transformer and RC filter to smooth out and amplify the PWM. Sorry I can't be more help, but it was a while ago, and I didn't make all of it.

---
Tags: arduino-uno, pwm
---


# Question
Title: MAX72XX with 8 digit 7 segment display library
A while ago, I found a library for the MAX72XX that had functions for writing text to the display, but unfortunately cannot find such library now.

Which would be the best library to use for a text and number display? I'm using LedControl but it is very awkward to use.

# Answer
I have a library for driving the MAX7219 chip connected to a 7-segment display. It is at: https://github.com/nickgammon/MAX7219

Example of use:

```
#include <SPI.h>
#include <bitBangedSPI.h>
#include <MAX7219.h>

const byte chips = 1;

// 1 chip, bit banged SPI on pins 6, 7, 8
MAX7219 display (chips, 6, 7, 8);  // Chips / LOAD / DIN / CLK

void setup ()
  {
  display.begin ();
  display.sendString ("HELLO");
  }  // end of setup

void loop () { }

```

In operation displaying a number:

More details at: Interfacing LED displays with the MAX7219 driver
> 3 votes

---
Tags: arduino-uno
---


title: Wire.endTransmission() Hangs

text:
# Question
Title: Wire.endTransmission() Hangs
I have written a code that transmits data over the I2C channel, The device ID and every other stuff is working fine. The only issue being that my code gets stuck at Wire.endTrasnmission().

I found the issue using Serial debug messages.

Strange thing:

When i disconnect the SCL line (A5 on arduino Pro Mini), the hang disappears and the code starts to function again.

A search brought me to this forum http://forum.arduino.cc/index.php?topic=66353.0

where a guy talks about the code snippet

```
if(hang)
unfreeze();

```

is this possible, if yes where do i place it?

Observation: The hang goes away if i disconnect the SCL line on either of the arduinos communicating, the sam edoes not happen if i disconnect the SDA.

# Answer
> The device ID and every other stuff is working fine. The only issue being that my code gets stuck at Wire.endTransmission().

* Nothing is transmitted until you call `Wire.endTransmission()` so that is where it will hang.
* You should not try to do Wire transmissions inside an ISR (if you are doing that).
* There is an alternative to the Wire library which times-out rather than hanging. It is at: Arduino I2C Master Library.
* Make sure you have pull-up resistors on SDA and SCL. Typically 4.7 k from both to +5 V.
* If none of that helps, please post your code.
> 7 votes

---
Tags: i2c, arduino-pro-mini
---


# Question
Title: Eeprom write function does not seem to write in more than 100 locations
I am trying log my sensor data (1 byte each) on my Arduino Uno Eeprom. I have an ATmega328 on it, so it should allow me to write up to 1Kb on it, however I've tried the Eeprom write command and it does not seem to write to more than 100 locations on it (the first 100 bytes!)

I am using the Eepromex library.

Any thoughts on what's causing this?

Edit:

These are the excerpts from my code related to Eeprom logging:

```
int addr1 = 0;
int addr2 = 256;

  // Store Data in EEPROM

  EEPROM.write(addr1,FinalMoisture[0]);

    delay(5);

  EEPROM.write(addr2,FinalMoisture[1]);

    delay(5);
  // advance index pointer to the next location.  There are 256 bytes assigned for each sensor in the EEPROM, so go back to 0 when we hit 255/511.

  addr1 = addr1 + 1;

  if (addr1 == 255)
    addr1 = 0;

  //same for addr 2 :

   addr2 = addr2 + 1;

  if (addr2 == 511)
    addr2 = 256;

  // delay until next measurement (msec)
 Sleepy::loseSomeTime(30000);

```

PS: As mentioned earlier I've included the EepromEx library. Each sensor stores only first 50 locations. Also, I've noticed that if I run a single loop instead of storing data in two locations, I can write 100 straight entries. In any case it seems that the write function is limited to 100?

Could this be a setting in the library? How to disable/modify it? I tried looking at the info on the lib author's postings but didn't help.

# Answer
> 2 votes
Looking at the library at https://github.com/thijse/Arduino-EEPROMEx/blob/master/EEPROMex.cpp it seems they limit the number of writes to 100:

```
EEPROMClassEx::EEPROMClassEx()
  :  _allowedWrites(100)
{
}

```

There seems to be a way of changing that:

```
/**
 * Set global maximum of allowed writes
 */
void EEPROMClassEx::setMaxAllowedWrites(int allowedWrites) {
#ifdef _EEPROMEX_DEBUG
    _allowedWrites = allowedWrites;
#endif
}

```

---
Tags: arduino-uno, eeprom
---


title: Serial communication with two devices

text:
# Question
Title: Serial communication with two devices
I have two devices connected to my Arduino using the SoftwareSerial library. However, it seems that they cannot communicate at the same time. I can only communiate with both by switching between which one I am listening to every 1000ms (they poll for 1500ms), but this slows down overall communication significantly. Is there anyway to communiate with both at the same time? Could this be achieved by using SoftwareSerial with one and the hardware serial port with the other?

# Answer
See SoftwareSerial Write to return Read in Serial Monitor? \- SoftwareSerial cannot both read and write at the same time.

However HardwareSerial can.

> Could this be achieved by using SoftwareSerial with one and the hardware serial port with the other?

Yes.

---

> So, likewise, there is no way to read from both devices using only SoftwareSerial?

That is correct. Not at the same time. SoftwareSerial uses an interrupt to detect the start bit of incoming data. So far so good. But once it gets it, it leaves interrupts disabled while it goes into a timed loop to read all the bits.

Thus, it is impossible for it to react to another incoming byte on another pin at the same time.

Still, you could receive on SoftwareSerial on one pin, and HardwareSerial on another. With HardwareSerial the hardware will run in the background, receiving the byte.
> 0 votes

---
Tags: serial
---


# Question
Title: Variables not initialized in Class Constructor
I'm creating a library driver for AdaFruit's GFX library. During Constructor initialization, all the variables (set in another .cpp) are returned as zero. This code has several modular files to separate graphics functions from graphics primitives from device interfacing. What am I doing wrong?

In the Arduino sketch I call the class constructor: MB\_GFX\_SPI (in file MB\_GFX\_SPI.cpp). In the Constructor I'm call a function: mbR.SetMatrixSize (in another file raster.cpp). Also in the Constructor I call a function: clearScreen (in the same file MB\_GFX\_SPI.cpp).

The test variable mbR.r\_totNumChannels set in clearScreen is returned with 99. All the variables set in mbR.SetMatrixSize return zero.

```
//Test Sketch
//Initialize both the Adafruit library and the current library.
//Instantiate an object mbGFX so all Adafruit GFX and MB_GFX add-on functions are addressed as mbGFX.xxx();
MB_GFX_SPI mbGFX = MB_GFX_SPI(Period, numCathodeLeds, numAnodeLeds, CathodeSSPin, AnodeSSPin);

//In file MB_GFX_SPI.cpp

MB_GFX_SPI::MB_GFX_SPI(int Period, int numCathodeLEDS, int numAnodeLEDS,
      int CathodeSSPin, int AnodeSSPin)
      : Adafruit_GFX(numCathodeLEDS, numAnodeLEDS) {

  mbR.SetMatrixSize(numCathodeLEDS, numAnodeLEDS);
  clearScreen(0);
}
void MB_GFX_SPI::clearScreen(uint16_t color) {
   mbR.r_totNumChannels = 99;   //test set value
}

//In file mb_raster.cpp

void mbRasterClass::SetMatrixSize(int numCathodeLeds, int numAnodeLeds){
//cathodes require 1 byte per channel
//anodes require 1 bit per channel

    int numAnodeChannels = numAnodeLeds;
    int numCathodeChannels = mbX.pin2pin * numCathodeLeds; //times 1 or 3

    r_numCathodeRegisters = (int)((numCathodeChannels+7)/8);   //select next higher number of registers
    r_numCathodes = 8 * r_numCathodeRegisters;  //must be whole 8 bit registers - is every single chatode pin
    r_numAnodeRegisters = (numAnodeChannels+7)/8;       //round up to next register number
    r_numAnodes = 8 * r_numAnodeRegisters; //must be whole 8 bit registers
    r_PWMBufferSize = r_totNumChannels = r_numAnodes * r_numCathodes;

    r_PWMBuffer = (uint8_t *) realloc(r_PWMBuffer, r_totNumChannels); //resize array for PWMBuffer
}

```

# Answer
> 1 votes
First, I would do what Edgar Bonet suggested, call the normal constructor:

```
MB_GFX_SPI mbGFX (Period, numCathodeLeds, numAnodeLeds, CathodeSSPin, AnodeSSPin);

```

Second, I'm not keen on what you are doing in the constructor for a variable which appears to be at global scope (mbGFX).

See What's the "static initialization order fiasco"?

Basically you cannot assume that constructors in different compilation units are called in any defined sequence, you also cannot assume that the system has been initialized yet (ie. `init()` called).

Thus, things that address the hardware (eg. `clearScreen(0);`) may not work properly, or at all.

---
Tags: c++, class
---


# Question
Title: can I create an on/off switch for my Arduino using the reset pin?
If i connect a switch to the reset pin, can I create an effective way of turning off the Arduino (overnight) without removing its power supply?

# Answer
> 1 votes
Tests show that connecting Reset to Ground on a Uno reduces the power consumption from 47 mA to 41 mA. So it is hardly "off".

All that would do is stop the currently-loaded sketch running, and save a few milliamps.

---
Tags: reset
---


title: Uploading... forever

text:
# Question
Title: Uploading... forever
This is my code:

```
const int trigPin = 4;
const int echoPin = 2;
const int trigPin2 = 6;
int incomingByte;
int val, val2;
const int echoPin2 = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(trigPin2, OUTPUT);
  digitalWrite(trigPin2, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin2, LOW);

  pinMode(echoPin, INPUT);
  pinMode(echoPin2, INPUT);

  val = digitalRead(echoPin);
  val2 = digitalRead(echoPin2);

  if (val && val2 == HIGH) {
    Serial.println("Elephant on tracks");
  }

  if (Serial.available() > 0) {  // if the data came
    incomingByte = Serial.read();
  }
  // read byte
  if(incomingByte == '0') {
     digitalWrite(trigPin, LOW);
     digitalWrite(trigPin2, LOW);
     Serial.println("The system is OFF.");  // print message
  }
}

```

Anyhow, I click upload, and as the title of this question says, have to wait forever. Not only this code, nothing gets uploaded. It was working just fine a week ago. I run a Windows 7 64-bit system, and have an Arduino Uno R3. Does anyone have any suggestions?

# Answer
> 1 votes
From your code, I assume that the bluetooth module is connected to pins 0 & 1 on the arduino. These pins are to be kept free/floating/not connected to anything if you need to upload code to your board.

Use software serial in such cases reduces the headache

# Answer
> 0 votes
*Comment by SR1 turned into an answer*:

Thanks for the suggestions. It finally worked. It was because of my HC-06 Bluetooth module. I don't know if the mistake was mine or if it is a fault with the module.

---

(Done to reduce "unanswered questions" on this site).

---
Tags: arduino-uno, uploading
---


title: Using UART to Set RTC

text:
# Question
Title: Using UART to Set RTC
I'm using an Adafruit NRF8001 Low Energy Bluetooth module and a Real Time Clock module with my Arduino board. I want to connect to the BLE module using UART to set the clock. I'll also be using UART to set alarms.

I'm not sure which is the best way to take a string from the UART receiver and pull it apart into the hours, minutes, second, etc.

Any ideas? I did look at the Arduino JSON library but it seems a little buggy, and possibly overkill.

Any help would be very much appreciated :)

# Answer
> 2 votes
The simplest method is to keep it as a fixed format string with line termination.

Read one line in from serial into a character array (aka C string) and then chop it up. As long as the string is in the correct format you can easily chop it around.

For instance, assume you chose the format `YYYY-MM-DD HH:MM:SS\n` which is quite common and easy to use, you may have data like this:

```
char *indata = "2015-08-22 17:23:48\n";

```

(`\n` is the new-line character)

Using simple char pointers you can get each substring quite easily:

First slice the string up into the component parts by replacing the separator tokens with character 0:

```
indata[4] = 0;
indata[7] = 0;
indata[10] = 0;
indata[13] = 0;
indata[16] = 0;

```

Then you can assign pointers to each segment:

```
char *year = indata;
char *month = indata + 5;
char *day = indata + 8;
char *hour = indata + 11;
char *minute = indata + 14;
char *second = indata + 17;

```

Or if you want it as integers, you can pass it straight to `atoi`:

```
int year = atoi(indata);
int month = atoi(indata + 5);
int day = atoi(indata + 8);
int hour = atoi(indata + 11);
int minute = atoi(indata + 14);
int second = atoi(indata + 17);

```

In fact, if passing it direct to `atoi()` you shouldn't need to even do the first stage, since it will stop parsing at the first non-numeric character.

There are more flexible ways of parsing the string too, using `strtok()`, but that is somewhat more advanced.

Note that this method is highly intolerant to invalid strings being passed, so you may want to first ensure that a) the string is the right length, and that b) there are the right separator tokens in the right placed, to validate that the string is properly formatted before proceeding.

---
Tags: string, rtc
---


# Question
Title: 433MHz transmitter and receiver pair doesnt work
I have a pair of 433 MHz transmitter and receiver:

Transmitter is connected to Arduino pro mini, receiver to Arduino Uno R3.

Output of receiver on serial looks like that (it doesn't change much):

Basicly I am getting either 75x or zero regardless of transmitter is on or off.

```
in > upper
756
in > upper
758
0
0
 0
in > upper
758
0
in > upper
757
in > upper

```

Transmitter code:

```
#define rfTransmitPin 4
#define ledPin 6

void setup()
{
    pinMode(rfTransmitPin, OUTPUT);
    pinMode(ledPin, OUTPUT);
}

void loop()
{
    for(;;)
    {
         digitalWrite(rfTransmitPin, HIGH);     //Transmit a HIGH signal
         analogWrite(ledPin, 255);              //Turn the LED on
         delay(500);                            //Wait for 1 second

         digitalWrite(rfTransmitPin,LOW);       //Transmit a LOW signal
         analogWrite(ledPin, 0);                //Turn the LED off
         delay(500);                            //Variable delay
    }
}

```

Receiver code:

```
const unsigned int upperThreshold = 70;  //upper threshold value
const unsigned int lowerThreshold = 0;  //lower threshold value
const int ledPin = 13;

#define ReceiverPin  A0

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

    pinMode(ledPin, OUTPUT);

    DiodeTest();
}

void loop()
{
   int data = analogRead(ReceiverPin);
   delay(50);

   if(data>upperThreshold)
   {
       digitalWrite(ledPin, LOW);   //If a LOW signal is received, turn LED OFF
       Serial.println("in > upper");
   }

   if(data<lowerThreshold)
   {
       digitalWrite(ledPin, HIGH);   //If a HIGH signal is received, turn LED ON
       Serial.println("in < lower" );
   }

   Serial.println(data);
}

```

# Answer
> 3 votes
These types of receivers are AC coupled so you will not be able to do what you are doing as you need to have regular transitions in the signal and not stay in one state for too long.

They are also limited in the speed at which they will work, I expect 19200 bps is too fast.

You need to use a modulation technique such as Manchester Encoding or other technique that guarantees a suitable density of transitions, can synchronize the data and perform error checking.

One popular software library that does this is VirtualWire Arduino Library that is designed for Arduino and the type of transmitters and receivers you are using.

# Answer
> 1 votes
See this post about a radio-controlled car.

I found when using what looks like a similar receiver to yours, that the received data looked like this:

The cyan line was the receiver, the yellow line is what is being transmitted.

The trouble turned out to be the pull-up resistor on the Arduino Rx pin (from the USB chip).

Even with SoftwareSerial it wasn't too great:

I found that using an op-amp as a buffer helped a lot:

---

I also agree with the comments about adding an aerial wire, just a short length of hookup wire should do it.

# Answer
> 0 votes
You also need to attach a piece of insulated wire as a 1/4 wave length antenna to each of the receiver and transmitter boards. For the 433 MHz type antenna's this would be a piece of wire ~6.8" (17.3cm) long.

For reference if you were using the other popular type of low cost RF link pair at 315 MHz the antennas would be ~9.37" (23.8cm) long.

---
Tags: remote-control, electronics
---


# Question
Title: Connecting MicroSd Reader with arduino uno
I am working on a Project with (a) Arduino Uno Clone (6 PWM Pins i.e, 3,5,6,9,10,11) (b) 6 Servos (c) MicroSD Reader Module (d) Speaker

As We Know that MicroSD reader modules uses pins 10, 11, 12 of an Arduino board, but **my pin 11 is already being used by a servo motor**. 1. Then how can I connect the MicroSD reader in my project ? 2. Which pin can I use for the speaker in this case ?

Please help me plus Provide me some additional information if needed.

# Answer
> 3 votes
The best answer is: *don't use pin 11 for your servo motor - move it to another pin*.

The SD card needs SPI. SPI is pins 10/11/12/13. You can't change that. You can much more easily move the servo to a different pin, since there are multiple PWM pins that can support the servo in hardware. If they are all taken then software PWM is easy and there are libraries available to do it for you, so you can use any IO pin you like for that. Much simpler than re-writing the SD card software to use bit-banged SPI on other pins (which would also be incredibly slow).

---
Tags: arduino-uno
---


title: Programming arduino with Objective-C

text:
# Question
Title: Programming arduino with Objective-C
Can you use `clang`, with `--mpu=arm`, etc. and `avrdude` to program an Arduino Due (Arm Cortex M3)?

# Answer
> 0 votes
It can be done, however, it is inadvisable. In order to implement this, one must implement the Objective-C runtime, which, though not insurmountable, is very near insurmountable as far as difficulty is concerned. Perhaps someday some brave soul will see fit to grace the world with their custom Arduino Objective-C runtime, but until that day, the rest of us mere mortals have naught to do but wait for the coming of the Objective-C prophet.

If there are any brave souls in the audience who wish to take on this ultimate challenge, then let them. But otherwise, keep the code in C and hold your peace.

# Answer
> 4 votes
Simple version: No, you cannot program Arduino using Objective-C.

Long version: The Arduino IDE uses avr-gcc as it's compiler, and avr-gcc is a C/C++ compiler, not an Object-C compiler. The Arduino libraries are written in C/C++.

There are other compilers that exist for *AVR* processors, and so it is possible to use other languages for the *AVR*.

However, if you switch to a different compiler for your code, you will not be able to use the Arduino libraries with it, because they are written in C/C++ for the avr-gcc compiler. (It may be possible to compile the Arduino libraries with avr-gcc, and then link them to your code using external language linking methods, but that could be a significant challenge.)

Also, I do not know of any existing Objective-C compilers for AVR; it's possible one may exist, but after a quick web search, I didn't find any.

# Answer
> 2 votes
Theoretically, many things are possible. There is an easy way to code Arduino on Xcode with EmbedXCode (http://playground.arduino.cc/Main/EmbedXcode), but in C and CPP.

You need a compiler that will compile your Objective-C to for the AVR (if you are using an AVR-based Arduino), this may be difficult to find. Once your code is compiled, then you need to upload it to the Arduino.

So in any reasonable means, it is at least very challenging.

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


# Question
Title: What does a higher clock signal frequency actually mean for my AHRS?
I've got an Arduino with an ATmega328 processor. It can be operated at 3.3V which nets a clock signal frequency of about 12 MHz respectively 16 Mhz at 5V.

I've got an IMU connected to the Arduino and a AHRS algorithm turning accelerometer, gyroscope and magnetometer data into orientation data.

What does the higher frequency of 16 MHz actually mean in this context?

Will the AHRS be calculated faster so I get a lower latency? Can I poll the sensors more often? I want a deeper understanding of what I'm doing here.

# Answer
> What does the higher frequency of 16 MHz actually mean in this context?

The Arduino will run a bit faster (33% faster). Therefore it could calculate things faster. Whether you can poll the sensors more often might depend on the sensor. Limiting factors could be how fast you can communicate with the sensor, how often the sensor takes readings, what you are going to do with the readings, and whether it matters if calculations are a bit slower.

For a better response I suggest you post a link to the particular sensor, the AHRS algorithm you are using, and describe the application you are using it for.
> 1 votes

---
Tags: arduino-uno, accelerometer, gyroscope, frequency
---


# Question
Title: Cannot bootload again after changing the board?
We are so tired and would like to get help with this. We are trying to bootload using the arduino Uno.

We have an `atmega 328p` smd , that we are trying to bootload. We have connected all the right pins, added to the boards.txt the `"Atmega328 on a breadboard(8mhz internal clock)"`.

Then I have chosen from the "board" menu, this option (internal clock), and uploaded the program. **it worked** .

Later, I wanted to try and bootload for external clock so I chose from the boards menu the `pro mini with 5v board.`(is it wrong?)

Not only that I got an error, now, **I can't bootload the internal clock again** !!

Why can't we bootload again? Did we damage something? Can it be reset again? How can you bootload for external 16Mhz ??

error :

```
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again

```

# Answer
> Not only that I got an error, now, I can't bootload the internal clock again !

You need an external clock source, such as a crystal and two capacitors. Once you switch the fuses to the external clock it won't work any more unless you have such a clock.

I have a bootloader uploader sketch that also provides a clock signal if you need it.
> 1 votes

---
Tags: arduino-uno, atmega328, bootloader, avrdude
---


# Question
Title: Direct port manipulation to write 40 bits
I have 5 shift register changed in series and want to shift the data quickly. I have learned that the internal shiftOut function is slow and direct port manipulation can speed up the things.

However, I am not sure to write code in the specific way.

The current working code block is:

```
#define SensDataPin 4
#define SensClockPin 9
#define SensLatchPin 8
updateAllShifters()
{
digitalWrite(SensLatchPin, LOW);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_1);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_2);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_3);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_4);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_5);
digitalWrite(SensLatchPin, HIGH);
}

```

As the code shows, I have 5 bytes which are written by independent functions and just before the return statement, these functions call "updateAllShifters()" to mark the changes.

I have followed few tutorials over the internet and have re-written the logic like:

```
#define MSDATAHIGH PORTD |= (1<<PD4)
#define MSDATALOW PORTD &= ~(1<<PD4)
#define MSLATCHHIGH PORTB |= (1<<PB0)
#define MSLATCHLOW PORTB &= ~(1<<PB0)
#define MSCLOCKHIGH PORTB |= (1<<PB1)
#define MSCLOCKLOW PORTB &= ~(1<<PB1)
updateAllShifters()
{
MSLATCHLOW;
for(int i=0;i<40;i++)
{
HOW TO CODE HERE USING THE DEFINED MACROS!
}
MSLATCHHIGH;

```

Edit: Coding example of this (but want a more optimized way):

```
#define MSDATAHIGH PORTD |= (1<<PD4)
#define MSDATALOW PORTD &= ~(1<<PD4)
#define MSLATCHHIGH PORTB |= (1<<PB0)
#define MSLATCHLOW PORTB &= ~(1<<PB0)
#define MSCLOCKHIGH PORTB |= (1<<PB1)
#define MSCLOCKLOW PORTB &= ~(1<<PB1)
updateAllShifters()
{
MSLATCHLOW;
for(byte i=0;i<8;i++)
{
 if(!!(byte_1 & (1 << i)));// LSBFIRST
   {
   MSDATAHIGH;
   }else
   {
   MSDATALOW;
   }
}
 MSCLOCKHIGH;
 MSCLOCKLOW;
//DO ABOVE FOR ALL REMAINING 4 BYTES
MSLATCHHIGH;
}

```

# Answer
> I have few SPI ADC which have forced SPI bus down to 1 Mhz. I understand that the shiftout works at 14Khz which is too slow.

You can change the SPI speed at any time. Once the device is selected (Slave Select asserted) then reconfigure the SPI bus for high speed operation.

eg.

```
SPI.setClockDivider(SPI_CLOCK_DIV2);

```

SPI is definitely the fastest way you can communicate with a shift register.
> 2 votes

---
Tags: digital, shift-register
---


# Question
Title: Data from PROGMEM array mismatches initialisation
The amount of memory needed for my user interface is outrageous. Hence I decided to use flash memory. But after some successful readouts from program space, problems emerge.

**Updated:** I have some sort of initialisation files to collect all global arrays which go into flash like this: (intitialisation.cpp)

```
#ifndef INITIALISATIONDEF
#define INITIALISATIONDEF

#include "initialisation.h" //which includes Arduino libraries and "globals.h"

const uint8_t gl_PsNMenuType[MAXMENUS] PROGMEM = { 0, 0, 0, 0, 0};  // this is, what I intend to read out later.
const uint8_t gl_PsNMenuParent[MAXMENUS] PROGMEM = { MAXMENUS, 0, 0, 0, 0};
const uint8_t gl_PsNMenuFixTexts[MAXMENUS][MAXFIXTEXTSPM] PROGMEM = {
  { 20, 2, MFTS, MFTS, MFTS}, // 0
  {2, 9, 1, MFTS, MFTS}, // 1
  {2, 10, MFTS, MFTS}, //2
  {2, 11, MFTS}, //3
  {2, 12, MFTS} //4

};
#endif

```

**Updated:** while I propagate all global vars via another header (globals.h):

```
#ifndef GLOBALS
#define GLOBALS
#define SDTXT

#define MAXMENUS 80
#define MAXFIXTEXTSPM 5

#include "initialisation.h"
extern const uint8_t gl_PsNMenuType[MAXMENUS];
extern const uint8_t gl_PsNMenuParent[MAXMENUS];  // referenz auf den übergeordneten MP
extern const uint8_t gl_PsNMenuFixTexts[MAXMENUS][MAXFIXTEXTSPM];  // Liste der festen Menütexte zu jedem MP
#endif

```

as one can see, I do not initialise my arrays fully, as I'm in a development phase, but the first bytes should be zeroed out correctly AFAIK.

But, when accessing my stored values later in a third file: (uimenu.cpp)

```
#include "uimenu.h" // which includes globals.h and initialisation.h

// somewhere in the code inside a function, with uint8_t mp=0:
Serial.print(pgm_read_byte(gl_PsNMenuType[mp]));

```

The last line should print 0, as stated in initialisation, but it prints 12.

So, I think, I'm doing sth. substantially wrong here, but have no clue at the moment. I have several guesses:

1. I should not use const with PROGMEM. I did this to be informed by the compiler, if I accidentally write to an array stored in flash.
2. I made some mess with #includes, perhaps with order of occurrence. At the moment I try to sort the order out.
3. There's something with having global variables or arrays defined and declared in a header and accessed in another source files function. But I cannot imagene, what.
4. **Updated:** something wrong with my indices for my arrays? is uint8\_t insufficient?

If you need more information or code, I'll edit my question accordingly. Thanks in advance! I appreciate any help. (all files were edited for brevity before posting them)

**Update:** I moved the definitions of the progmem arrays to the source file and all macro constants (#define) to globals.h. The outcome is: different numbers are printed, but they are wrong whatsoever. I poked elsewhere into the progmem array and got other wrong numbers.

# Answer
> 1 votes
> @TMa: seems to work! I totally missed the necessity of referencing the array element. Thanks a lot. But I did not get any compiler warnings without the reference operator. Why isn't this call type-safe?

The PROGMEM word is an **attribute**, not a **type**. It might be type-safe but not attribute-safe (if there is such a thing). See Data in Program Space

---

## Reference

Putting constant data into program memory (PROGMEM)

---
Tags: progmem
---


# Question
Title: Increment in switch statement not working
No matter how I rearrange this, the increment compare always returns false....

I have even taken it out of the if, and put it in its own if:

```
int buttonFSM(button *ptrButton)
{
    int i;
    i = digitalRead(ptrButton->pin);
    switch(ptrButton->buttonState)
    {
    case SW_UP:
        if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down
        {
            ptrButton->buttonState = SW_DOWN;
            ptrButton->debounceTics = 0;
            return SW_TRANS_UD;
        }
        ptrButton->debounceTics = 0;
        return SW_UP;
    case SW_DOWN:
        if(i==1 && ++ptrButton->debounceTics == DBNC_TICS) //switch is back up
        {
            ptrButton->buttonState = SW_UP;
            ptrButton->debounceTics = 0;
            return SW_TRANS_DU;
        }
        ptrButton->debounceTics = 0;
        return SW_DOWN;
    }
}

```

# Answer
Looks to me like the path where the if doesn't happen are getting you. You don't show what DBNC\_TICS is set to, but I'm assuming it's \> 1.

ptrButton-\>debounceTics will never be greater than 1 because you always:

```
    ptrButton->debounceTics = 0;

```
> 1 votes

# Answer
The error is due to wrong expectations on operators precedence: ++ and -\> have the same precedence, so they are evaluated left to right. See http://en.cppreference.com/w/c/language/operator\_precedence .

Overall, the lack of parenthesis makes the readability poor.

The code can be improved by dropping the switch and simply checking that the current value is equal to the previous value through the duration of the sampling period. Then read the value and decide if it's high or low.

But even this might be a poor choice, because it simply samples the value periodically and can miss changes that are not intercepted by the sampling.

Depending on the application, it might be preferrable (certainly it is more precise) to use interrupts on both edges (rising and falling) and a timeout: reset the timer at every interrupt. If the timer expires undisturbed, use the level read at the last interrupt.
> 0 votes

# Answer
```
  if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down
    {
        ptrButton->buttonState = SW_DOWN;
        ptrButton->debounceTics = 0;
        return SW_TRANS_UD;
    }
    ptrButton->debounceTics = 0;

```

I'm going to agree with user3877595 but explain why, as his/her answer got a downvote.

`DBNC_TICS` has to be \> 1, right? Otherwise what is the point?

We want to debounce after "x" ticks, and let's assume that the number of ticks is initially zero.

If `DBNC_TICS` is == 1 then this is always true:

```
++ptrButton->debounceTics == DBNC_TICS

```

Therefore that test is useless.

If `DBNC_TICS` \> 1 then it will not execute the "if" block and execute this instead:

```
    ptrButton->debounceTics = 0;

```

So `ptrButton->debounceTics` is back to zero, and we are back to square 1.

Therefore the test will always be false.

> No matter how I rearrange this, the increment compare always returns false....

As stated in the question.
> 0 votes

---
Tags: arduino-mega
---


# Question
Title: What does “LSB per degree per second” mean?
I'm currently working with a digital output gyroscope. Its sensitivity is given as 120 least-significant bit per degree per second.

While every single component of that unit is easy to understand I don't quite get what it means altogether.

**Can you explain it to me?**

# Answer
Let us say we have a number, "4025". The "most significant digit" of the number is the 4 in the thousands position, since it tells us the most about the magnitude of the number ("in the four thousands"). Consequently, the "least significant digit" is the 5 in the units position, since it tells us almost nothing about the magnitude of the number. "Most/least significant bit" is the same, except it applies to binary numbers (which the MCU cares about, of course; we can still use any radix we like to talk about them). So the device's output count can change by up to 120 per degree per second.
> 5 votes

# Answer
With further elaboration on Ignacia's answer:

A gyroscope itself is generally an analog device in the sense that in reality, it will have a continous output. This output is digitized using some form of Analog to Digital A/D converter where the analog output is converted to a digital number. The output from the gyroscope is a measurement of angular speed, generally millidegrees/sec.

The number read by your Arduino from the gyroscope will be a digital version of your current angular speed at the time of measurement. For example, if you're getting an 8bit number back equal to 121, this in binary is equivalent to 01111001, where the '1' furthest to the right is the least significant bit.

The term "lsb per degree per second" means how many bits change with your angular speed. For example, with a gain of 1 (meaning 1 degree/second = 1 bit), an angular speed of 90 degrees/sec will produce a read value of 90 or 01011010. Therefore, 1 bit changes per degree/second. Increasing the essential "gain" (which will most likely be referred to as "dps" will change how many lsb's change per degree/second.
> 4 votes

---
Tags: programming, digital, gyroscope
---


# Question
Title: Pass a member function pointer to a method of a foreign class (EDB Lib)
I'm currently working on my own arduino library and I'm becoming exasperated with the following problem: I want to store data with the extended database library (https://code.google.com/p/arduino-edb/) on a sd card. I tried to follow and adapt the instructions on this page and I gave my custom library a property "File dbFile" as well as a property "EDB db". Additionally I have to pass two function pointers to the constructor of the EDB library. So my custom library got two more properties: a writer and a reader function. My class looks roughly like that:

```
class myLib
{
   public:
      myLib();
      ~myLib();
      void configWriter( unsigned long address, byte data );
      byte configReader( unsigned long address );
      File dbFile;
      EDB configDB;
}

```

...so far so good. But here comes the pain in the ... When I'm trying to instantiate a new EDB object in the constructor of my class by passing two pointers to the member functions I'm constantly getting an error. Here is how I call the constructor of the EDB library:

```
configDB = new EDB( &myLib::configWriter, &myLib::configReader );

```

I get the following error:

> no matching function for call to 'EDB::EDB()'
>
> \[...\] note: candidates are:
>
> note: EDB::EDB(void (*)(long unsigned int, uint8\_t), uint8\_t (*)(long unsigned int)) EDB(EDB\_Write\_Handler \*, EDB\_Read\_Handler \*);

The prototype of the EDB constructor looks like this:

> EDB(EDB\_Write\_Handler \*, EDB\_Read\_Handler \*);

EDB\_Write\_Handler and EDB\_Read\_Handler are defined like so:

> typedef void EDB\_Write\_Handler(unsigned long, const uint8\_t); typedef uint8\_t EDB\_Read\_Handler(unsigned long);

So I assume that my constructor call doesn't work because the functions that I'm passing are from a foreign class: (myLib::*) and not just (*)

I have no idea how to solve that problem. Does someone of you have any idea?

Thanks, Andy

EDIT: Here is a Minimal, Complete, and Verifiable example:

myLib.h:

```
#ifndef myLib_h
#define myLib_h

#include "Arduino.h"
#include <SPI.h>
#include <SD.h>
#include <EDB.h>

#define SD_CS 4
#define SD_SS 10

class myLib
{
  public:
    myLib();
    ~myLib();
    void begin();
    void configWriter( unsigned long address, byte data );
    byte configReader( unsigned long address );
    File dbFile;
    EDB * configDB;

};

#endif

```

myLib.cpp:

```
#include "myLib.h"

myLib::myLib( void )
{}

myLib::~myLib()
{}

void myLib::begin()
{
  // Init SD
  pinMode(SS, OUTPUT);
  SD.begin(SD_CS);

  // Load Config
  configDB = new EDB( &myLib::configWriter, &myLib::configReader );
  dbFile = SD.open("config.db", FILE_WRITE);
}

void myLib::configWriter( unsigned long address, byte data )
{
  dbFile.seek(address);
  dbFile.write(data);
  dbFile.flush();
}

byte myLib::configReader( unsigned long address )
{
  dbFile.seek(address);
  return dbFile.read();
}

```

Arduino sketch:

```
#include <SPI.h>
#include <SD.h>
#include <EDB.h>
#include "myLib.h"

myLib* a;

void setup()
{
  a = new myLib();
  a->begin();
}

void loop()
{
}

```

# Answer
The problem here is a common one with C++. It basically boils down to how C++ handles member functions.

You define a member function as, say,

```
class myLib {
    void myFunc(int val);
};

```

When you call the function it's actually not defined as that - it's instead had its definition change to:

```
void myFunc(myLib *this, int val);

```

The addition of the `myLib *this` is an *implicit* parameter, and it's how C++ keeps track of its object instances when calling different functions.

So a function which expects a parameter of `void (*func)(int)` won't accept your method because it's actually `void (*func)(myLib *, int)`. Hence the error you are seeing.

There is no easy, clean, way around it that I have found as yet, I am afraid. The closest you can do is to move the reader and writer functions outside of your class and store a global pointer to the actual class, something like:

```
static myLib *globalLib;
void globalConfigWriter( unsigned long address, byte data ) {
    globalLib->congigWriter(address, data);
}
byte globalConfigReader( unsigned long address ) {
    return globalLib->configReader(address);
}

```

Then in the constructor for your lib you can do:

```
myLib::myLib() {
    globalLib = this;
}

```

You then register the global reader and writer functions with the EDB constructor instead of the class member functions.

It does have the rather major down-side that there can only be one instance of your class since there is only one global pointer and only one pair of reader / writer functions. There are ways of supporting a finite number of instances, but it basically involves having a reader/writer pair for each instance and allocating one to an instance when it's constructed and de-allocating it when its destructed. Keeping track of them and knowing which object is associated with which function pair is tricky at best...
> 2 votes

# Answer
Can you post a Minimal, Complete, and Verifiable example? We don't care what the functions do, just make up an example that demonstrates the message.

---

Having said that, this looks wrong:

```
class myLib
{
   public:
      myLib();
      ~myLib();
      void configWriter( unsigned long address, byte data );
      byte configReader( unsigned long address );
      File dbFile;
      EDB configDB;
}

```

> Here is how I call the constructor of the EDB library:

```
 configDB = new EDB( &myLib::configWriter, &myLib::configReader );

```

OK so myLib is a **class**, not an **instance of a class**.

> The prototype of the EDB constructor looks like this:

```
    EDB(EDB_Write_Handler *, EDB_Read_Handler *);

```

So you want an **instance** of EDB\_Write\_Handler.

---

Let's say that EDB needed a dog and a cat. You don't pass "dog" and "cat" you pass "Fido" and "Fluffy". They are instances of the classes.

---

You have this:

```
configDB = new EDB( &myLib::configWriter, &myLib::configReader );

```

The constructor for EDB expects two functions:

```
EDB(EDB_Write_Handler *, EDB_Read_Handler *);

```

These are declared like this:

```
typedef void EDB_Write_Handler(unsigned long, const uint8_t);
typedef uint8_t EDB_Read_Handler(unsigned long);

```

These are **static** functions, that is, they cannot be class functions. Why not? Because a class function has an implicit pointer **this** which points to this instance of the class.

So, you cannot pass a non-static class-function to the EDB constructor.

Now you can make the functions configWriter and configReader static, but then they can't access class variables (eg. dbFile) because they belong to an **instance** of the function.

I've tried fiddling around with your code, but without a clear understanding of your intentions, I can't get it to compile. Do you mean to **derive** your class from EDB?

Why do you even want a class `myLib`? Are you planning to have multiple instances of it? If so, why? If not, why make a class?
> 0 votes

---
Tags: c++, library, class, pointer
---


# Question
Title: Arduino Servo.h library returns error in compilation
I have a problem with Servo library. This is my (very short XD) "code":

```
#include <Servo.h>

void setup() {
  Servo.attach(9, 554, 2400);
}

void loop() {
  Servo.write(2000);
}

```

And it returns:

```
Arduino:1.6.5 (Windows 7), Board:"Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

sketch_aug24a.ino: In function 'void setup()':
sketch_aug24a:4: error: expected unqualified-id before '.' token
sketch_aug24a.ino: In function 'void loop()':
sketch_aug24a:8: error: expected unqualified-id before '.' token
expected unqualified-id before '.' token

```

Like there is no included library. What can I do with it ?

# Answer
> 2 votes
`Servo` is a class not an object. You have to instantiate it, and then call the functions on the instance. For example:

```
#include <Servo.h>

Servo sv;

void setup() {
  sv.attach(9, 554, 2400);
}

void loop() {
  sv.write(2000);
}

```

(Unlike some other libraries, it's done this way so that you can use more than one servo at the same time. You'd make one instance for each servo you want to control.)

---
Tags: c++, servo, compile
---


# Question
Title: Powering Arduino Pro Mini + Driving LED Strip
Just looking for a second opinion on my circuit below. Wired up everything works great, but last night as i was unplugging the FTDI programmer something seemed to have happend, and the mini was bricked.

I'm not sure if it has to do with my wiring below, or if it was me unplugging the cable in a haphazard manner.

What I'm attempting to do is run my arduino from 12v wall supply, but also drive an LED strip with it. I'm just unsure if this is the best way to go about it, any advice is welcome.

Thanks Justin

# Answer
According to the schematics, the Pro Mini uses the MIC5205, which is a linear regulator. Using it directly with 12V is not a very good idea, in terms of power efficiency, as it will dissipate 35mW vs 25mW provided to the ATMega board.

From this perspective, I'd recommend a step-down converter for powering the Arduino.

However it will not cause any damage, at least at room temperature, as the power dissipation is well within operating margins, see calculation at page 8 of the MIC datasheet.

**Edit:** detailed pros and cons, power wise.
> 1 votes

---
Tags: led, mosfet
---


# Question
Title: How to change the topic_name string to PROGMEM?
I'm trying to save SRAM on my Arduino pro mini by going through some libraries. I've noticed that to use my Arduino as a ROS node the library stores the topic name and message type as constants.

```
class Publisher
{
public:
  Publisher( const char * topic_name, Msg * msg, int    endpoint=rosserial_msgs::TopicInfo::ID_PUBLISHER) :
    topic_(topic_name),
    msg_(msg),
    endpoint_(endpoint) {};

  int publish( const Msg * msg ) { return nh_->publish(id_, msg); };
  int getEndpointType(){ return endpoint_; }

  const char * topic_;
  Msg *msg_;
  // id_ and no_ are set by NodeHandle when we advertise
  int id_;
  NodeHandleBase_* nh_;

private:
  int endpoint_;
};

```

How can I store the constants to PROGMEM? Thank you

# Answer
My take on this is that you cannot save more memory on `topic-name` nor `msg` parameters. Their memory usage is already optimized.

The `const` keyword in the constructor declaration `Publisher( const char * topic_name, Msg * msg, ...` just tells the compiler that the parameter won't be changed throughout their life cycle. But their values will be defined at run-time during object creation when you issue something like this:

```
Publisher pb = new Publisher("topic", "message", ...);

```

So, they cannot be put into flash memory if they are not there already. But if the strings you pass on to the constructor are already in flash, then you're already saving those bits of RAM.

---

Finally, I just wanted to warn you not to modify 3rd party lib code extensively without comprehensive testing, like you are trying to do. You'll start to get strange behavior in your code. The slightest and simplest of changes may have unforeseen consequences.
> 1 votes

---
Tags: arduino-uno, programming, arduino-ide, library
---


# Question
Title: Not able to receive the operation results from the slave after the command being sent by Master - SPI
Brief - I am using two arduino Uno's. One acts as a master and the other as slave using Arduino IDE. Below is the Master Code:

```
// Taken from Nick Gammon's Forum//

#include "SPI.h"
#include"pin_arduino.h"
int ss = 10;
void setup()
  {
    pinMode(ss,OUTPUT);
    Serial.begin(9600);
    Serial.println();
    digitalWrite(ss,HIGH);
    SPI.begin();
    SPI.setClockDivider(SPI_CLOCK_DIV8);
   }
byte transferAndWait(const byte what)
 {
   byte a = SPI.transfer(what);
   delayMicroseconds(20);
   return a;
 }
void loop()
 {
   byte a,b,c;
   digitalWrite(ss,LOW);
   transferAndWait('a');
a = transferAndWait(17);
b =  transferAndWait(33);
c = transferAndWait(0);
digitalWrite(ss,HIGH);
Serial.println(a,DEC);
Serial.println(b,DEC);
Serial.println(c,DEC);
delay(1000);
 }

```

Before I go into the details of the results I obtained and the problem, below is the Slave code:

```
//Taken from Nick Gammon's Forum//

#include "SPI.h"
#include "pins_arduino.h"
int slave = 10;
int miso = 11;
byte c = 0;
void setup()
  {
    pinMode(miso,OUTPUT);
    pinMode(slave,INPUT);
    Serial.begin(9600);
    SPR|= BV_(SPE);
    SPR|= BV_(SPIE);
 }
ISR(SPI_STC_vect)
 {
   c = SPDR;
  switch(c)
    {
      case 0:
      SPDR = 0;
      break;

     case 'a':
     SPDR = c + 15;
     break;
   }
  }
  void loop(void)
   {
     if(digitalRead(slave)==HIGH)
     c = 0;
   }

```

My Results : After dumping the master and slave codes into their respective arduino uno's, then when I open the serial monitor of the master code, It displays the number 17, 33, 0 and the same goes with the slave, meaning that the data is being sent to the slave and received back successfully, and hence I presume the SPI bus is working properly!. But why isn't the add operation happening?

Problem: Now the problem is, when the command 'a' is sent from the master to the slave, the slave has to interpret this 'a' command as Addition command and perform the addition of a number 15 to the incoming byte from the master as shown in the slave code, and return the results to the master, which should display the addition results in the masters serial monitor. I am having problem performing this task and looking forward to suggestions on how to test or where I am doing wrong or make changes to the code or methods in order to get this working. I am expecting answers relevant to the below codes and method.

# Answer
Since I wrote that example, I'll try to answer this. First I tested with the code from my page about SPI.

---

## SPI Master

This is the master:

```
#include <SPI.h>

void setup (void)
{
  Serial.begin (115200);
  Serial.println ();

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (20);
  return a;
} // end of transferAndWait

void loop (void)
{

  byte a, b, c, d;

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('a');  // add command
  transferAndWait (10);
  a = transferAndWait (17);
  b = transferAndWait (33);
  c = transferAndWait (42);
  d = transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("Adding results:");
  Serial.println (a, DEC);
  Serial.println (b, DEC);
  Serial.println (c, DEC);
  Serial.println (d, DEC);

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('s');  // subtract command
  transferAndWait (10);
  a = transferAndWait (17);
  b = transferAndWait (33);
  c = transferAndWait (42);
  d = transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("Subtracting results:");
  Serial.println (a, DEC);
  Serial.println (b, DEC);
  Serial.println (c, DEC);
  Serial.println (d, DEC);

  delay (1000);  // 1 second delay
}  // end of loop

```

---

## SPI Slave

And this is the slave:

```
// what to do with incoming data
volatile byte command = 0;

void setup (void)
{

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  // add to incoming byte, return result
  case 'a':
    SPDR = c + 15;  // add 15
    break;

  // subtract from incoming byte, return result
  case 's':
    SPDR = c - 8;  // subtract 8
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{

  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH)
    command = 0;
}  // end of loop

```

---

## Test results

Testing gave the expected results:

```
Adding results:
25
32
48
57
Subtracting results:
2
9
25
34

```

---

So, what is different in your code?

Your slave ISR:

```
ISR(SPI_STC_vect)
 {
   c = SPDR;
  switch(c)
    {
      case 0:
      SPDR = 0;
      break;

     case 'a':
     SPDR = c + 15;
     break;
   }
  }

```

This isn't quite the same, is it? In my code you get the command in one session (one interrupt) and what to use it for in another one.

Hence I had this:

```
  byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

```

Sending a "command" of zero clears the current command. So the sequence being sent is like this:

```
0    <-- start a new command
command  (ie. 'a' or 's')
22   <-- what to add to
33   <-- what to add to
44
55

```

Perhaps confusingly, I didn't send in that order, because I knew that the command would be zero initially<sup>(1)</sup>, so I actually sent:

```
command  (ie. 'a' or 's')
22   <-- what to add to
33   <-- what to add to
44
55
0    <-- start a new command

```

There would be other ways of achieving this, but the fact is you changed the way the slave interpreted the incoming data.

---

1. I knew it would be zero because the slave sets the command to zero in the main loop if SS is not asserted.
> 1 votes

# Answer
```
ISR(SPI_STC_vect);  <-- Reason 1.
 {
   byte c = SPDR;
  switch(command)   <-- Reason 2.
    {                      |
      case 0:              |
      command = c;  <------┘
      SPDR = 0;
      break;

     case 'a':
     SPDR = c + 15;
     break;
   }
  void loop(void)   <--- Reason 3.
   {
     if(digitalRead(slave)==HIGH)
     command = 0;
   }

```

The slave code is not going to work, for various reasons.

Reason 1: This is a declaration of a function. Not an implementation. The ";" is badly misplaced here.

Reason 2: You're switching on a value "command" but it's only changed after executing the case/command?

Reason 3: The loop function is still part of the previous function? The "{" below the ISR(SPI... isn't closed right. (With another "}")
> 0 votes

---
Tags: arduino-uno, arduino-ide, spi
---


# Question
Title: undefined reference to `PPMintIn::PPMintIn(int)'
I am making a new library that will utilize PinChangeInt's library. My intention is to further simplify repetitive code by creating a library. (This is to allow for multiple PPM channels without rewriting a bunch of code for each channel i decide to add.) Since i understand OOP i knew that i could go the route of make my own library.

The problem i'm having right now, is that the library is returning an undefined reference. The IDE i'm using is UECIDE with QTcreator on the side to help me with my syntax. The compiler is avr-gcc. The chip is an Arduino Uno. The problem i'm recieving is

> C:...\RCRoomba\_TestPulseV2.cpp.o: In function '\__static\_initialization\_and\_destruction\_0':
> C:...\RCRoomba\_TestPulseV2.ino:5: undefined reference to 'PPMintIn::PPMintIn(int)'
> C:...\RCRoomba\_TestPulseV2.cpp.o: In function 'setup':
> C:...\RCRoomba\_TestPulseV2.ino:9: undefined reference to 'PPMintIn::begin()'
> Failed linking sketch

I tried to define the variables in my h and cpp files but it doesn't seem to be fixing the problem.

Here is the .ino code.
for some reason UECIDE can't see the Pinchange and PPMint libraries

```
#include "arduino.h"
#include "C:\Users\User\Documents\UECIDE\libraries\PinChangeInt\PinChangeInt.h"
#include "C:\Users\User\Documents\UECIDE\libraries\PPMintIn\PPMintIn.h"

PPMintIn CH1(A0);

void setup(){
    Serial.begin(115200);
    CH1.begin();
}

void loop(){
}

```

Here is the .cpp code

```
#include "arduino.h"
#include "ppmintin.h"
#include "PinChangeInt.h"
//defined these
volatile int pwm_value = 0;
volatile int prev_time = 0;
uint8_t latest_interrupted_pin = 0;

PPMintIn::PPMintIn(int pin){
    pinMode(pin, INPUT);\
    digitalWrite(pin, HIGH);
    _pin = pin;
}

void PPMintIn::rising(){
    PPMintIn::latest_interrupted_pin = PCintPort::arduinoPin;
    PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
    PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
}

void PPMintIn::falling(){
    PPMintIn::latest_interrupted_pin=PCintPort::arduinoPin;
    PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
    PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
}

void PPMintIn::begin(){
    PCintPort::attachInterrupt(_pin, &rising, RISING);
}

void PPMintIn::getSignal(){
    return(PPMintIn::pwm_value);
}

```

Here is the .h code

```
#ifndef PPMINTIN_H
#define PPMINTIN_H

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
  #else
  #include "WProgram.h"
#endif
#include "PinChangeInt.h"

class PPMintIn{
public:
    PPMintIn(int pin);
    void begin();
    void getSignal();
    int _pin;
    volatile int pwm_value;
    volatile int prev_time;
    uint8_t latest_interrupted_pin;
private:
    void rising();
    void falling();
};

#endif // PPMINTIN_H

```

here is the full thing in github in case I didn't supply it here. https://github.com/tisaconundrum2/PPMintIn

# Answer
As both Majenko and I tried to explain in Pass a member function pointer to a method of a foreign class (EDB Lib) you can't pass a class member function where a static function is expected.

---

Your error is on:

```
PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);

```

Error:

```
/home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp: In member function ‘void PPMintIn::rising()’:
/home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp:22: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&PPMintIn::rising’

```

---

PCintPort::attachInterrupt expects a `PCIntvoidFuncPtr` variable:

```
int8_t PCintPort::attachInterrupt(uint8_t arduinoPin, PCIntvoidFuncPtr userFunc, int mode)

```

That is:

```
typedef void (*PCIntvoidFuncPtr)(void);

```

That is a static function (not a class function).

However you have it as a class function:

```
class PPMintIn{
public:
    PPMintIn(int pin);
    void begin();
    void getSignal();
    int _pin;
    volatile int pwm_value;
    volatile int prev_time;
    uint8_t latest_interrupted_pin;
private:
    void rising();
    void falling();
};

```

Now you can make `rising` and `falling` static but now they can't access any of the class variables (eg. pwm\_value, prev\_time, latest\_interrupted\_pin).

The whole thing needs a redesign. You could try making PPMintIn a namespace rather than a class.

---

Regarding one of the comments:

Unless your class implements `operator()` this line doesn't make sense:

```
chan1(15);

```

---

*Please copy and paste error messages into the post, don't make people go to Imgur to find a screenshot of some text.*
> 0 votes

---
Tags: arduino-uno, library, compile, avr-gcc
---


# Question
Title: Arduino works bad when powered by 9V battery
At first I am sorry for my bad English.

I am making robot which can do a lot of things...

If I connect arduino on my robot with PC via USB, the robot works properly. If I use external power supply (9V battery) the robot is doing almost nothing.. The diodes are little bit blinking and sometimes dc motors make motion... And thats all. Batteries are charged. Where's the problem?

Everything I want is make into motion dc motors.. With 5V USB it works. With external power supply not (9V battery).

# Answer
I got a fresh 9 V out of a packet and measured it.

```
 9.58 volts

```

Now with a load of 500 mA (which you quite likely would get with a robot) it dropped to:

```
 7.4 volts

```

With a load of 750 mA the voltage dropped to 6.6 V which is below what you are supposed to supply via the power jack.

And that was with a fresh battery, testing for a few seconds.

Those 9 V batteries are just not designed to drive motors.

I suggest a somewhat heavier-duty battery, like 5 x AA batteries, at least for the robot part.
> 1 votes

---
Tags: arduino-mega, power, motor, battery, usb
---


# Question
Title: How to return the value in Arduino function (that can be read by the connected device)?
Right now I have an RC car program for Arduino. The code is like this:

```
void loop() {
  distance = Dist.getDistanceCentimeter();
  if(distance<=5 & distance>1)
  if(Serial.available()) {
    lkf = Serial.read();
  switch(lkf) {
  case 'a':
     forward();
     servoX.write(90);
     lkf=0;
     break;
  }
}

```

I wrote a TCPclient that can order the RC car to move forward by connecting through TCP and sending the message "a" to the Arduino board.

The problem is how to return the distance to the cilent? Is it simply `return distance;` or something like `system.println(distance);`? Thanks for helping.

# Answer
You are using the USB interface, right? So you just use Serial to send data back. For example, this would send the distance every second:

```
unsigned long lastSent;
void loop() {
  distance = Dist.getDistanceCentimeter();
  if (millis () - lastSent >= 1000)  // every second
  {
    lastSent = millis ();
    Serial.println (distance);
  }

  if (distance <= 5 & distance > 1)
  {
    if (Serial.available()) {
      command = Serial.read();
      switch (command) {
        case 'a':
          forward();
          servoX.write(90);
          command = 0;
          break;
      }  // end of switch
    }
  }
}

```
> 1 votes

---
Tags: programming
---