body: Indeed, this is an issue of RAM available. If you do not need 8 bits per piece of data (if you are perhaps willing to reduce image quality, for example), consider compacting your data such that you have multiple piece of data per bit. For example, hex values or BCD (binary coded decimals) could work, depending on the size of each piece of data.


sender: user

message:
Arduino Uno not able to handle 2-dimensional array

<!-- language-all: lang-C++ -->

Now the code I'm writing in Arduino (Using Arduino) uses multiple 2-dimensional arrays. Now when I print some thing using the Serial Monitor it prints it correctly but when I declare and initialize the 2-dimentional array it won't print it.

Code:

    void setup()
    {
      Serial.begin(9600);
      int image_width = 56;
      int image_height = 96;

      int image_result[image_width][image_height];
      for (int i=0; i<image_height; i++) {
        for (int j=0; j<image_width; j++) {
          image_result[j][i] = 5;
        }
      }

      Serial.print("code works");
    }

Now in this case "code works" does not print but when I remove the array declaration and initialization code works is printed. What is the problem?

Do 2 dimensional arrays work differently in Arduino or is it a space issue?

sender: assistant

body:
As others have noted, your array is larger than the available RAM in your Arduino. Others mentioned Flash memory which could be a solution for you. Your Arduino has 32 KB of memory which could hold your array. See the following reference for more info about Flash memory. Keep in mind that Flash and EEPROM have a limited number of write cycles before becoming unreliable.

[Hidden Powers - storing data in Flash and EEPROM][1]

  [1]: http://playground.arduino.cc/Code/EEPROM-Flash


body:
In case the matrix is mostly empty or anyway has values that can be calculated programmatically, [sparse arrays][1] might come to the rescue. It requires memory allocation and hopping, so the access time to individual elements is not deterministic, but you can calculate the worst-case scenario.

  [1]: https://en.wikipedia.org/wiki/Sparse_array


message:
What's the benefits between different interrupts on Arduino

On an Arduino you can have several different interrupt types, two of them being RISING and FALLING. Looking past that RISING is from LOW to HIGH, and FALLING is the opposite, what are the benefits of using one or the other?

To clarify; why would you use a RISING interrupt or a FALLING interrupt?

body:
Imagine that you have the circuit below:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/RFd8S.png)

<!-- End schematic -->

Let's say that you wanted to catch the user pressing the button. The input signal will go from high to low, which is a falling edge. So you would use a FALLING interrupt to catch this event. Easy, right?

Now let's say you wanted to catch a user releasing the button instead. This time the inverse is true, so you want to use a RISING interrupt.

You should note that since these interrupts are edge triggered, the simple circuit below would not be ideal. Without any debouncing, there may be several edges to trigger from, resulting in repeated interrupts. Also, given the analogue nature of the design, we can't be sure that the rise / fall times will be fast enough to trigger the edge interrupt. We can get around this by adding a 100nF capacitor across the switch and following by a Schmitt trigger (which I can't find a symbol for in the circuit editor!).

So to answer your question, you use the interrupt that is correct for the event you are trying to catch. The Arduino MCU implements both edges for completeness and flexibility in your design, so if this interrupt was coming from an external IC you have no control over the design of, you can easily match the interrupt to its behaviour without having to add in an inverter.


body: Suppose you have a pushbutton that connects Arduino pin to the ground. The pin is also pulled up  to VCC (may be internally in Atmega chip, or through external resistor). Now, when the switch is open, Arduino sees HIGH, and when you press the button it sees LOW. If you would like to perform an action when the button is pressed, you would use FALLING interrupt. If you would like to know when the button is released, you would use RISING. There are no general benefits of using one over another.


body: The interrupt will be generated by an external circuit.  In many cases, you have the control over the design of the external circuit, and you can choose whether it will be generating low-to-high edges or high-to-low edges.  But in some cases you don't have the control over the design of the external circuit which generates the interrupt.  Then you have to adapt your firmware code to the interrupt source.


message:
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.

body:
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](https://msdn.microsoft.com/en-us/library/jj610646.aspx) 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](http://www.netduino.com/)

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.


body:
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.


message:
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?

body:
I can highly recommend [these cheap little 433Mhz radios][1].  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.

  [1]: http://smile.amazon.com/gp/product/B00INTI8R2/ref=ox_sc_sfl_title_6


body:
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.


message:
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][1].

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.

  [1]: https://www.arduino.cc/en/ArduinoCertified/IntelGalileo

body:
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.


body:
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.


body:
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.


message:
Arduino Serial.write sending more than 64 bytes

<!-- language-all: lang-C++ -->

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.

body:
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.**


message:
Use all pins As digital I/O

**Increase the number of digital pins**

There are many post that explain how to use more than just the standard pins on the various arduinos but none of them explain the limitations and the proplems properly.

[![enter image description here][1]][1]

Arduino Uno:

**1.You can** use the analog pins

    Pin 14 = Analog in 0
    Pin 15 = Analog in 1
    Pin 16 = Analog in 2
    Pin 17 = Analog in 3
    Pin 18 = Analog in 4
    Pin 19 = Analog in 5

    digitalWrite(14,HIGH);
    or
    digitalWrite(A0,HIGH);

**2.You can't** use both SDA , SCL & A4 , A5 as they are basically the same (18,19).

**3.You can** also use the TX/RX.

> "Don't do it, you break the serial communication..."

> "Never use pins 0 and 1"

> "you can't use the TX/Rx Pins"

**You can... but you need to take precautions. Which ones?**

It should have software serial over USB, right?

Or do i break the USB serial?

Are there internal Chip problems if i use TX/RX?

As i use those TX/RX pins in the code i probably should not use `Serial.print()`?

What happens if i forget to remove `Serial.print()` after uploading the code that use pins 0,1?

How to hardware reset the arduino/bootloader if something goes wrong?

As there are various other Arduino's that use different chips, is the above valid for all Atmel chips?

**So, what shuold i know before using those TX/RX or also maybe the other analog pins?**

> There are cheap shiftregisters, pwm drivers, led drivers, spi, i2c and
> more ic's to expand your I/O

----------

But if there are not to big problems it means that the arduino has 20 I/O pins...

*You could theoretically control:*

    17x3 = 51 = 17 RGB leds (multiplexing, pwm sourcing&sinking);
    14x6 = 84 leds (multiplexing, pwm on 6 rows/colums );
    10x10 = 100 leds (multiplexing, high low);
    20x(20-1) = 380 leds (charlieplexing, high low);
    // yes it would flicker

Correct me if i'm wrong. That means you are able to control 380 "Whatever" using diodes and one arduino.

  [1]: https://i.stack.imgur.com/dVkQU.jpg

body:
The main issue is with pins 0 and 1.

Many pins have multiple functions assigned to them, such as A4 and A5 are also the I2C pins, pins 10/11/12/13 are also the SPI pins, etc.  But pins 0 and 1 are the only multi-function pins that actually have something attached to them on the board.

All the other pins, while being multi-function, have their function defined basically by what you attach to them.  Since the pins 0 and 1 are already attached on the board to the USB interface chip their usage possibilities are somewhat more limited.

* As soon as you enable Serial in your sketch (`Serial.begin()`) those two pins can no longer be reliably used for digital IO.

That means that you can *either* use the hardware serial port *or* you can use the pins for digital IO, but not both.

* Devices connected to pins 0 and 1 can interfere with the serial connection

That includes uploading of sketches.  You have serial data coming in from the PC while the same pins are being affected by other things connected to them.  The most common one is things like GPS modules which connect to those pins and constantly send serial data.  That serial data will conflict with the PC's serial data and neither will arrive right.

* How do you upload sketches if the serial is being interfered with by your sketch? How do you "reset" the board?

You don't.  It's not your sketch that's interfering with the serial, it's what is physically connected to those two IO pins that are interfering.  Just disconnect those two pins from whatever is connected and you will be able to upload sketches again.  Many shields now are starting to add a small switch on them to disconnect those pins so you can upload sketches without unplugging the shield.  You can also use the same trick with other devices you wire up to those pins - add a double-pole-single-throw or double-pole-double-throw (and not use one position) to easily isolate both pins from the rest of your hardware when you need to.

* Does this affect all Arduino boards?

No, only those that use a USB to Serial bridge chip - that's things like the Uno, Due, Mega, etc.  Boards that have a direct USB connection don't use the TX and RX pins for uploading sketches - they use the dedicated USB D+ and D- pins.  That's boards like the Leonardo, some of the smaller (mini? micro? I forget which) boards, etc.


body:
> 20x(20-1) = 380 leds (charlieplexing, high low);
> Correct me if i'm wrong. That means you are able to control 380 "Whatever" using diodes and one Arduino.

First, the figure of 380 is correct for 20 pins (202 - 20) however pins 0 and 1 are connected to pull-up resistors on the Atmega16U2, so they are never really at 0V. If you load a blank sketch, you will measure 5 V on pins 0 and 1.

Second, you can't drive 380 "whatevers" you can drive 380 **LEDs** via Charlieplexing. The property of the LED, that current only flows one way through it, is important to the way it works.

Related question <https://arduino.stackexchange.com/questions/117/is-there-a-way-to-have-more-than-14-output-pins-on-arduino>


body:
I can't comment due to insufficient reputation but I want to point out that the OP pinout has at least one pin wrong!

**PB6 should be PB5**

I spent quite a lot of time trying to figure out why I couldn't see SCK on scope (SPI bus). I was working low level, not with the IDE.

As this is the first picture that comes up when googling I wanted to avoid the same trouble to others...


message:
Increasing the numbers of I/O pins on Arduino Uno

I want to make a game of [Tic-tac-toe][1] 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?

  [1]: https://en.wikipedia.org/wiki/Tic-tac-toe

body:
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 Matrix Keypad how-to][1]*

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.

* *[How to Multiplex an LED Grid...][2]* (YouTube)
* *[Charlieplex Library for Arduino][3]*

  [1]: http://playground.arduino.cc/Main/KeypadTutorial
  [2]: https://www.youtube.com/watch?v=MmCGDJ90Qt4
  [3]: http://playground.arduino.cc/Code/Charlieplex


body:
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.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/cxlSz.png


message:
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:

<!-- language: c -->

    #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

body:
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);


message:
Use AS3935 with I2C?

Has someone experience with interfacing the AS3935 lightning sensor using I2C? I found a library but it only works with SPI as far as I can tell. I really don't want to give up 4 pins for SPI as I need those for other things. I2C would be great as I use a couple more sensors with I2C so no extra pins only for AS3935.

body:
Just use these functions to read/write AS3935 registers, replacing the SPI ones (_devAddr is the device address, usually 0x03) :

    // read/write functions for I2C mode
    uint8_t AS3935::_i2cRead(uint8_t addr)
    {
     // send register number
     Wire.beginTransmission(_devAddr);
     Wire.write(addr);
     Wire.endTransmission(false); // <<<--- THE 'false' here is mandatory!

     // request register data
     Wire.requestFrom(_devAddr, (uint8_t)1);

     // read data
     return Wire.read();
    }

    void AS3935::_i2cWrite(uint8_t addr, uint8_t data)
    {
     Wire.beginTransmission(_devAddr);
     Wire.write(addr);
     Wire.write(data);
     Wire.endTransmission();
    }

The "trick" is to use Wire.endTransmission(false) inside the read routine; this avoid to send the stop bit, which is mandatory for AS3935 read operation.


message:
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.

body:
> 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](http://reprap.org/) - a 3D printer using an Atmega1280 as the controller. As it says [here](http://reprap.org/wiki/Generation_2_Electronics):

> 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.


message:
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?

body:
See <https://arduino.stackexchange.com/questions/14179/softwareserial-write-to-return-read-in-serial-monitor/14180#14180> - 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.


message:
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 :)

body:
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.


message:
How to wire up 4-digit 7-segment display?

I have an **Arduino Mega** and the **CL5642BH**, a **4-digit 7-segment display.** I found very helpful code [here][1], but I don't understand how to wire it up on the breadboard.

The display has 12 pins: 6 on the top and 6 on the bottom. First I guess I need to find out which one is GND.

Then (see the link) there is this code:

    int digit1 = 11; //PWM Display pin 1
    int digit2 = 10; //PWM Display pin 2
    int digit3 = 9; //PWM Display pin 6
    int digit4 = 6; //PWM Display pin 8

    int segA = A1; //Display pin 14
    int segB = 3; //Display pin 16
    int segC = 4; //Display pin 13
    int segD = 5; //Display pin 3
    int segE = A0; //Display pin 5
    int segF = 7; //Display pin 11
    int segG = 8; //Display pin 15

It's 11 pins, that's the correct amount so far. But **how do I wire it up?** The pins on the display are in no way labeled.

*Note: I'm a software developer, but as far as electronics go, I'm still a beginner.*

  [1]: http://www.hobbytronics.co.uk/arduino-4digit-7segment

body: As page 2 of the datasheet shows, there are 5 anode pins (4 digit and 1 aux) and 8 cathode pins (7 segments and 1 DP). Connect the digit lines to the digit anodes and the segment lines to resistors connected to the segment cathodes. The location of pin 1 is shown on the top right of page 2, and as always they go counter clockwise from there. Segments are lit by putting the anode high and the cathode low.


body:
The first thing you do is ask Google for a datasheet.  It tells you: http://www.robotshop.com/media/files/pdf/datasheet-com-09483.pdf

Then you can read the datasheet and find the pin diagram:

[![enter image description here][1]][1]

That tells you that it is a *Common Anode* LED display - which means that for each digit all the *Anodes* (positive pins) of the LEDs are wired together.

Further, all the *cathode* (negative) pins of the LEDs for the same segments across the digits are connected (that is the cathode for segment A on digit 1 is connected to the cathode for segment A on digit 2, digit 3 and digit 4, etc).

From that you can then infer that you need to provide current for each digit in turn through its common anode pin, and sink current from the segments you want to have lit for the digit that is currently having its current sourced.

The diagram also shows you which pin on the display is for what function - the common anodes are pins 9, 10, 12 and 13, with pin 11 the common anode for the extra dots.

The datasheet also tells you which pin is pin 1 - in this case the one in the bottom left when you have the display facing you and the numbers the right way up.  The pins count anti-clockwise from there, so 2 is to its right and 13 is above it.

[![enter image description here][2]][2]

By the sounds of it though you may not have the same display as in that datasheet.  If your display lacks the extra dots then it may not have the LEDs on pin 11, and pin 12-13 may be moved down one, so you have 4 commons on 9, 10, 11 and 12 with no pin 13.

So the four digit select pins in your program are wired to pins 9, 10, 12 and 13, and the segment select pins connect to pins 1, 2, 3, 4, 5, 6, and 7.  Don't forget the resistors on all the segment pins to limit the LED current or you will damage the Arduino.

You can do some manual testing of the display by using two wires and a resistor (say 1KΩ).  Connect the resistor to +5V, and one wire to the other end of the resistor.  The other wire you connect to ground.

You then take the loose ends of the wires and try probing pins.  Start with the 5V wire touching pin 9 and connect the other one in turn to pins 1-8 to see if the first digit's segments light up.  Repeat with the 5V wire on pins 10-12.

Edit:

If this (http://mklec.com/displays/7-segment-4-digit-12-pin-common-anode-display) is indeed the same display as yours you can ignore the numbers I mention above and work from the pin numbers on that page.  The same principle applies though, just the pin numberings are different.

  [1]: https://i.stack.imgur.com/TnON4.png
  [2]: https://i.stack.imgur.com/16F42.png


body:
From the datasheet found by Ignacio Vazquez-Abrams:

[![7-segment display][1]][1]

Now one segment will light up if there is a positive (eg. 5 V) on the anode, and a negative (eg. ground) on the cathode. You need a resistor (eg. 330 ohm) to protect the LED and the output pin.

---

Hopefully it is clear from the original question which Arduino pins go to which LED pins.

---

Then the code which I presume you found will have to multiplex the display. That is, it will ground (send LOW) to the appropriate cathode pins for the number of segments it needs to light up (all of them, for example, for the number 8, except the decimal point). And then it will raise to 5 V (send HIGH) to DIG 1. That will make some segments on digit 1 light up. Then it repeats that for digits 2 to 4, fast enough that they will all appear to be on at once.

  [1]: https://i.stack.imgur.com/RUUEq.png


body:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/vJzZu.png

Apply the pin 1, 2, 3 with 5v from Audrino passing through the resistors. Apply low voltage to pin-a to light up the led, so on so forth.
You can use the multi-meter to confirm the common pins and led pin.
For example touch the pin1 with (+) and pin-a with (-) of the multimeter.
If the pins are correct, led pin-a will light up.

Picture Reference:http://www.circuitstoday.com/voltmeter-using-arduino


message:
433MHz transmitter and receiver pair doesnt work

I have a pair of 433 MHz transmitter and receiver:

[![Transmitter / receiver][1]][1]

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:

<!-- language-all: lang-C++ -->

    #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);
    }

  [1]: https://i.stack.imgur.com/xXjyL.jpg

body:
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.


body:
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][1] that is designed for Arduino and the type of transmitters and receivers you are using.

  [1]: http://www.airspayce.com/mikem/arduino/VirtualWire.pdf


body:
See [this post about a radio-controlled car](http://www.gammon.com.au/forum/?id=11506).

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

[![Radio receiver][1]][1]

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:

[![Radio receiver software serial][2]][2]

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

[![Op-amp buffer][3]][3]

---

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

  [1]: https://i.stack.imgur.com/eJWAd.jpg
  [2]: https://i.stack.imgur.com/7aJQe.jpg
  [3]: https://i.stack.imgur.com/qBQiR.png


message:
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.

body:
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).


message:
Arduino nano getting powered through analog input?

I noticed something today. I am powering the Arduino Nano from a battery and a 5v step up converter. That works just fine and I'm getting a stable 5v output. I have a second cable coming out from the battery which plugs right into analog input A0 set as input so I can measure the battery voltage. However when I disconnect the battery from the usb plug and leave the voltage sensing cable connected to the analog input the power led stays on. I want it to shut down and be disconnected from the power source and have the voltage sensing cable still connected.
How can I fix this?

body:
Power is flowing from the analog pin, through the internal clamping diodes, to the Vcc line. Those diodes are however not designed to handle that much current, so don't continue doing this.

Either also disconnect the ground wire from the battery, or simply add a resistor between the battery and the analog pin. Something like 10k. That way less than a mA of current will be clamped, and the arduino will stay off.


body:
This addresses a subset of your question which was covered in your added comment-question. I've addressed use of a 20V full scale input range to make the answer more general. The results would be "even better" for your 5V input case. Note that is Vin ~= 5V you would want a measurenet range somewhat above 5V max so that you can handle typical voltage variations.

> Do you know any transistors/FETs with a very low voltage drop which I need for switching off a sensor?

If you used a say 10k resistor in the upper leg of a voltage divider and added a MOSFET switch with an on resistance (Rdson) of 2 Ohms (a terrible spec) between Vin and the divider then the error introduced would be about 2/10k = 1:5000. If measuring a say 12V  battery and using a Vinmax voltage of 20V the error in voltage measurement would be in the order of 20V/5000 = 4 mV. If using an Arduino Nano with a 10 but ADC the resolution (not accuracy) is 1 in 2^10 = 1:1024 or 20V/1024  = about 19 mV for a 20V input range. ie the resistor introduces an error of about 1/5th of a bit of available measuring accuracy.
Worse (or better) - if you use 1% resistors they will swamp errors caused by ADC resolution. Even use of say 0.1% resistors or calibration is liable to produce a result where ADC resolution is not the main limiting factor.

Even with no resistive divider, getting accuracies that are doinated by the 1:1024 ADC resolution and not other factors takes care and effort. At 5V in ax ADC resolution of 1:1024 means that a variation of 1 part in 2048 could cause an erroneous reading. Input offset voltages, thermal effects, board and connector resistances and ground voltage dropsm and offsets can easily provide greater error magnitufes.

Test: Take a working design. Set meter to lowest voltage range such that 1 mV can easily be seen. (Ideally 200 mV range. 2V range marginally OK). Measure ground voltages between various "ground" points at various locations in the system. Differences ofm mV to 10's of mV can often be found. Differences are poptentially higher if power current are present - say 10's of mA or more.


message:
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.

body:
> 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.


message:
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?**

body: 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.


body:
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.


message:
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][1] 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()
    {
    }

  [1]: http://blog.brauingenieur.de/2014/01/20/extended-database-library-using-an-sd-card/

body:
Can you post a  [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)? 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?


body:
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...


message:
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 ?

body:
`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.)


message:
ESP8266 as I2C client

I've got an ESP8266 that takes instructions from a web page and sets a series of NeoPixels to flash in different sequences.

I noticed that when the Wi-Fi got data and parsed it, my LEDs would "stutter" as the processor ignored them for a moment while processing the incoming instructions.

So I added a 2nd ESP8266. This one just handles the LEDs. So the 1st ESP gets the Wi-Fi data and parses it. It then sends an interrupt to the 2nd ESP which breaks out of the LED display loop, checks the interrupt pin for HIGH or LOW and sets the LEDS based on HIGH/LOW.

However, I would like to send more data from the Wi-Fi ESP to the LED driving ESP. e.g. Colour data, transition speed, rotation direction etc. All of these settings I can send to the ESP from a web page.

I thought I2C (the wire library) would help but all comments seem to say that the ESP8266 cannot act as a slave so I can't send to it.

So it appears I'm left with Serial comms (the interrupt is over by the time comm start because I realize Serial does not work in an interrupt).

So my questions are:

 - Am I right that I2C will not work?

 - If I am wrong does anyone have a working end to end example?

 - If I am right is there an approved way to do ESP to ESP serial comms?

body:
I assume that you are using the Arduino core for the ESP8266 (https://github.com/esp8266/Arduino)

> Am I right that ic2 will not work?

I am not certain, but I get the same impression as you.  It seems that the Expressif SDK only supports master mode.

> If I am right is there an approved way to do ESP to ESP serial comms.

There is no "approved way", but there are many ways you can do it.  A direct serial link will give you a simple pipe of data - what you put in at one end comes out the other.  It's up to you to decide how you format and interpret that data.

My ICSC library may help you with that - I use it to connect an ESP8266 to an BeagleBone Black through serial: https://github.com/MajenkoLibraries/ICSC


body:
The issue with the ESP8266 is that it is multitasking, and only 80% of the CPU time is available to developers. This manifests as an outage of 100-200us every 500ms or so, which rather complicates all sorts of software serial interfaces, such as I2C, SPI and UART. As a bus master the ESP8266 hides these issues as it is responsible for the bus clock, but as a bus slave it needs to halt data transfer for the duration of these random events.

A typical solution for this inter-CPU issue is to provide an external RAM cache to act as a mailbox, where each CPU will periodically check to see if any actions are outstanding and leave any requested data.

Has anyone explored this option for the Arduino to ESP8266 interface?


body:
> I am not certain, but I get the same impression as you.
> It seems that the Expressif SDK only supports master mode.

Sorry no.
Espressif SDK supports Slave Mode too.
official the Master works with 50 kHz (CPU 80MHz), and  100 kHz in technical referenz  and unofficial in my test with !1.2MHz you must switch then to the 160 MHz CPU and you must work for delays with
asm ("nop") 12.5 ns at 80MHz and 6.25 ns at 160 MHz
then you can toggle the pins at 80 MHz with 700 kHz and with 160 MHz with 1400 kHz. because there are instruction to the gpio ( toggle output low, "opendrain" clear output with pullup high ) it will be a netto rate of
620 kHz, and 1260 kHz.

[![a stable 120 kHz is done][1]][1]

best wishes
rudi ;-)

[![I2C Slave ESP8266 ][2]][2]

  [1]: https://i.stack.imgur.com/NZnJQ.png
  [2]: https://i.stack.imgur.com/BoZVs.png


message:
Two sensors on one input

I got this question from my teacher the other day and I can't figure it out:

> If you have two sensors from two different outputs but want them to go into one input, what do you need, and how can you read the input?

[![enter image description here][1]][1]

In short, the project includes an Arduino Uno with two ultrasonic sensors.

  [1]: https://i.stack.imgur.com/Xb7N2.jpg

body:
There are two basic solutions to your problem, an active one and a passive one, and which is best (or will even work) depends on the rest of your setup.

The active solution requires a device called a *multiplexer*.  This is basically a switch and it selects one of its inputs to route through to its output, so it can be used to connect your input pin to the output of one of the sensors.  It requires an extra IO pin, though, so is pretty pointless as you could just use that IO pin as an input from the second sensor.  It does mean, though, that both sensors can be active at once and you just select one to read the output from.

The passive solution is called *open drain* or *open collector* (if you are using TTL not CMOS terminology).  This means you convert each of the outputs of the sensors into a switch using a transistor (NPN BJT or N-Channel MOSFET) to connect your input pin to ground.  When then transistors are off the input pin is pulled up through a pullup resistor (could be internal or external to the IO pin).  When one sensor's output activates it turns on the transistor which then pulls the input pin low.  This means that you can only have one sensor active at a time, so they have to be triggered by separate output pins.

[![enter image description here][1]][1]

Open Drain is how things like I2C support multiple devices on the same bus without any voltage conflicts.

  [1]: https://i.stack.imgur.com/z7pDQ.png


body:
This solution only actually uses one pin, but only works with simple things like push buttons (which are either open, or closed).

Connect a (different) resistor in series (end-to-end) with each switch. Connect the loose end of each resistor together to +5V. Connect the loose end of those two switches together, then via another resistor to ground. Where the two switches meet, connect them to an analog pin on your Arduino.

For example, you might use a 20k resistor with button A, and a 10k resistor with button B, and a 10k resistor connected to ground. They should be pretty close to the same value, and at least 1k each.

Use the ReadAnalogVoltage sketch to measure the voltage with different combinations of button presses (no button pressed, A, B, A+B), then, in your final sketch, you can compare the value read with the values in this table - pick the closest one, because actual readings may vary slightly. For the resistors above, you should get about: (no button = 0v; A=1.7v, B=2.5v, both 3v). Sort these numerically (which in this case they already are), and work out the values exactly between each pair (up to 0.85 is closest to 0=> no button; else up to 2.1=> button A; else up to 2.75 is closest to B; otherwise, both are pressed.

The circuit described looks like this:

[![Switch circuit][1]][1]

The wire leading off to the right goes to the analog pin on the Arduino. Switch A is on the left.

The results can be used either in a table, with a loop, or in an if/else if statement (I used this technique on a 12-key keypad, so the list was a lot longer).

  [1]: https://i.stack.imgur.com/LjsPo.png

Read up about voltage dividers https://learn.sparkfun.com/tutorials/voltage-dividers and, for both buttons being pressed at the same time, resistors in parallel https://learn.sparkfun.com/tutorials/series-and-parallel-circuits


body:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/xhtgM.png

Try the above logic use a 555 timer with  C1: 10uF, R2: 300k and R1: 30k for 1.1 sec switching time,now for approx every one second data from USS1 goes to SIN(Arduino IN) when the timer OUT is high and  similarly when timer OUT is LOW signal from USS2 goes to SIN(Arduino),,,

But you will not be able to know from which sensor is the output coming.

If you would like to know from which sensor the output is coming you can just add one INVERTER to one of the branch so so both the sensors will give different states i.e one will return HIGH and other will return LOW

hope this helps

Edited:Please note 555 timer design part is not complete ,,i am just giving an idea :)


body:
> If you have two sensors from two different outputs but want them to go
> into one input, what do you need, and how can you read the input?

If you want your teacher lose his mind answer his question with this:

What I need? :)

 - A wire

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/QhnyU.jpg

The solution is to use one trig for both ultrasonic sensor and two echos.

or one echo and two triggers.

ultrasonic sensor sends the pulse > pulse back > now echo pin is connected to second sensors trig > the Second Ultrasonic sensor sends the pulse then starts listening. When the second ultrasonic echo back, it sends to other Arduino pin, reverse it if you want it on one input pin :)

    #define trigPin 6
    #define echoPin 4
    #define echoPin2 7

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
       pinMode(echoPin2, INPUT);
    }

    void loop() {
      long duration, distance, distance2;
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(20);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;
      duration = duration + pulseIn(echoPin2, HIGH);
      distance2 = (duration/2) / 29.1;
      if (distance >= 200 || distance <= 0){
        Serial.println("Out of range");
      }
      else {
        Serial.print(distance);
        Serial.println("cm");
           Serial.print(distance2);
        Serial.println(" cm");
            Serial.println("HHH");
      }
      delay(500);
    }

that's it.


body: A SPDT switch would fit nicely in your diagram where the question mark is.


body:
I ran into the same question, except I wanted to put 8 of the HC-SR04 sensors on pro-mini.

I used an I2C pin expander for the triggers, and an octal OR/NOR chip to multiplex the return.

Library, examples and pictures

https://github.com/arielnh56/SonarI2C
http://redhunter.com/blog/2016/04/28/sonari2c-multiple-hc-sr04-sensors-on-arduino-i2c/


body: The question is two Ultrasonic data get input on one.  Its simple.  You just need two IDs.  Creat a IDs of each sensors.  You can use I2C bus too.  You need to hub who keep the two input in raw.  And than digitally write with address and than do codding for read the data.  Howz my idea guys?


body:
The OP does not specify whether the focus is on hardware or software.

So I will presume that what the professor might looking for is a solution using minimal circuitry; as close to the diagram as possible.  Thus, the solution would be implemented in software.

Given all that, I'd propose that the trigger signal be sent out on sensor 1, and the reflection measured at the receiving pin.

It is time-gated (the time for the sensor to react to an object at maximum range).  If detected, then set a variable saving the distance measured on sensor 1.

Then the same could be sent from the second sensor's trigger pin.  And if there is a reflection within the time-gate then that can be recorded in another variable.

It would require creating two instances of the ultrasonic sensor, and they would just happen to share the same receive pulse pin.


message:
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

[![example layout][1]][1]

  [1]: https://i.stack.imgur.com/4VmOx.png

body:
According to the [schematics][1], the Pro Mini uses the [MIC5205][2], 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][3] 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]: https://learn.sparkfun.com/tutorials/using-the-arduino-pro-mini-33v
  [2]: http://www.micrel.com/_PDF/mic5205.pdf
  [3]: http://www.ebay.com/itm/LM2596S-ADJ-Power-Module-DC-DC-Buck-Regulator-3A-Adjustable-5V-12V-24V-/171819436954?hash=item28013c8b9a


message:
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

body:
<!-- language-all: lang-C++ -->

As both Majenko and I tried to explain in <https://arduino.stackexchange.com/questions/14480/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:

<!-- language-all: lang-none -->

    /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’

---

<!-- language-all: lang-C++ -->

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:

[![Error message][1]][1]

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.*

  [1]: https://i.stack.imgur.com/Sm1q3.png


message:
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

body:
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.


message:
Connecting to Arduino Ethernet Shield

How do I figure out how to connect to my arduino using ethernet shield?

It prints the IP in the serial monitor, but it doesn't work, and adding the port doesn't make a difference.

The client example works, so it's not broken or anything.

I'm using `Arduino 1.6.5` IDE on a `Mega 2560`. I'm trying to run the `Examples/Ethernet/WebServer` example.

body:
Your question is kind of trivial, but from what I understood you're typing the IP address (that the Arduino displays on the serial monitor)  into your browser.

First, make sure you connect your Ethernet shield to your router using an ethernet cable. (Now it's connected locally...)

Second, even if you type in your Arduino's IP address into the browser, the browser will return nothing because the Arduino simply has nothing to display, and hasn't been programmed to accept requests.

To actually have the Arduino display something you can try the Webserver example sketch or you can follow this great [Tutorial][1] that I found very useful for beginners.

BTW ports are only used to expose your Arduino to the Internet, in other words if you don't portforward to your Arduino, your Arduino won't be able to get requests from outside your local network (Wi-Fi,Ethernet).

  [1]: http://startingelectronics.org/tutorials/arduino/ethernet-shield-web-server-tutorial/


message:
Buzzer - Does the voltage change with the frequency?

So I have this project where the component "buzzer" is implementet. I was wondering if the voltage is changing along the change of frequency given to the buzzer?

Note that the project just says "buzzer" - not any more details.

Project: http://www.instructables.com/id/Arduino-Distance-Detector-with-a-Buzzer-and-LEDs/?ALLSTEPS

body:
No, the frequency of the "buzzer" has no relationship to the voltage.

The *duty cycle* of the generated tone is proportional to the *average voltage* though.  Typically the duty cycle is 50% - that is it's turned on for half the time, and turned off the other half the time, to make a square wave.  This means that the *average* voltage is 50% of the supply voltage.

If you were to low-pass filter the signal (say through an RC filter as many people do to create a crude DAC) you would end up with a voltage around 2.5V.

Changing the frequency doesn't change the duty cycle, it only changes the audio pitch.

The only caveat to that is that if the buzzer draws more current that the IO pin (or the power supply) can source then it may cause the voltage on that IO pin to *droop*.  That has nothing to do with the frequency though and it would droop just the same at all frequencies.  Basically the IO pin has a small resistance to Vcc through the MOSFET that drives it internally - the higher the current the more voltage is dropped across that resistance, and the lower your resultant output voltage.  Draw too much current and the heat dissipated by that MOSFET's resistance becomes too great and damages the chip.


message:
UltraSonic sensor in rain?

I am onto a simple project with Arduino, SR04 and a buzzer for "Car reverse parking assistance". The aim here is to make a buzz when the car gets too close to the objects.

I was thinking what if it's raining when a person is driving (assuming I somehow achieved to water proof the sensor) - will the buzzer make continuous sounds?

Is there any alternative solution for ultrasonic sensors?

body:
> will the buzzer make continuous sounds

If you mean the sensor will detect the rain drops in the air
Nop it's tiny to read it in the air
But if there is drops on the sensor your sensor will not gives you the right reading

There is a water proof ultrasonic sensors available.

I am working on water level devices, after long path of searching in different ultrasonic sensors and after I tried a lot of method like using water proof Cloth, I found the best way is using water proof sensors PLUS water proof cloth.

water proof sensors work perfectly in high humidity but at the same time if there is a water drop on the sensor the reading will be different, and for that some cars manufacturers used not only one sensor, to avoid the errors. and calculate the differences.

[![enter image description here][1]][1]

The left car used old technology with separate sensors, but that's make errors the only good thing was to detect more things, in the next generation they mix them together.

water proof cloth will make the water drops not stuck at the sensor, but you will need to replace it every 5-6 months. "in your case because the sun will destroy the cloth" in my case and because my sensor inside tanks that's will least more.

I tried to spray the sensor with a different material to make my sensor not catch any water drops, it dose not work too.

And to make my cheap sensor water proof, I tried to use ceramic layers, and that's not work too, they use it with ultrasonic fog maker, these layers not work with cheap ultrasonic sensors, it's need a lot of power to vibrate it and different frequency. and of course you need to replace the layers "depending on the environment"

If you find ultrasonic car sensor with special material for water drops just let me know, I am searching on that too.

**NOTE** These days car manufacturer use different ways, in the past the cover was vibrate itself and made from aluminum, now they cover it and make different filters to ignore the plastic cover, How?! maybe it's different plastic or material maybe they find away to vibrate the plastic! sorry I could not find the secret.

  [1]: https://i.stack.imgur.com/MF7Cp.jpg


body: It would probably be easier to use an IR distance sensor.  That would also be easier to waterproof.


body: Just a thought, a lot of cars use them, why not try your local salvage yard you may be able to get them on the cheap.


message:
Enabling pins of Arduino Due with direct port manipulation

I want to enable pin 13 on my SAM3X8E using direct port manipulation. On this chip the pin is bit 27 in port B, so I used `PIOB->PIO_PER = 1<<27;` to enable this pin, but it doesn't work. This pin keeps at 3.08V, the default value of non-initialized pins.

Here's my complete code:

    #include <asf.h>

    int main (void) {
      // Insert system clock initialization code here (sysclk_init()).
   board_init();
   sysclk_init();
   delay_init(sysclk_get_cpu_hz());
   PIOB->PIO_PER = 1<<27;
   PIOB->PIO_OER = 1<<27;
   while(1) {
        REG_PIOB_ODSR = 1<<27;
  delay_ms(1000);
  REG_PIOB_ODSR = 0<<27;
  delay_ms(1000);
   }
    }

Can anyone tell me how I can get this to work?

body:
I suggest the following test:  Use `REG_PIOB_SODR = 1<<27;` to set the bit, and  `REG_PIOB_CODR = 1<<27;` to clear it.  If that works ok, see about enabling synchronous data output via the port's PIO_OWSR register.  (If it doesn't work ok, perhaps review section 31.6, “I/O Lines Programming Example”, on page 629 of Atmel document 11057, the Cortex datasheet.)

Section 31.5.5, “Synchronous Data Output”, on page 623 says in part:
>After reset, the synchronous data output is disabled on all the I/O lines as PIO_OWSR resets at 0x0.

I imagine that writes to REG_PIOB_SODR and  REG_PIOB_CODR should have effect after you enabled output by setting bits in PIOB->PIO_PER and PIOB->PIO_OER, which you did.  However, with the bit in PIO_OWSR being clear, synchronous data output isn't available, so writes to REG_PIOB_ODSR have no effect.


body:
        #define Led_ON  REG_PIOB_ODSR |= 0x8000000
        #define Led_OFF REG_PIOB_ODSR &= ~0x8000000
        //for Arduino Due
        PIOB->PIO_PER |= 0x8000000;//led
        PIOB->PIO_OER |= 0x8000000;//led
And then call Led_ON and Led_OFF


message:
Problem with codebender project not compiling

I have written a codebender project which returns this error:

    Oops! Looks like there was a serious issue with your project.

    If you are not sure what could be wrong please contact us

    /mnt/tmp/compiler.amxHJ9/files/Many Games.o: In function `gamesMaster::gamesMaster()':
    Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xa): undefined reference to `vtable for gamesMaster'
    Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xc): undefined reference to `vtable for gamesMaster'

What does it mean by `vtable`?

The code uses basic classes and inheritance.

The program is designed to select and play the game of your choice.  I have only programmed the basic structure.

Class `games` contains a ref to the class `gamesMaster`.

Class `gamesMaster` contains a ref to `simpleTimer`.

Classes `playHiLow` and `playSimon` are children of `gamesMaster`.

Class `games` handles and input and outputs, `win` and `lose` control and keeps track of lives.

Class `gamesMaster` handles the `simpleTimer`, displays a new round, checks for the correct answer, and checks if game has finished successfully.

The `main()` function runs a routine in the `games` class.

The code is listed here: <https://codebender.cc/sketch:144869>

    class simpleTimer
    {
    private:
     unsigned long _previousMillis;
     unsigned long _interval;

    public:
     simpleTimer()
     {

     }
     void start(float mins)
     {
      _interval = (unsigned long) (mins * 60 * 1000);
      _previousMillis = millis();
     }
     bool stillRunning()
     {
      return (millis() - _previousMillis < _interval);
     }
    };

    class gamesMaster
    {
    public:
     unsigned short lives;
     gamesMaster()
     {
      timeOutTimer = new simpleTimer();
      gameTimer = new simpleTimer();
      gameTimer->start(1.5);
      lives = 5;
     }
     void right()
     {
      Serial.println("Correct");
     }
     void wrong()
     {
      Serial.println("Wrong");
     }
     void winGame()
     {
      Serial.println("**********");
      Serial.println("* WINNER *");
      Serial.println("**********");
     }
     void loseGame()
     {
      Serial.println("\\ /          \\ /");
      Serial.println(" X    LOST    X");
      Serial.println("/ \\          / \\");
     }
     void startTimeOut(float mins)
     {
      timeOutTimer->start(mins);
     }
     bool notTimedOut()
     {
      return timeOutTimer->stillRunning();
     }
     bool gameTimerOver()
     {
      return !gameTimer->stillRunning();
     }
     simpleTimer *timeOutTimer;
     simpleTimer *gameTimer;

     virtual void setupForNewRound(void);
     virtual bool checkAnswer(unsigned short);
     virtual bool reachedEnd(void);
    };

    class gameHiLow: public gamesMaster
    {
    public:
     gameHiLow() : gamesMaster() {}
     void setupForNewRound()
     {
      Serial.println("  ->(HiLow) New round");
     }
     bool checkAnswer(unsigned short answer)
     {
      Serial.println("  ->(HiLow) Correct Answer");
      return HIGH;
     }
     bool reachedEnd()
     {
      Serial.println("  ->(HiLow) End of game");
      return HIGH;
     }
    };

    class gameSimon: public gamesMaster
    {
    public:
     gameSimon() : gamesMaster() {}
     void setupForNewRound()
     {
      Serial.println("  ->(Simon) New round");
     }
     bool checkAnswer(unsigned short answer)
     {
      Serial.println("  ->(Simon) Correct Answer");
      return HIGH;
     }
     bool reachedEnd()
     {
      Serial.println("  ->(Simon) End of game");
      return HIGH;
     }
    };

    class games
    {
    private:
     unsigned short _gameToPlay;
     unsigned short _levelToPlay;
     gamesMaster *myGame;
     unsigned short _getAnswer()
     {
      if (Serial.available() > 0)
      {
       int inByte = Serial.read();
       Serial.println("  ->(games) Decode Answer");

       switch (inByte)
       {
        case '<':
         return 1;
         break;
        case '>':
         return 2;
         break;
       }

      }
      return 0;

     }
     bool _respond()
     {
      unsigned short answer;
      while(myGame->notTimedOut())
      {
       if((answer = _getAnswer()) != 0)
       {
        if(myGame->checkAnswer(answer) == HIGH) return HIGH;
       }
      }
      return LOW;
     }
    public:
     games(unsigned short gameToPlay, unsigned short levelToPlay)
     {
      _gameToPlay = gameToPlay;
      _levelToPlay = levelToPlay;
      switch(_gameToPlay)
      {
       case 1:
        myGame = new gameHiLow();
        Serial.println(" ->(game) play Higher or Lower Game");
        break;
       case 2:
        myGame = new gameSimon();
        Serial.println(" ->(game) play Simon Game");
        break;
      }
     }
     void play()
     {
      unsigned short answer;
      while(!myGame->gameTimerOver())
      {
       myGame->setupForNewRound();
       myGame->startTimeOut(.5);
       if(_respond() == HIGH)
       {
        myGame->right();
        if(myGame->reachedEnd())
        {
         myGame->winGame();
         return;
        }
       }
       else
       {
        myGame->wrong();
        if(--myGame->lives <= 0)
        {
         myGame->loseGame();
         return;
        }
       }
      }
      myGame->loseGame();
     }
    };

    //////////////////////////////////////////////////////////////////////////////////
    games *game;

    void setup()
    {
     Serial.begin(9600);
     unsigned short gameToPlay = 1;
     unsigned short levelToPlay = 1;
     game = new games(gameToPlay, levelToPlay);
    }

    void loop()
    {
     Serial.println("Let the games begin");
     game->play();
     Serial.println("Program Complete");
     delay(5000);
     exit(0);
    }

body:
As discussed here

https://stackoverflow.com/questions/3065154/undefined-reference-to-vtable

declare these functions pure virtual:

    virtual void setupForNewRound(void) = 0;
    virtual bool checkAnswer(unsigned short) = 0;
    virtual bool reachedEnd(void) = 0;


body:
I agree with @GeryOshlike.  But that's not the only option.

Yes, you can make them *pure virtual*:

    virtual void setupForNewRound(void) = 0;
    virtual bool checkAnswer(unsigned short) = 0;
    virtual bool reachedEnd(void) = 0;

Or you can make them virtual with a default function:

    virtual void setupForNewRound(void) { }
    virtual bool checkAnswer(unsigned short) { return false; }
    virtual bool reachedEnd(void) { return false; }

Pure virtual will complain when you compile if you haven't implemented those functions in your child class.  By providing a default function body it will not complain if you haven't implemented it, and will just use the default body.

If it's a function which you know will always have to be implemented at the child level (will always be different) then go the pure virtual route.  If it's a function that will be the same in a number of children but differ in only a few, then providing the default body and overriding with different ones when needed is the better way to go.


message:
Atmega328 board output voltage

I'm thinking about making my own "arduino" low power board but I have a question about the atmega328. Is the output voltage on the pins always 5v or it depends on the input voltage I gave to the atmega?

Thanks in advance.

body:
It depends on the input voltage you give it.  If you run the ATMega328p at 3.3V then you get 3.3V out.  If you run it at 5V you get 5V out.

A word of caution about running at lower voltages:  The chip can't run as fast when it has a lower supply voltage - that's why you will see the 3.3V Arduino boards running at 8MHz (or 12MHz at a pinch).


message:
Arduino ESP8266 receive email?

Is there a sketch that supports the receiving of email using the Arduino environment on the ESP8266? I can only find support for sending email. I know it's possible because the NodeMCU environment supports it. Any help is appreciated!

body:
Once you know how to connect to any server and send messages to it, retrieveing emails is just a matter of sending right messages (=commands).

Here below follows an "IMAP tutorial", i.e. guide to which commands to send to an IMAP server to search and retrieve messages.

Note: once you connect to the IMAP server, the first command to send is the login command:

    foo login user password

"foo" is just a session identifier, not a keyword. "login" is the keyword.

Once you get the welcome message, you can start sending more commands:

Select the proper folder:

    . SELECT "INBOX"

Look for desired message (strings are always considered substrings, so no wildcards are needed):

    . SEARCH FROM "user@example.org" SUBJECT "some keywords here"

This will result in list of matching messages, with search results formatted as follows:

    * SEARCH 5 10 456

This means messages n.5, n.10 and n.456 match the query.

If examining just the subject (which may contain keywords and switch as required) is not enough, the whole body can be retrieved, both marking the message as read or leaving it untouched:

    . FETCH 5  BODY[TEXT]

or

    . FETCH 5  BODY[TEXT].PEEK

End IMAP session with:

    . logout

For experiments from Windows using telnet:

    telnet mailserver.domain.com 143

Reference:

https://www.skytale.net/blog/archives/23-Manual-IMAP.html


message:
adding a dead band to my motor and gearbox

I have a motor and gearbox that has limits and a pot built in.

I have some code what drives the motor one way to when it hits its limits takes a value and drives the other way and takes a value, then map the range from 0 to 100, that all works fine.

I also have a analog input map to 0 to 100 what I would like to do is to drive the motor to where ever the analog input is at, which is what I have done with the code below but when the motor gets close it starts hunting backwards and forwards.

I tried to add some sort of dead band (where + 0.5 / where - 0.5) it just seems to just move the problem.

I did try -+ but this still did not help, so what I need to do is aim for the target value and stop then if I'm within 0.5 ether way then that is good enough.

How can I do that?

<!-- language-all: lang-none -->

    sensor       = pot on motor,
    where        = 0 to 5 input,
    vent1UPlim   = limits,
    vent1DOWNlim = limits

PS. I know the map of 0 to 100 could do with being bigger but it's just easier to get my head around at the moment.

<!-- language-all: lang-C++ -->

            //            pot           0-10v     ONE WAY
              if (sensorValue > (where + 0.5)) {
              if (digitalRead(vent1UPlim)==    HIGH) {
                DoneInitializationA=false;
                digitalWrite(vent1enable,      HIGH);
                delay(50);
                digitalWrite(vent1PWMA ,       HIGH);
                mydisp.drawStr(0, 2, "-close-|");
              }
              else {
                digitalWrite(vent1PWMA ,       LOW);
                delay(50);
                digitalWrite(vent1enable,      LOW);
                mydisp.drawStr(0, 2, "       |");
              }
            }
            else {
              if (!DoneInitializationA)
              {
                digitalWrite(vent1PWMA ,       LOW);
                delay(50);
                digitalWrite(vent1enable,      LOW);
                mydisp.drawStr(0, 2, "       |");
                DoneInitializationA=true;
              }
            }

               //                                   OTHER WAY
              if (sensorValue < (where - 0.5)) {
              if (digitalRead(vent1DOWNlim)==  HIGH) {
                DoneInitializationB=false;
                digitalWrite(vent1enable,      HIGH);
                delay(50);
                digitalWrite(vent1PWMB ,       HIGH);
                mydisp.drawStr(0, 2, "-open -|");
              }
              else {
                digitalWrite(vent1PWMB ,       LOW);
                delay(50);
                digitalWrite(vent1enable,      LOW);
                mydisp.drawStr(0, 2, "       |");
              }
            }
            else {
              if (!DoneInitializationB)
              {
                digitalWrite(vent1PWMB ,       LOW);
                delay(50);
                digitalWrite(vent1enable,      LOW);
                mydisp.drawStr(0, 2, "       |");
                DoneInitializationB=true;
              }
            }

body:
The simple way is to just subtract one from the other, take the absolute value and see if it exceeds your hysteresis range.

eg.

<!-- language-all: lang-C++ -->

    if (abs (sensorValue - where) >= 0.5) {
      {
      // do something

      if (sensorValue > where)
        {
        // one way
        }
      else
        {
        // other way
        }
      } // end of large enough to worry about

---

In response to this (since deleted):

> would this not have the same problem as mine as instead of hunting round its target it will just do it 0.5 away from the target?

By subtracting and taking the absolute value, we create a band of +0.5 and -0.5 where, if the sensor is in that range, we do nothing. It hasn't moved the problem because it can't move in two directions at once (both up **and** down).


message:
Can I program the Arduino without having an actual board with the able to emulate a COM connection to the computer?

I have ordered my Arduino, but it is not going to arrive until 2 months, and I would like to be able to emulate a COM connection to the emulated Arduino. I am writing a program that listens on the com port, and would like to test it.

The program needs to run on Windows, and emulate a COM connection, and a breadboard with a LED, and motors on it.

body:
You could use the [Simulator][1] in [Atmel Studio][2] or something like [Virtual Breadboard][3] which looks good

The [Atmel Studio][2] simulator might take a bit of work to simulate your devices but if you have 2 months then maybe that's okay :) If you want to use the simulator in Atmel Studio then you might also find the [Arduino plugin for Atmel Studio][4] useful.

I think there are quite a few other solutions if you search google.

  [1]: http://www.atmel.com/webdoc/simulator/simulator.wb_Simulator_Use.html
  [2]: http://www.atmel.com/microsite/atmel_studio6/
  [3]: http://www.virtualbreadboard.com/
  [4]: http://www.visualmicro.com/page/Arduino-for-Atmel-Studio.aspx


message:
Wifi.status() always returns WL_NO_SHIELD

I've an Arduino Mega 2560 R3 and recently bought a Wifi Shield CC3000 from ebay http://www.ebay.de/itm/201405512301
They write that the firmware has the version ServicePack 1.11.1.
The WiFi shield is connected to the Arduino and green status light is on.

I try to run this example code:

    void setup() {
      //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
    }

    // check for the presence of the shield:
    if (WiFi.status() == WL_NO_SHIELD) {
      Serial.println("WiFi shield not present");
        // don't continue:
      while(true);
    }
    ...

It seems that Wifi.status() always returns WL_NO_SHIELD.
What can I do?

Thanks for help.

body:
The problem is solved now.

- I imported the Adafruit_CC3000 library which can be downloaded here: https://github.com/adafruit/Adafruit_CC3000_Library
- I run the example but the output was chinese nonsense
- Instead of

    Serial.begin(115200);

   I used

    Serial.begin(9600);

   then the examples run without any problem

Thanks @Majenko. His question was very helpful.