How to replace String objects with char arrays while still using string methods

You already received good answer about some general ideas for
replacing String objects with C strings. Here I will try to add some
more tricks more specifically targeted to your actual situation.

I can see two places in your program where the use of String shines by
its convenience, and replacing it with C strings will require some
effort. The first is the use of Stream::readStringUntil(char) for
getting the first request line. Here
I see no better option (see edit below) than reading
the stream one character at a time, and putting those characters into an
array:

const size_t input_buffer_length = 256;

// Read a line of text up to the first '\r'.
// Returns a NUL-terminated string, without the final '\r',
// into a statically allocated buffer.
// Warning: this never times out.
const char *readline(Stream &input)
{
  static char buffer[input_buffer_length];
  size_t pos = 0;  // writing position within the buffer
  int c;           // current character
  while ((c = input.read()) != '\r') {
    if (c >= 0 && pos < sizeof buffer - 1) {
      buffer[pos++] = c;
    }
  }
  buffer[pos] = '\0';  // terminate the string
  return buffer;
}

You would use it like this:

const char *request = readline(client);

For more robustness, you may want to add a timeout. Note also that this
implementation is no reentrant, as it uses a static buffer. This is not
an issue for your use case.

Edit: As noted by hcheung in a comment, you do not need to implement
this readline() function, as you can use
Stream::readBytesUntil(), which handles the timeout
and is provided by the Arduino core:

char buffer[input_buffer_length];
client.readBytesUntil('\r', buffer, input_buffer_length);

The other place is the usage of String::operator+=(const char *) for
generating the response. Here I would advice you against using
strcat() or strncat(): these will require extra memory to store the
concatenated string which you probably do not need. Instead, you can
simply print() the pieces one by one:

void GenerateResponse(const char *text) {
  Serial.println(text);
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println();
  client.println("<!DOCTYPE HTML>");
  client.println("");
  client.print("

");
  client.print(text);
  client.println("
");
  client.flush();
  delay(1);
}

Alternatively, you can make use of the implicit concatenation of string
literals in order to reduce the number of calls to client.print():

void GenerateResponse(const char *text) {
  Serial.println(text);
  client.print(
      "HTTP/1.1 200 OK\r\n"
      "Content-Type: text/html\r\n"
      "\r\n"
      "<!DOCTYPE HTML>\r\n"
      "\r\n"
      "

"
  );
  client.print(text);
  client.print("
\r\n");
  client.flush();
  delay(1);
}


It is possible an Arduino generate 3d graphics on tft or vga

On AVR based Arduinos: No, definitely not. It is possible to create a VGA signal, but only with very limited resolution and few colors (like 4 or so) and also a framerate, that will not be enough. Also they all have too few memory.

It might be possible on the Due (don't have much experience with it), but it is still a bad choice for a platform (also partly because the Due is in general such a bad designed board with no good documentation).

  Is there a library can done that?

I don't think, that you will find any library doing all what you want. You might find libraries, that help you draw on the display, but you will do all the hard stuff (creating and loading sprites, distorting them, animating them) yourself. This is, because Arduino is a bad choice for such a project.

Also: In the title you mentioned TFT. I guess you meant one of the TFT display modules, that you can connect to Arduinos. Forget about that. They are connected over rather slow serial data interfaces (not meaning the Arduino Serial here, but serial interfaces like I2C or SPI). You won't get a sufficient frame rate with them.

I would oppose your arguments against the Raspberry Pi. Sure, it has an OS, but that also means, that it can make use of a variety of languages and frameworks. You are not bound to plain C/C++. You can use the language or framework, that best suites your needs. That can be a bit complex at first to find the right one. But thats, because your project is complex. What you are describing is a very complex task, when you cannot rely on others, that have already implemented the hard stuff (which would be the case for the Arduino).

Also a Raspberry Pi has plenty of RAM and plenty of storage space. It runs at high speed and is actually capable of outputting video with a good framerate.

Without wanting to offend you: I think, as you are asking this question here, you are not qualified enough yet to do such a project on an Arduino. There are insanely capable people out there (wouldn't count myself to them), who do incredible things with Arduinos by milking the very last drop of resources out of them. But they are doing it for the grind, not for having a functioning product at the end. I guess you want this to work good at the end, without needing you to work on it for many years. Then you are result-focused and should choose the correct platform for this. A computer (like the Pi) will be easier.

  Rasberry Pi had lot of things but some of them are unnecessary.

Yes, but is that really a problem? Is the unused potential really a no-go for the project? You could say the same thing about an Arduino. It has a lot of peripherals build in (depending on type Timers, Comparators, ADCs, DACs, several communication interfaces, power management peripherals, ...). Almost no project uses all of them. But that's simply the difference between general purpose chips/boards (like all Arduinos or Raspberry Pis) and custom made chips for a single purpose. If (!) a fitting chip for your project exists, that really only has what you need, it will most likely be very expensive. Chips for a single very narrow purpose have a very narrow target group, thus are more expensive (simple economy here). Companies have formally nearly everytime designed their own chips for gaming consoles (which is way beyond your current scope), like PS1 or N64. Current gaming consoles rely often on modified standard hardware, also because it is cheaper. The really old gaming consoles used the generic electronical chips, which means, that you didn't have one single programmable chip. Instead lots of the logic was build into the electronic design.

So you will always have some excessive features, that are not used. Why would you want to remove them from the project, just for the fuzzy goal of not wasting features. It will make your project only more complex and expensive. You will gain nearly nothing from minimizing the resources. This is a hobby project, not for selling it.

  In rasberry pi you just writing a computer program.You don't have much control like arduino

That depends on what type of control you mean. On a computer you are writing code on a higher level of abstraction. That also makes it easier to do complex things, since you can rely on the low level programming of others. What control do you want to have over the system, that you don't have on a computer like the Pi? Do you think, you can program better display drivers or graphic renderers, than all the other people? Then you can still do that on the Pi. A Pi also gives you control over the GPIO pins, which let's you do many hardware things, that you can also do on an Arduino.

Also Linux is open source. If you think, you need more low level interaction with the hardware (cannot think of a reason for needing it), then you can build your own OS, which gives you the needed freedom. Sure, that is very complex. But when you are able to use the low level programming, then you are also able to change the OS.

You seem to already have chosen the Arduino for your project. I, like others, have advised you to use a Pi instead to make it a lot easier and better. It is up to you, if you want to believe us or not. All in all I'm still not convinced, that you are able to pull that off on the Arduino platform, while still getting good results. You are simply not at that point of knowledge yet. You write confidently about the problems with an OS, while you don't seem to have a concept about the exact structure of these problems and how they impact you. We will not prevent you from doing it the hard way. Please for free to choose your own way.


Measure the duration a pin is in a HIGH state

Non-blocking version.

bool old_button_state = LOW;
void loop()
{
    if(digitalRead(button_pressed) == HIGH)
    {
        current_state = current_state+1

        if( old_button_state==LOW )
            delay(500); // long delay
        else
            delay(100); // short delay

        old_button_state = HIGH;
    }
    else
    {
        old_button_state = LOW;
    }
}

Simplistic version.

void loop()
{
    if(digitalRead(button_pressed) == HIGH)
    {
        current_state = current_state+1
        delay(500);// long delay

        // repeat while the button is being pressed
        while(digitalRead(button_pressed) == HIGH)
        {
            current_state = current_state+1
            delay(100); //short delay
        }
    }
}

Ideally you wouldn't just wait for 500ms, but 'break out' of this delay as soon as the button is released.


To be honest, I still have to receive my RF's... But I have a similar problem, meaning I also need to have them all to both receive and transmit.

I thought it was not possible, since in a 6-1 network, one is receiver, 6 are transmitting. With auto-ack messages can be returned.

Depending on the amount of messages being sent and latency you can let them talk when needed and hope there is not too much sending simultaneously (causing resends).

One solution you could use, is to put in the message a receiver ID. Suppose the 'geographic location' of your objects are

A   <---->   B  <----> C

Assume A wants to send to C, but it will not be received by C, C does not auto-ack, and A knows this. Know A can send the message to B, which can auto-ack, and B has to send it to C. Possibly the original source (A) has to be added to the message as well, if this is important for C to know.

Update: (in steps)

Suppose A wants to send a message m to C

A sends message m to C
C does not receive it, thus is does not send an ACK-message back to A
A gets a timeout
A knows that message m has not been sent to C (so it is out of range)
A sends the message m to B (adding 'A' as sender of the message if not already done)
B receives message m
B sends an ACK back to A
A knows message m has been sent to B
B sends message m (with A as sender) to C
C receives the package
C sends back a message to B
B needs to send a message to A that m has been sent successfully

Some generic remarks:
- This scheme is maybe not full-proof or can be optimized (like that A knows from now on it needs to send to B first to reach C).
- Also both B and C can be out of range, you want to resend it (later)?


You need more decoupling capacitors - one per VCC and AVCC pin, plus a larger (10µF) for the whole chip.

You need a pullup resistor (and maybe button) on RESET.


The Particle Photon is a replacement for the Spark Core module. This module was exploiting the Texas Instrument CC3000 chip. It was this chip that handle the very simple and convenient Wi-Fi configuration of the Spark Core. Texas Instrument named this method : SimpleLink.

The Particle Photon is now using a different module than the Core : a Broadcom BCM43362 instead of the CC3000. It's seems to work in a similar manner even if I was not able to find any information on it.

I've found on the George Howkins Depletion Region blog  multiple articles that explain how the CC3000 SimpleLink works.

CC3000 Smart Config - transmitting SSID and keyphrase
CC3000 advertises presence on network via DNS-SD

All the posts : http://depletionregion.blogspot.fr/search?q=smart+config


Connecting Saleae Logic 8 to MISO (pin 12) on Uno 3 w/ NRF24L01+ halts program

It would appear from your description that the leads on your logic analyzer distort of the SPI MISO waveform and the Arduino does not read incoming data correctly.

To avoid this, you could place an digital isolator between the Arduino and the Logic 8.

Any decent oscilloscope should also allow you to read the SPI bus.


dns lookup only works with DHCP and not with static setup (EtherCard library)

DHCP does more than just give you your IP address: it also gives you the Net Mask, the Gateway IP address, and the DNS Server IP address. If you don't call dhcpSetup(), you'll have to do it yourself.

According to the EtherCard documentation, you can do that as follows:

const static uint8_t ip[] = {192,168,0,100}; // Example
const static uint8_t gw[] = {192,168,0,254}; // Example
const static uint8_t dns[] = {192,168,0,1};  // Example

...

if (!ether.staticSetup(ip, gw, dns)
{
    // handle failure to configure static IP address
    // (current implementation always returns true!)
}


I found the solution, it was the Arduino, older version R2, the R3 works like a charm. I didn't know that the version could cause so much trouble. But in case someone encounters the same problem R3 did it for me.


List of Arduino board preprocessor #defines

The list of board symbols can be generated by this shell command:

$ grep board= boards.txt | cut -f2 -d= | sort -u
AVR_ADK
AVR_BT
AVR_DUEMILANOVE
AVR_ESPLORA
AVR_ETHERNET
AVR_FIO
AVR_GEMMA
AVR_LEONARDO
AVR_LILYPAD
AVR_LILYPAD_USB
AVR_MEGA
AVR_MEGA2560
AVR_MICRO
AVR_MINI
AVR_NANO
AVR_NG
AVR_PRO
AVR_ROBOT_CONTROL
AVR_ROBOT_MOTOR
AVR_UNO
AVR_YUN

The boards are defined by the "build.board" property in the boards.txt file.

mini.build.board=AVR_MINI

This property is used by the build recipe together with ARDUINO_-prefix.

-DARDUINO_{build.board}

Cheers!


They seem pretty self-explanatory. Data, sclk and cs are normal SPI MOSI, CLK and CS. A0 is probably equivalent to C/D. RES is reset - tie high to run. Power and ground are obvious. The others look related to the back light.

However... How are you going to operate it? Do you know the SPI instructions to send? They will be specific to the display, so without a datasheet you're pretty much stuffed.


most effective ( progsize/speed ) SD card usage

For AVR + SDCard you should check FatFs from Chang. It is widely used and proven C library. You can tweak the configuration file to get minimal size (8K shall be easy). Check wrapper library for Arduino here (6K with default options).

There is also even smaller version called Petit FAT (2-4K) but it doesn't support file delete feature.

If you would like to get smallest possible code, there is option to use Atmel Studio for programming Arduino boards, but you will loose the convenience of Arduino libraries (re-implement the libraries or find AVR versions of them, work with registers directly etc).


Why does my Arduino seem to reboot every time that I open Serial Monitor?

That is a normal feature of Arduinos, not an error. I find it mildly annoying sometimes, but it's nice for interactive programs that want some kind of menu message to be the first thing you see in the terminal.

If you want help disabling the auto reset, your options are detailed in Disabling Auto Reset On Serial Connection.


Charge 14500 LiFePO4 lithium batteries from an Arduino Nano

No, you cannot charge a Lithium-Ion battery (of any variant) directly from an Arduino. You require a Lithium-Ion battery charge controller.

The best source for these kinds of things at a small size is retailers of model vehicle parts.


Shift register with relay board behaving erratically

If this is a noise issue, there are a number of mitigating actions to consider.  Also, consider that most if not all noise mitigating approaches are generic and may not apply to all situations.

It is almost always easier to mitigate noise at the source.  Filtering the power & shielding are two approaches.
When laying out digital integrated circuits, it is common to include bypass or decoupling capacitors as near as possible to each integrated circuit.  If unfamiliar with these, these capacitors go across the power pins of the integrated circuit.
If an electrically noisy environment is anticipated, making all communication leads and cables as short as possible prevents the likely hood of unexpected results.
If cables need to be long different communications methods such as balanced line or differential signalling should be considered.
Bring all power grounds to a single point.  This mitigates current loops which can cause unexpected power voltage fluctuations.
Consider the power requirements and generally use a power supply that is rated for double to have a margin of safety.
Avoid running cables containing high power or switched power near or in parallel to cables containing low voltage logic.

For this particular application / design:

Likely the reversed bias diode on the relay power supply lines is not needed.  There appears to be optical isolators on the relay board which should prevent the inductance of the relays from feeding back.
Verify you are creating the correct signal to the 74HC595 chip.  Use the timing diagrams on page 8 of this ti.com 74HC595 specification sheet as a guide.
Consider the gauge of the power cables.  Thinner wires over longer runs will drop the voltage proportional to the current demand.  If all 8 relays are active, the current demand may be as much as an Amp.


Old post, but here was my solution. Had to pickup some shielded cable. Pics below should clearly explain how everything was wired up.


As I turns out, the avr-gcc (GCC) 4.9.1 goodies weren't being used at all! The arduino package was using a decrepit version of gcc,

prakhar@sim74stic ~ $ /usr/share/arduino/hardware/tools/avr/bin/avr-g++ --version
avr-g++ (GCC) 4.3.2
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

prakhar@sim74stic ~ $ /usr/share/arduino/hardware/tools/avr/bin/avr-gcc --version
avr-gcc (GCC) 4.3.2
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

All I had to do was specify:

AVR_TOOLS_DIR = /usr

to exexute with -std=c++11 flag (I also had to add an -fpermissive flag to compile C with g++).


Can I use my phone's charger to connect arduino M0 pro R3 with computer?

Echoing what Gerben said, in order to wrap up this question:

If the Samsung cable has a micro-usb on one end, and a usb-a on the other side, then I don't see why not.
You just want to power it, not connect it to a PC? A regular USB port only supplies upto 500mA, so 1.5A is plenty.
The allowed input voltage range for this pin is 6-20 V. source. So your 12v adapter is also fine.


NodeMCU (Arduino IDE) 'DynamicJsonBuffer' was not declared in this scope

This error is caused by using a 6.x.x version of the ArduinoJson library with code that was written for a pre-6.x.x version of the library.

You have two options to solve the problem:

A. Downgrade the library to a version that is compatible with your code

For now, this is probably the best option because the 6.x.x version of the ArduinoJson is still in beta so it makes sense to wait until the new API is stabilized before porting your code. This is even recommended by the ArduinoJson developers:

https://arduinojson.org/v5/faq/error-jsonbuffer-was-not-declared-in-this-scope/

Sketch > Include Library > Manage Libraries...
Wait for the download to finish.
In the "Filter your search..." box, type: "arduinojson".
Click on "ArduinoJson by Benoit Blanchon".
From the "Select version" dropdown menu, select "Version 5.13.2".
Click "Update". Wait for the update to finish.
Click "Close".

Now your code will compile. If you have File > Preferences > Check for updates on startup enabled, you will continue to get updatable library notification for the ArduinoJson library but you need to refrain from updating back to a 6.x.x version or the error will come back.

B. Update your code to be compatible with the 6.x.x version of the ArduinoJson library

In this case you need to modify your deserialization code to use the new DynamicJsonDocument instead of the old DynamicJsonBuffer:

if (httpCode == 200) {
  // Parsing
  const size_t bufferSize = JSON_OBJECT_SIZE(1) + 50;
  DynamicJsonDocument jsonDocument(bufferSize);
  DeserializationError error = deserializeJson(jsonDocument, http.getString());
  if (error) {
    Serial.println("There was an error while deserializing");
  }
  else {
    JsonObject root = jsonDocument.as<JsonObject>();
    // Parameters
    int Mode = root["mode"]; // 1
    Serial.print("Name:");
    Serial.println(Mode);
  }
}

You can get more details about this here:

https://arduinojson.org/v6/doc/upgrade/


I would suggest to download the Arduino app (https://www.arduino.cc/en/Main/Software).

Download both the latest version and an a legacy build (https://www.arduino.cc/en/Main/OldSoftwareReleases#00xx). Within the DMG for the legacy you'll need to install the FTDI drivers to allow Arduino app to see the Arduino in ports.


As commenter by RSM

The issue you are facing is because you are using pins 0 and 1

These are used by the arduino for uart.

So for starters please use any pin other that 0 and 1.  But if you insist that you do need to use these pins,  then you don't need softwareserial you can use the default serial itself, but you will need to disconnect the bluetooth while programming.


Different Output Voltages from Same Source?

Are there any gotchas to consider with this type of circuit, or is this the totally normal way of doing things (eg. like wiring a house out of a breaker box)?

That's a perfectly normal way of wiring it.

Is there a better way to do this?

No, it's how I'd do it.

This won't cause a short circuit, right?

Not intentionally, no. However it's always good to add a fuse or two to protect everything just in case anything untoward should happen. Especially where water is concerned.


Most efficient way to store number in EEPROM?

My best off-the-top-of-my-head figure is 6 bytes.

4 bytes for the timestamp (assuming a 32-bit value).  Two byte for -32768 to +32767.

Multiply the temperature by 100 to make it into the integer range -5500 to +12599. That then fits comfortably inside a 16-bit signed integer.

However, there are other tricks you can use.

For instance, if you know the time of one reading you don't need to store the time of the next - only how much later it is.  One byte can then store up to 255 "whatevers" later than the previous entry - be that seconds, minutes, hours, whatever.

Similar with the temperature.  You can just store the difference from the previous reading as a single byte if you know that successive readings will never deviate by more than +/-1.27 degrees.

Also, you can check to see what the last saved temperature was, and only save a new temperature if it has changed from before.

Another thing is the resolution of your data.  You say 2 decimal points, but if the values are all multiples of 0.05 then what is the point of storing at 0.01 resolution?  Just store how many 0.05s there are (divide by 0.05) then multiply it out again afterwards to get the original temperature.  Most useful when coupled with a temperature difference to increase the storage range.

There's many tricks, you see, and which work best depend exactly on what you want to do with the data.


Reading the DotStar datasheet - power requirements

You have correctly worked out:

I(A) = P(W) / V(V)

I = 0.2 / 5
I = 0.04A

MAX:
I = 1 / 5
I = 0.2A

From that it seems it will use between 40 - 200mA depending on brightness.

Sink current refers to the current required to drive the led's digital input from your MCU's digital output.

More information on current sinking


W5100 Ethernet Shield to Custom Board Problem

A bit late to the party but... it may be that you are using pins 1, 2, 3 and 4 instead of 1, 2, 3 and 6 on the RJ45. It is unclear whether you are connecting via a header, in which case you my disregard this, or straight to the RJ45, in which case you need to change your pin:

1. white/orange
2. orange
3. white/green
6. green


Per the Quick start guide, Ino assumes the board is an Arduino Uno unless otherwise specified on the command line:

All examples were done in assumption that you have Arduino Uno and it is available on default port. Now consider you have Arduino Mega 2560 and it is available on port /dev/ttyACM1. We have to specify this for our build steps as command-line switches.
Board model may be set with --board-model or -m switch. Port is set with --serial-port or -p switch. So lets do it:
$ ino build -m mega2560
$ ino upload -m mega2560 -p /dev/ttyACM1
$ ino serial -p /dev/ttyACM1

For the full list of board names refer to ino build --help.

So you might be able to do this by using
$ ino build -m pro328
$ ino upload -m pro328 ...

However I don't know what options Ino includes for boards (presumably it uses the boards file), so using ino build --help should give you the information you need to select a suitable board if pro328 doesn't work.
Once that's done, the frequency setting should be taken care of for you.


Reason for warning "avr:build doesn't define a 'build.board' preference" when build.board is explicitly set in boards.txt?

It appears that you can no longer set a global property in the boards.txt file. You must set every property individually inside each board ID, even if they are the same for every board in the file. This seems to contradict the documentation that states that...

  The other properties will override the corresponding global properties
  of the IDE when the user selects the board.

Further, if any global key is set directly, then both the board specific keys  and the global keys are ignored.

So in my above boards.txt, setting the the global key build.f_cpu at the end of the file seems to cover the blink.build.board key and prevent it from being copied to build.board when the board is selected. Even if you set the global key build.board directly, this setting is ignored.


Is it possible to start audio playback when headphones gets plugged in?

A lot of 3.5mm jacks come with built-in normally-closed contacts, and their state can be tested through the pins of the jack with a multimeter or sensed by your MCU like any other switch. There are usually 2 pins each for the ring (pins 2 and 4 below) and the tip (pins 3 and 5), each pair connected to the other and one pin for the sleeve. The insertion of the headphones' connector breaks the connection between each pair, so that only one pin of each pair is actually connected to the connector's tip and ring.

You can connect the tip (pin 3) of each jack to digital input pins and connect the other pin of the pair (pin 5) to Vcc; you only need to read the tip because if the tip contacts are closed, it means nothing is fully plugged in yet. When no connector is plugged in, input pin reads HIGH from the tip since it is connected to Vcc through pin 5. When the headphones are plugged in, it breaks the 3-5 connection, and the tip now floats. Its voltage is indeterminate; it will probably sit somewhere near the middle of the 0-5V range, but we can't be sure.
To remedy this, there are 2 possible approaches I can see:

You use an analog input pin, instead of a digital pin. This way, you can read the very voltage at the tip; if its ADC value is above 900 perhaps, you can conclude that its HIGH and therefore nothing is plugged in, whereas if its below 600, you can conclude that the tip is floating and a headphone is plugged in. However, this method will require an input pin per headphone. The Uno has 6 analog pins, so this will take up all of them. If you aren't already using any of them, this method may be good enough. You could also use an analog GPIO expander.
You can use a digital input pin for the tip (pin 3) but instead of pulling pin 5 to Vcc, you connect it to a digital output pin. You can connect the pin 5 of each headphone set to this common output pin. To test if a particular jack has headphones plugged into it, you read the associated input pin and check if this is the same as the current value of the common output pin (saved to some variable). If it is, you toggle the output pin and again check the input pin to see if it mirrors the new value of the output pin; just additional confirmation. If everything checks out, then nothing is connected to the jack yet. If either test fails, you can reasonably conclude that headphones are plugged in.

Now that you know headphones are plugged in, you can call the appropriate function to begin playback through the right jack. Of course, all this assumes you'll be working with the jacks directly and not through some module. If you use the Adafruit Soundboard, you can check out the L (Left Channel) pin, which corresponds to the tip. I don't know if it's actually connected to the jack so you'll have to experiment and find out.


Unfortunately I do not have the ability to comment. What I can suggest is to look at the small 5 pin regulator and look at its markings. If the IC is marked with "QT33" then adafruit has stupidly soldered the wrong chip onto your trinket board. If it says "QT50" then the regulator is not at fault.


Come out of loop and execute Setup again

You could just call setup() yourself:

void loop() {
    if (some_condition) {
        setup();  // reinitialize everything
        return;
    }
    // etc.
}

But, as Majenko puts it, if you nee to do that it looks like there is
something wrong with your methodology.

That being said, it would be less suspicious if you only need to
reinitialize some specific part of your program. In this case you can
make a separate function for these initializations, and call it both
from setup() and, when needed, from loop():

void init_foo() {
    // ...
}

void setup() {
    init_foo();
    // other initializations...
}

void loop() {
    if (some_condition) {
        init_foo();  // reinitialize foo
        return;
    }
    // etc.
}


Comparison of Board Shape between Arduino MEGA and Arduino DUE

The Due has the same footprint as the Mega 2560.

source


How to use FTDI to program Lilypad Arduino?

"Access is denied" this looks like you should at least restart your computer after you installed the FTDI driver if you have not already.

Run Arduino IDE as Administrator and also make sure you are logged into an Administrator account in your windows login.

If all this fails this means another application is using that com port you will need to figure out what could be using that com port another instance of Arduino IDE opened? Etc

If all else fails restart your computer with the usb unplugged, login, open arduino IDE and plug in your usb and select the com port.

Edit: You can also try changing the USB port you are currently using for another one, this will also change your com port to a new number


Serial loop stopped after a while, I don't know why

Add:

while(!Serial) ;

I'll make sure the Leonardo is in sync with the Serial communication.

It is the case because the Leonardo is USB native thus the Serial communication works differently.


Looking at the GitHub page, there is a document explaining how everything works, https://arduino-esp8266.readthedocs.io/en/latest/


GUI interface with microcontroller to control a device through SPI

I grappled with the same question for a while. Here is how I solved the issue.

1- Find a suitable exchange format and protocol

Here you need to decide what is the most important thing on the communication. Is it speed? Is it error detection? Is it memory footprint? For my project, for instance, I decided that I need my communication to be as error free as possible, with minimal memory footprint (up to 64 bytes) and I don't really care about speed, so I gone for a JSON messaging protocol where the desktop application send a short (up to 64 characters) JSON message and receives a short answer. This solved MY problem, your requirements might be different. If you need speed and don't care for memory, for instance, you can use a binary protocol with a header specifing size, the message and a CRC footer to check vailidity. Or you can use BSON and take this library to avoid the hassle.

2- Define the Serial Polling Cycle
How will the arduino firmware knows it is time to send or receive messages? It is always talking? Always ready to receive? It looks at the serial port buffer once each few microsseconds to know if there is an incomming message? How that is handled by your device? If you just need to output data without bothering whether there is someone listening or not, like an GPS device, just throw a Serial.print now and then, but if you need to wait for data, you will have to compartimentalize the process inside an FSM or using some kind of scheduler. If you are not using a scheduler, I recommend this one.

3- Define the Communication Cycle
Here you will take the data from serial port and storing it on a buffer for later usage.
The trick here is
1- Check the serial FIFO for incomming data. Serial.available() does it already.
2- If there is incomming data, copy the data to next available space in the buffer.
3- Check if there is more incomming data after a few millisseconds.
4- If there is no incomming data, mark the buffer as ready to use, and parse it.

The following code is unscheduled for simplicity,and I recommend you to replace the sleep() calls to proper scheduling least you want the arduino go unresponsive. It is also waiting text data, so you will need to make changes if you are waiting binary data.

  char buffer[64];
  memset(buffer, 0, 64);

  while (!Serial.available())
    delay(50);

  while (Serial.available()){
    Serial.readBytes(buffer + strlen(buffer), Serial.available());
    delay(50);
  }
  parseBuffer(buffer);


Can I control a Arduino from an apache server?

If you attach a 'network adapter' to the Arduino, you can start a TCP server on Arduino. The server, a telnet server or a web server will listen for commands  sent from computer. In case of web server, you can send commands from web browser too. Other option is to use UDP communication. Arduino can listen UDP.

The options for the network are Ethernet or WiFi. Both are in form of shields or modules. For Ethernet Wiznet 5100 and 5500 chips are best supported and for WiFi the esp8266 is the common option.


If it's the byte order that causes a problem that's likely compiler specific and I don't think one can change it. Even if it were possible, changing the global endianness might break libraries that depend on it, so you likely can't escape using a function to swap the variable.

If you know you only need one value at a time you could write something like the following code, with a global buffer (untested but in principle should work (and I know global variables are evil, but should work for an Arduino project)):

byte buf[2];

byte* reverse(int val) {
    buf[0] = (byte)(val >> 8);
    but[1] = (byte)val;
    return buf;
}

So you could use it like:

int8_t ret = twi_writeTo(eeprom_i2c_addr, reverse(eeaddress), 2, 1);


ATMega328 functions, but will not output to any pins

This may not be your only problem, but you need a second delay.
void loop() {
  Serial.println("TICK");
  digitalWrite(5,HIGH);
  delay(1000);
  digitalWrite(5,LOW);
  delay(1000);    // LOW for a second as well
  }

Otherwise you will not be able to see the LOW part, because it will be really quick.

I believe that Arduino IDE is attempting to compile my code for the UNO and those pins do not work on the ATMega328

The Uno has an Atmega328 on it, and I usually compile for the Uno when uploading to a custom board, so this is not the issue.


Sim800L Uploading issues, HTTPACTION returns 0, 302, 701

302 is HTTP code returned by the server. It is used for redirection. Print the response with AT+HTTPREAD to see where does it redirectd.


Idenitifying pins in my code. which pin is which?

If you select the right board in Tools menu, you can use constants corresponding to labels.

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


Certainly the issue is from EMI but not from the collector side as from the transistor base even the wires are shorter on that side as I understand from the comments.

It's a common mistake to let the transistor base floating, see here a different application but with the same cause and result, the transistor is turning on apparently with no reason. With the base floating the EMI current has no other path than through the transistor base where is amplified by beta ( 110 to 800 for BC547).

Put a 10Kohm resistor between the transistor base and emitter to  let a path for EMI currents to the ground. Try different values, smaller if you still have false triggering, higher if the sensor is not turning on the transistor.

Of course, use  INPUT_PULLUP but the internal resistor is to high 30 to 100 kohm, better use an external resistor arround 10k or lower form the transistor collector to 3V3 to ensure a good noise margin on the collector side to.

simulate this circuit – Schematic created using CircuitLab


The Arduino Due is backed by an Atmel SAM3X8E ARM Cortex-M3 microprocessor and most of the pins on the Due are connected directly to this chip. Therefore, you can refer directly to the chip's datasheet for descriptions of these hardware features.

Atmel SAM3X8E ARM Cortex-M3 datasheet


FastLED-driven strip acts weird when using PN532

After spending way too much time on the code, I figured that it had to do with something entirely different:
The RFID reader created an RF interference on the data wire towards the LED strip... Shielding it properly did the trick, no matter which pin is being used.
Thanks for the help anyway.


I2C from two masters (ATtiny85, ESP8266) to one slave (ATmega328)

If you have 1 receive only device, and 2 send-only devices, why not make the receive-only device the master, but have it poll (periodically, repeatedly ask) the slave devices to send any data they have pending. That way, there is only one master, and it only asks for data when it's ready (that is, not receiving from some other device.)

One purpose of a master/slave bus system is to avoid contention (two or more devices talking at the same time.) The master tells each device when to send, and only listens after it asks.


So I've just tested your code and apparently you have to send all data at once. After some research: it sends characters into the function twi_transmit and this function just fills the buffer and actual data are sent asynchronously. So, if you are fast enough, you will overwrite the buffer with another bytes and it's still like you have only 1 character to send.

For example this works (AVRs are little endian):

#include <Wire.h>

// This is called from the I2C host.
void I2C_Send()
{
    uint16_t   uints[2] = {0xDEAD,0xBEEF};

    Wire.write((uint8_t*) uints, 4);
}

void setup(){
    Wire.begin(30);  // initialize I²C library and set slave address
    Wire.onRequest(I2C_Send); // define I²C slave transmit ISR

    Wire.flush();
    Wire.setTimeout(1000L);
}

void loop(){
    //stuff
}

And receiver with HEX prints:

#include <Wire.h>

uint16_t receive_wire_int(){

    while(Wire.available() < 1){}

    // Read low byte into rxnum
    uint16_t rxnum = Wire.read();

    while(Wire.available() < 1){}

    // Read high byte into rxnum
    rxnum += Wire.read() << 8;

    return rxnum;
}

void setup() {
    Wire.begin();        // join i2c bus (address optional for master)
    Wire.setTimeout(1000L);
    Serial.begin(9600);  // start serial for output
}

void loop() {
    Serial.println("Requesting data..."); Serial.flush();

    Wire.requestFrom(30, 4);

    uint16_t acount = receive_wire_int();
    uint16_t bcount = receive_wire_int();

    Serial.print("acount: 0x");
    Serial.print(acount,HEX);
    Serial.print("  bcount: 0x");
    Serial.println(bcount,HEX);

    delay(500);
}


USB Device not recognized (error 43, arduino uno)

The USB microcontroller Atmega16U2/Atmega8U2 on the Ardunio UNO board might be corrupted. Try uploading the USB to Serial HEX file with boot-loader found in C:\ProgramFiles\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\firmwares\atmegaxxu2\Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex
using Flip OR any other other ardunio (as an ISP programmer). for doing this you have to first enter BOOT-LOADER by shorting the Reset Pin of the USB controller to GND  both pins can be found on ICSP2 of the UNO.
This will surely solve the issue.
But,
if the problem still persists then your USB controller is damaged and have to replace the controller and again upload the USB to serial firmware, the process is same as mentioned above, but you don't need to short reset and GND as you don't have an boot loader installed in the new controller.


Given that only the falling edge of your input is sharp and well
defined, I suggest the following approach:

Use the input-capture feature of Timer 1 to get a timestamp on the
falling edge and trigger an interrupt.
In the ISR, start by toggling the output in order to set it low. Then
compute the period of the signal (timestamp of this falling edge minus
timestamp of the previous one) and program a compare register to
trigger a compare match event after half a period.
The compare match would automatically toggle the output pin again, by
using the “toggle on compare match” timer output mode.

The following program attempts to implement this approach. Note that it
is completely untested. Input is on pin 8 (i.e. PB0 and ICP1). Output is
on pin 9 (i.e. PB1 and OC1A). The timer is set to run at F_CPU/8 in
order to accommodate frequencies as low as about 30.1 Hz. A
different prescaler should be used if lower frequencies are needed. The
program does not rely on the Arduino core, and thus defines its own
main() instead of setup() and loop().

ISR(TIMER1_CAPT_vect)
{
    TCCR1C = _BV(FOC1A);  // force output compare -> toggle output
    static uint16_t last_capture;
    uint16_t capture = ICR1;
    uint16_t period = capture - last_capture;
    last_capture = capture;
    OCR1A = capture + period/2;  // compare match after 1/2 period

    // If output is high, toggle again.
    if (bit_is_set(PINB, PB0))
        TCCR1C = _BV(FOC1A);
}

int main()
{
    // Set OC1A = PB1 = digital 9 as output.
    DDRB = _BV(PB1);

    // Configure Timer 1.
    TCCR1A = _BV(COM1A0);  // toggle OC1A on compare match
    TCCR1B = _BV(CS11);    // clock at F_CPU/8
    TCCR1C = _BV(FOC1A);   // force output compare -> toggle output
    TIFR1  = _BV(ICF1);    // clear capture flag
    TIMSK1 = _BV(ICIE1);   // enable capture interrupt
    sei();

    for (;;) {}
}


Why does Serial.print print out the wrong thing?

You've stumbled across the difference in the C++ language between a String and an "array of characters". What you gave Serial.println() was an array of characters:

Serial.println("Flame: "...);

and then tried to add a number to it.

Serial.println("Flame: " + flameState);

If it had have been a String, then what you typed would have been fine:

String flame = "Flame: ";
Serial.println(flame + flameState);

Adding (literally +) a number to a String adds characters to the String to represent the number. Unfortunately you didn't start with a String, you started with an array of characters:

"Flame: "

Adding a number to THAT changes where the array starts. flameState must have been 1, and "Flame: " + 1 would have been "lame :" - as you found out!

The version that worked did so through a little bit of magic:

Serial.print("Flame: ");
Serial.println(flameState);

The first line called a version of print() that accepted an array of characters and printed each of them out. The second line called a different version of println() that accepted a number and printed out its representation as a series of characters (digits) - followed by a new line (the ln part of the name).


How to identify Arduino Mini Pro 5v vs 3.3v

Consideration (go down for the actual solution)

If you have a lot of different China-Arduino-clones, the easiest way will be to just test it. The cloned Arduinos use a lot of different voltage regulators and often you won't even be able to find datasheets for them on Google.

Someone here provided an Arduino sketch which helps you identify the frequency with which the Atmel is running and the comments say "it is the safest method". But why? It is complicated (you need to connect the USB-TTL-converter to each of the different Arduinos and sometimes they have different pinouts, so it's error-prone - you could easily fry your Arduino if you connect the wires to the wrong pins)...

Solution

I think the safest way is just connecting a voltage in the range of 6V-12V to the RAW-pin and measuring the (regulated) output of the VCC-pin.

There is no reason why this would kill your Arduino (in case your Arduino isn't broken - which would be good to know anyway; and of course you shouldn't short anything).

I've done a short sketch of how you should connect your Arduino Pro Mini:

RAW <---> 6V-12V
VCC <---> multimeter (5V = 5V Arduino, 3.3V = 3.3V Arduino)
One GND pins to the GND of the power source and one GND pins to the GND of the multimeter (you can take any of the Arduino pins labeled with GND)

Don't worry if your Arduino looks a little bit different, just look for the pin labels. For instance, one of my 5V Arduino Pro Minis looks like this, but also has RAW-, VCC- and GND-labels (just one of the GND pins is at a different position, make sure you check your Arduino pin-labels):

Alternative

You don't want to use the method above for some reasons? Then you need sharp eyes and some luck that the following list includes you components (some of these are collected from the other posts, some of them from my Arduinos):

3.3V:

Voltage regulators: KB33, S20K, F34V, L0RA, L0RB
Oscillators: 80e., 80'0

5V:

Voltage regulators: KB50, L05, L0UA, L0UB
Oscillators: R160JAC6s, 16.000-30, A1, A'N, A'a

(no limit or warranty for these details...)

More Suggestions

Some of the Arduino Pro Minis come with MHz and V markings on the back. In my case, none of these were checked. Make sure you check them as your new Arduinos arrive, so you won't have any problems identifying them later!


Can't figure out how to send Motor Values over Bluetooth, Arduino Bluetooth-controller robot

A state machine is the right way to go if you are sending multibyte commands.

However do you need to send 4 bytes for every turn? Do you need accuracy to one degree? Are you going to make regular turns of greater than 60 degrees?  If not I would consider encoding the dAta into a single byte.  You will reduce the radio bandwidth by 3/4, it will improve the responsiveness of. Your software and it will remove the need to have a handler for incomplete messages.

Of course there are probably other requirements that I don't know that will stop you doing this, but in case you haven't thought of it.


I have to reload Sketch every time I start my Yun

Please explain which messages? Serial port messages or MQTT messages?

The mqtt.connect name "arduinoClient" is the ID name. It depends on the server what the parameters should be. For some servers it can be an empty string and the second parameter should be the account name, and a third parameter for the password/key.

When you upload a sketch, the OpenWrt part is already running. Perhaps there is a problem with Bridge.begin. Try to wait 90 seconds before calling Bridge.begin. If a 90-second delay makes it work, lower it to 5 seconds, and keep it at 5 seconds.

Perhaps you can use (blinking) LEDs to indicate that the code has finished the Bridge.begin or to indicate an error.

When you solve this problem, there will be other problems. Have you updated to the newest firmware for the OpenWrt part? The Arduino Yún might only work with a very simple and small sketch. Don't try to add too many things that use the Bridge. The OpenWrt/linux part is reliable, you can run linux scripts there. The ATmega32U4 part is just like an Arduino Leonardo and is also reliable. It is the combination and the Bridge that causes a never ending chain of problems.

What about the Raspberry Pi? That is reliable. Have you thought about the ESP8266 or ESP32 in Arduino compatible mode? Adafruit has an MQTT server for users, and the Adafruit Feather M0 WiFi seems a very nice board. Anything but the Yún.

My best advice for you is to grab a hammer and destroy the Yún and forget about it. It will make your life so much easier.

(I just noticed that this is a very old question, sorry, but my answer is still valid).


Why isn't DigiSpark automatically recognized on other computers?

You will need to install the drivers before you can use it on other computers.
The drivers tell a Windows PC how to talk to the device.  The device is not a generic device so Windows can't use a fall back driver, like it could with a keyboard or monitor.


Why is 8x8 matrix pins do not correspond to rows and columns order?

It's probably easier to manufacture, other than that, I don't see why.
If this is a serious issue, you can contact your manufacturer, since he is most likely to know why.

You can:

Work around the issue, by wiring pin 1 to input 9, pin 2 to input 14 etc.
Make a software solution like:

#define ROW1 9

#define ROW2 14
Buy an LED-matrix that has the pins in the correct order (check the datasheet before purchase).


When accessing a variable from an ISR, is a volatile pointer enough?

First, beware that what you have written is not a volatile pointer, it's
a pointer to volatile data. If you always access the object through this
pointer, you should be fine. If you use the pointer in the ISR, but
access the data directly in the main code (bypassing the volatile
qualifier), then the program could fail.
Consider the following:
void loop()
{
    if (_flag_ISR) {
        _flag_ISR = false;
        Serial.println(struct_data.a_field);
    }
}

Once the compiler inlines the call to loop() from main(), the
main program looks like
int main()
{
    init();  // Arduino core initialization
    setup();
    for (;;) {  // inlined loop()
        if (_flag_ISR) {
            _flag_ISR = false;
            Serial.println(struct_data.a_field);
        }
    }
}

And now, since struct_data is not volatile, the compiler can
legitimately optimize the code by avoiding repeatedly accessing the same
RAM location:
int main()
{
    init();  // Arduino core initialization
    setup();
    register int data_copy = struct_data.a_field;
    for (;;) {  // inlined loop()
        if (_flag_ISR) {
            _flag_ISR = false;
            Serial.println(data_copy);
        }
    }
}

And now the program prints only zeros.


Servo start to turn like madman with simple if statement

Please, connect the buttons to the ground and change the code:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int buttonState = 0;         // variable for reading the pushbutton status
int buttonState2 = 0;        // variable for reading the pushbutton status
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin2 = 5;    // the number of the pushbutton pin

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);
  if (buttonState == LOW) {
    myservo.write(173);              // tell servo to go to position
    delay(300);                       // waits 25ms for the servo to reach the position
  }
  if (buttonState2 == LOW) {
    myservo.write(97);              // tell servo to go to position
    delay(300);                       // waits 25ms for the servo to reach the position
  }
}

Pull-up resistors get a high input level when the buttons are open. Otherwise, electromagnetic interference may occur.


Confusion receiving I2C data from magnetic sensor

This is how you send a byte to your slave:

  Wire.beginTransmission(SLAVE_ADDRESS);
  Wire.write(someByteValue);
  Wire.endTransmission();

You must sandwich the writes between a beginTransmission/endTransmission. Output buffer is 32 bytes long, so keep things short.

Wire.write() doesn't write; just put thing in an output buffer, waiting for your endTransmission().

If you need an answer (said, a byte), first you said how many bytes you want and then read them:

  byte pin;
  Wire.requestFrom(SLAVE_ADDRESS, 1);
  if (Wire.available() == 1) {
    pin = Wire.read();
  }

Your are Wire.read()ing, but you are not capturing the return value!

Disclaimer: after requestFrom, you have to be prepared to wait for the data (it may be not inmediatly available). Also, data may arrive in chunks.


Will a delay() function in a void SerialEvent() also stop the code that is running in the void loop() function?

This is the main function of the Arduino core:

int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

serialEventRun() runs the serialEvent() function, if it is assigned,
so yes, a delay in serialEventRun will delay the loop.


There are examples in the ESP8266 library
https://github.com/me-no-dev/ESPAsyncTCP/tree/master/examples


How should I use an optocoupler to control a 12Vcc load with Arduino?

If your load draws a small amount of current (less than about 30 mA current), your 4N35 optocoupler could drive the load directly on 12 volts.

Ignore my use of 4N28 (similar to 4N35). It is the symbol that I had.

It appears that your PNP transistor circuit is something like this :

The PNP transistor circuit can work well depending upon your load current.  The PNP circuit has some problems with the transistor not turning on fully (and won't be described here).  You may not get the full 12 volts to your Load. But, if it works for your load, then be happy with the PNP circuit.

The circuit below is for a NPN transistor circuit  :

Using the NPN circuit allows (in this case) for the transistor to turn on fully, leaving almost the full 12 volts for your Load.

Important Note :  The NPN transistor circuit produces an output that is the LOGIC opposite of the PNP circuit.   Notice that for the PNP circuit, a logic 1 to the input of the optocoupler (LED on) turns on power to your Load.

On the NPN circuit, a logic zero (0) to the optocoupler LED is required to turn on your Load.

Another variation of the circuit is below, and does NOT have the reverse logic situation.  In other words, it will behave like the PNP circuit. When LED is on, the Load will be on  :

You can experiment with the value of R1 in the NPN circuits. You could experiment with lower value, down to 1K (1000 ohms) if you are using a power transistor to drive high current loads.


Is this function subject to memory fragmentation?

Pretty much every use of the String object can lead to memory fragmentation. Especially concatenating and copying objects.

I cover it here: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

You are much better off never using the String class and instead sticking to basic C strings (char arrays).


Can't extract basic data using ThingspeakHTTP

You should use this page, since the other is the front page of the site and more likely to be dynamic:

http://www.aurorawatch.ca/index.php?option=com_content&task=view&id=28&Itemid=47

The XPath is also slightly different. The first tbody in the reported path doesn't actually exist. You should also add /text() to the end of the path to just return the textual content of the node:

/html/body/div[1]/div[5]/table[2]/tr[3]/td/table/tbody/tr/td[2]/span/text()


The AD converter in the ATMega microcontroller (as used in Arduino) converts an input voltage to a number.

This ADC happens to be 10 bit that means 2^10 states which is 1024.

The number 0 (zero) means 0 Volt input voltage.

The number 1023 means the maximum input voltage.

Since 0 is also a value the scale runs from 0 to 1023 making 1024 values.

The scale is linear so 511 means half of that maximum voltage.

What is this maximum input voltage?

That is the ADC Reference voltage. By default the power supply voltage is used so if you run your Arduino on 5 V, then 1023 = 5 V. But if you run your Arduino on 3.3 V, then 1023 = 3.3 V.

There is also in internal reference of 2.56 V (or 1.1 V depending on your Arduino), if you use that then, you guessed it, 1023 = 2.56 V (or 1.1V).

You might have a very fancy external reference voltage already available and if you want to use that, use the external setting and connect that reference voltage to the AREF pin.

If your analog sensor gives 0 to 5 V and your Arduino is also powered by 5 V then you should use the default setting so that the VCC is used as ADC reference.

If your sensor gives a voltage between 0 and 1 V then you could use the internal reference so that more of the 0 to 1023 range is usable. Giving you get better resolution.


How to post HTTP POST requests on my website?

void wifi_connect(){
  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
  delay(1000);
  WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot
  //WIFI_STA It's very important !!!!

  WiFi.begin(ssid, password);     //Connect to your WiFi router
  while(WiFi.status() != WL_CONNECTED){
    delay(1000);
    Serial.print(".");
  }

  Serial.println("Wifi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  return;
}


Well as usual it was something stupid (-__-) I changed the byte array for long and it worked perfectly.

Here is the complete code working():

#include <IRremote.h> // IR Library - Encode/Decode

void irSerial( char SerChar[] ) { // Receive array of characters

    char IDChar[]={'s', 'i', 'u'}; // List of Serial Char to identify position
    String HRD[]={"Power", "Input", "ChaUp"}; // Action reference
    long CodesIR[]={0x61A0F00F, 0x61A048B7, 0x61A050AF}; // IR Codes
    int IRArray = 3; // Size Of The array # Edit

    if ( SerChar[0] == 's' ) { // Compare Array
      for (int CountIR = 0; CountIR < IRArray; CountIR++){ // Loop through array # Edit
        if ( SerChar[0] == IDChar[CountIR]) {
           Serial.println(HRD[CountIR]); // Send String in array - Works
           SendIR.sendNEC(CodesIR[CountIR],32); // Send IR in array position
        }
      }
    }
}


Looking for information and/or how to connect the RF433Mhz module (WL101-341/WL102-341)

You're right not to just go ahead and wire things up. There's a couple of nuances that you need to take into account.
Transmitter

Ignore the EN pin - that does nothing on that module
The transmitter is 1 3.3V device. You need to power it from the 3.3V pin and use logic level (5V -> 3.3V) translation on the Data pin

simulate this circuit – Schematic created using CircuitLab
Receiver
The receiver is much simpler as it is a 5V device:

simulate this circuit
On the Arduino it shouldn't matter what IO pin you use, the Radiohead library should work fine with any of them.  These modules are pretty dumb - you raise DAT high on the TX and DO on the RX goes HIGH. Very simple.


Ring topology by using arduino and Bluetooth

Its probably possible, but I don't think it would be a good idea.

Each Arduino is going to have to forward information it receives that is not for it.  This is a drain on processing power.  Add to that you are going to need to give the devices an identity, so they know what data is for them, and a inform them of the topology of the network so they know how to connect to the adjacent nodes.

Depending on what problem you are trying to solve you might want to look at direct radio coms implementing a mesh network, or the simplest of all solutions Wifi.  You could use an ESP8266 to form an access point and others to connect to it.  I believe there might be a limit to the number of connections an ESP8266 can have at any one time but this could be mitigated by dropping the connection after the message has been sent.


Short answer: do not try to “handle” the millis rollover, write
rollover-safe code instead. Your example code from the tutorial is fine.
If you try to detect the rollover in order to implement corrective
measures, chances are you are doing something wrong. Most Arduino
programs only have to manage events that span relatively short
durations, like debouncing a button for 50 ms, or turning a heater
on for 12 hours... Then, and even if the program is meant to run
for years at a time, the millis rollover should not be a concern.

The correct way to manage (or rather, avoid having to manage) the
rollover problem is to think of the unsigned long number returned by
millis() in terms of modular
arithmetics. For the
mathematically inclined, some familiarity with this concept is very
useful when programming. You can see the math in action in Nick Gammon's
article millis() overflow ... a bad
thing?. For the problem at hand,
what's important to know is that in modular arithmetics the numbers
“wrap around” when reaching a certain value – the modulus – so that
1 − modulus is not a negative number but 1 (think of a
12 hour clock where the modulus is 12: 1 − 12 = 1).

For those who do not want to
go through the computational details, I offer here an alternative
(hopefully simpler) way of thinking about it. It is based on the simple
distinction between instants and durations. As long as your tests
only involve comparing durations, you should be fine.

Note on micros(): Everything said here about millis() applies
equally to micros(), except for the fact that micros() rolls over
every 71.6 minutes, and the setMillis() function provided below
does not affect micros().

Instants, timestamps and durations

When dealing with time, we have to make the distinction between at least
two different concepts: instants and durations. An instant is a
point on the time axis. A duration is the length of a time interval,
i.e. the distance in time between the instants that define the start and
the end of the interval. The distinction between these concepts is not
always very sharp in everyday language. For example, if I say “I will
be back in five minutes”, then “five minutes” is the estimated
duration of my absence, whereas “in five minutes” is the instant
of my predicted coming back. Keeping the distinction in mind is
important, because it is the simplest way to entirely avoid the rollover
problem.

The return value of millis() could be interpreted as a duration: the
time elapsed from the start of the program until now. This
interpretation, however, breaks down as soon as millis overflows. It is
generally far more useful to think of millis() as returning a
timestamp, i.e. a “label” identifying a particular instant. It could
be argued that this interpretation suffers from these labels being
ambiguous, as they are reused every 49.7 days. This is, however,
seldom a problem: in most embedded applications, anything that happened
49.7 days ago is ancient history we do not care about. Thus,
recycling the old labels should not be an issue.

Do not compare timestamps

Trying to find out which among two timestamps is greater than the other
does not make sense. Example:

unsigned long t1 = millis();
delay(3000);
unsigned long t2 = millis();
if (t2 > t1) { ... }

Naively, one would expect the condition of the if () to be always
true. But it will actually be false if millis overflows during
delay(3000). Thinking of t1 and t2 as recyclable labels is the
simplest way to avoid the error: the label t1 has clearly been assigned
to an instant prior to t2, but in 49.7 days it will be reassigned
to a future instant. Thus, t1 happens both before and after t2. This
should make clear that the expression t2 > t1 makes no sense.

But, if these are mere labels, the obvious question is: how can we do
any useful time calculations with them? The answer is: by restricting
ourselves to the only two calculations that make sense for timestamps:

later_timestamp - earlier_timestamp yields a duration, namely the
amount of time elapsed between the earlier instant and the later
instant. This is the most useful arithmetic operation involving
timestamps.
timestamp ± duration yields a timestamp which is some time after
(if using +) or before (if −) the initial timestamp. Not as useful as
it sounds, since the resulting timestamp can be used in only two
kinds of calculations...

Thanks to modular arithmetics, both of these are guaranteed to work fine
across the millis rollover, at least as long as the delays involved are
shorter than 49.7 days.

Comparing durations is fine

A duration is just the amount of milliseconds elapsed during some time
interval. As long as we do not need to handle durations longer than
49.7 days, any operation that physically makes sense should also
make sense computationally. We can, for example, multiply a duration by
a frequency to get a number of periods. Or we can compare two durations
to know which one is longer. For example, here are two alternative
implementations of delay(). First, the buggy one:

void myDelay(unsigned long ms) {          // ms: duration
    unsigned long start = millis();       // start: timestamp
    unsigned long finished = start + ms;  // finished: timestamp
    for (;;) {
        unsigned long now = millis();     // now: timestamp
        if (now >= finished)              // comparing timestamps: BUG!
            return;
    }
}

And here is the correct one:

void myDelay(unsigned long ms) {              // ms: duration
    unsigned long start = millis();           // start: timestamp
    for (;;) {
        unsigned long now = millis();         // now: timestamp
        unsigned long elapsed = now - start;  // elapsed: duration
        if (elapsed >= ms)                    // comparing durations: OK
            return;
    }
}

Most C programmers would write the above loops in a terser form, like

while (millis() < start + ms) ;  // BUGGY version

and

while (millis() - start < ms) ;  // CORRECT version

Although they look deceptively similar, the timestamp/duration
distinction should make clear which one is buggy and which one is
correct.

What if I really need to compare timestamps?

Better try to avoid the situation. If it is unavoidable, there is still
hope if it is known that the respective instants are close enough:
closer than 24.85 days. Yes, our maximum manageable delay of
49.7 days just got cut in half.

The obvious solution is to convert our timestamp comparison problem into
a duration comparison problem. Say we need to know whether instant t1 is
before or after t2. We choose some reference instant in their common
past, and compare the durations from this reference until both t1 and
t2. The reference instant is obtained by subtracting a long enough
duration from either t1 or t2:

unsigned long reference_instant = t2 - LONG_ENOUGH_DURATION;
unsigned long from_reference_until_t1 = t1 - reference_instant;
unsigned long from_reference_until_t2 = t2 - reference_instant;
if (from_reference_until_t1 < from_reference_until_t2)
    // t1 is before t2

This can be simplified as:

if (t1 - t2 + LONG_ENOUGH_DURATION < LONG_ENOUGH_DURATION)
    // t1 is before t2

It is tempting to simplify further into if (t1 - t2 < 0). Obviously,
this does not work, because t1 - t2, being computed as an unsigned
number, cannot be negative. This, however, although not portable, does
work:

if ((signed long)(t1 - t2) < 0)  // works with gcc
    // t1 is before t2

The keyword signed above is redundant (a plain long is always
signed), but it helps make the intent clear. Converting to a signed long
is equivalent to setting LONG_ENOUGH_DURATION equal to
24.85 days. The trick is not portable because, according to the C
standard, the result is implementation defined. But since the gcc
compiler promises to do the right
thing,
it works reliably on Arduino. If we wish to avoid implementation defined
behavior, the above signed comparison is mathematically equivalent to
this:

#include <limits.h>

if (t1 - t2 > LONG_MAX)  // too big to be believed
    // t1 is before t2

with the only problem that the comparison looks backwards. It is also
equivalent, as long as longs are 32-bits, to this single-bit test:

if ((t1 - t2) & 0x80000000)  // test the "sign" bit
    // t1 is before t2

The last three tests are actually compiled by gcc into the exact same
machine code.

How do I test my sketch against the millis rollover

If you follow the precepts above, you should be all good. If you
nevertheless want to test, add this function to your sketch:

#include <util/atomic.h>

void setMillis(unsigned long ms)
{
    extern unsigned long timer0_millis;
    ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
        timer0_millis = ms;
    }
}

and you can now time-travel your program by calling
setMillis(destination). If you want it to go through the millis
overflow over and over again, like Phil Connors reliving Groundhog Day,
you can put this inside loop():

// 6-second time loop starting at rollover - 3 seconds
if (millis() - (-3000) >= 6000)
    setMillis(-3000);

The negative timestamp above (-3000) is implicitly converted by the
compiler to an unsigned long corresponding to 3000 milliseconds before
the rollover (it is converted to 4294964296).

What if I really need to track very long durations?

If you need to turn a relay on and turn it off three months later, then
you really need to track the millis overflows. There are many ways to do
so. The most straightforward solution may be to simply extend millis()
to 64 bits:

uint64_t millis64() {
    static uint32_t low32, high32;
    uint32_t new_low32 = millis();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

This is essentially counting the rollover events, and using this count
as the 32 most significant bits of a 64 bit millisecond count.
For this counting to work properly, the function needs to be called at
least once every 49.7 days. However, if it is only called once per 49.7 days, for some cases it is possible that the check (new_low32 < low32) fails and the code misses a count of high32. Using millis() to decide when to make the only call to this code in a single "wrap" of millis (a specific 49.7 day window) could be very hazardous, depending on how the time frames line up. For safety, if using millis() to determine when to make the only calls to millis64(), there should be at least two calls in every 49.7 day window.

Keep in mind, though, that 64 bit arithmetic is expensive on the
Arduino. It may be worth to reduce the time resolution in order to stay
at 32 bits.


As always, the answer is in the datasheet:

  TXD/PCINT17 – Port D, Bit 1

  TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1.
  PCINT17: Pin Change Interrupt source 17. The PD1 pin can serve as an external interrupt source.

  RXD/PCINT16 – Port D, Bit 0

  RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input regardless of the value of DDD0. When the USART forces this pin to be an input, the pull-up can still be controlled by the PORTD0 bit.

As to what trying to set the output level on the TX pin would have, only experimentation can show.  It's not defined in the datasheet (because who would do it?)


Line 30 in Adafruit_BMP085.h clearly give you the address of sensor. Looks like the address is fixed meaning the only way you can connect several of these sensors is using a i2c multiplexer


How to pause Arduino for 1 millisecond through MATLAB?

The increased in observed delay is due to the time it takes to send the command from MATLAB to the Arduino have its code execute the requested command. In your case the a.digitalWrite. So actual time between pulses using MATLAB's delay is 0.001 pause plus the time of baud rate times the packet size and decoding then execution.

I would recommend not pursuing this solution of the MATLAB controlling the timing of Step Motors, remotely. As this latent coupling will be a frustrating limitation. Noting that for step motors the timing can not afford such latent execution. Hence all the 3D printers and many CNC with Step Motors use Arduino's which get G-Code (motor move commands with destinations) and the Real-time firmware handles the stepping, within tolerances.

I would suggest using something like grbl firmware with step motor shield and then have the MATLAB send the needed G-code. Where there are others with much more features but tailored to 3d Printing. grbl is simpler and straight to the point of moving motors.


Why am I getting "expected primary-expression before '.' token"?

Change three lines right after loop() to these:

  int chk = dht.read(DHTPIN);
  float hum = dht.humidity;
  float temp = dht.temperature;

Change 'DHT' into lower case letters. DHT is the class and dht is the object of the DHT class.

Also you have multiple copy of these libraries: DHT.h and Esp8266WiFi.h. Check your cuurent directory where your Arduino code is and also Documents->Arduino->Libraries directory. These libraries should be in the  Documents->Arduino->Libraries directory.


It is the reference voltage against which all other analog voltages (analog inputs) are measured against.

By default it is the same as the chip supply voltage (5V on most Arduino boards), so the analog inputs can measure between 0 and 5V.

If you connect the AREF pin to a lower voltage, say to the 3.3V pin (for convenience) and set the analog reference to EXTERNAL, you can then measure between 0 and 3.3V.

This is good if you are measuring a smaller voltage and want to get as much resolution in the analog reading. If you leave it at 5V and are measuring only up to, say, 3.3V, you're wasting all the analog reading values between 3.3V and 5V that could go to getting you more sensitivity.


Understanding writing to input pins and pull up resistors

As noted in the I/O-Ports – Introduction section of the ATmega2560 datasheet,

  ... writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register.  In addition, the Pull-up Disable –  PUD bit in MCUCR disables the pull-up function for all pins in all ports when set.

Bits masked with a zero won't be affected.  You can toggle several bits at once if the byte written to the PINx register has several 1's in it.

Pullups are on for an input bit when the data bit is high and the PUD bit in  MCUCR is low.  So as suggested in your comment, pullups for toggled bits would toggle too, if PUD is low.

Regarding the macro code, your reduction looks right.  But note that use of _TOGGLE as an identifier in that code violates section 17.4.3.1.2 of the C++ Standard.  Names beginning with an underscore followed by an uppercase letter are reserved for use by language-implementation software.  They are off-limits for user code.  See What are the rules about using an underscore in a C++ identifier? for discussion.


It looks like you intended the for-loop to run to completion once. If that is correct, just include it and its entire block of code within and at the end of the setup() function. You will still need to provide a loop() function but it can be empty:

void loop(){
   ;
}

If, instead, you wanted the for() loop to be run repeatedly, enclose it in the loop() function:

void loop(){
   for ( k=0; k<=h; k++ )
   {
   ...
   }
}

The setup() function runs once after a power up or reset. The loop function then gets called repeatedly, forever. Put your functional code in whichever one fits your purpose.

The reason for the error message is that, as you've written the for-loop, it is outside of a function, but executable code (as opposed to defining global variables) is only valid within a function.


How do I reduce this down to a smaller, more permanent prototype?

At a bare minimum, you need a power supply, and an AtMega or AtTiny chip.

The AtMega and AtTiny's have an internal clock, 1mhz. It's not terribly accurate for timekeeping purposes (1% error, I think, as opposed to 20ppm = 0.02% for the external clock), but I see you have an RTC, so a 1% drift is probably fine (I can't see your code, so I don't know if the internal time is used for anything). Remember that you will need to adjust your code for the different clock rate, anything that uses anything time-related will run at 1/16th speed (delay, serial comms, etc). You will need to set the fuses to use the internal clock.

If your power source isn't 5v, then you need a transformer.

What type of AtTiny or AtMega you use depends on your code, and how many pins you use. I see 5 pins, they are all used as digital I think? You might get away with one of the 14-pin AtTinys. I suspect your code is probably pretty small. You can probably get away with nearly any AtTiny. To select an AtTiny, go to http://www.atmel.com/products/microcontrollers/avr/tinyavr.aspx

Nick Gammon (who will probably be providing his own answer as I type) has an excellent site on how to put the parts together, at http://www.gammon.com.au/breadboard

This site mentions programming the bootloader. On a low-memory chip, you do not need a bootloader, you can upload your program using SPI (same way as you upload the bootloader in Nick's example). Alternatively, you can use a programmer like the USBASP, which makes the whole process a lot easier. When you build your final board, I strongly suggest putting a 6-pin ICSP header (same as the 2x3 pins on the end of your Arduino board) on, to make reprogramming easier. You plug the USBASP into the 6-pin header, and click File->Upload using programmer.

ADDITIONAL:

If you want your project "really nice", you can design and etch your own PCB. If "good enough is good enough" (which for me it always is), I suggest you use stripboard (also known by it's brandname, veroboard).

In either case, spend some time thinking about your exact layout. Use a computer layout tool, and spend some time working out the best layout. I generally spend at least 5 times as much time on the layout, as I do on building the board - if a project is twice as big, I will spend twice as much time soldering, but at least 4 times as long laying it out.


Put the stuff before setup() together, fix any duplicates:

int mamank=13; <<< pin assignment? If yes, this can be byte
int red=2; <<< pin assignment? If yes, this can be byte
int green=3; <<< pin assignment? If yes, this can be byte
int blue=4; <<< pin assignment? If yes, this can be byte

Put the stuff in setup() together, fix any duplicates

void setup() {
pinMode (mamank,OUTPUT);
Serial.begin(9600);
pinMode (red,OUTPUT);
pinMode (green,OUTPUT);
pinMode (blue,OUTPUT);
Serial.begin(9600);  <<< duplicate, so delete this line
}

Put the stuff in loop() together, then check the desired functionality:

void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
if (sensorValue>550) {
digitalWrite(mamank,HIGH);
}
else if (sensorValue<500) {
digitalWrite(mamank,LOW);
}
delay(100);
// read the input on analog pin 0:
int value = analogRead(A1);
if (value > 500) {
Serial.println("Very heavy Rain");
digitalWrite (red,HIGH);
digitalWrite(green,LOW);
digitalWrite(blue,LOW);
}
else if ((value > 300) && (value <= 500)) {
digitalWrite (green,HIGH);
digitalWrite (red,LOW);
}
else {
Serial.println("Dry Weather");
digitalWrite (blue,HIGH);
digitalWrite (red,LOW);
digitalWrite (green,LOW);
delay(100);
}

}


The way to do this, since there is no digital value in between HIGH and LOW, is to actively create a signal on the pin you can recognise.  Note that if the signal coming in to the pin is a datastream (a sequence of HIGH and LOW) that runs all the time this may not work reliably, but it's good for things like buttons and other simple sensors.

Any signal on a wire has a drive strength.  This is basically how powerful the signal is and how good it is at overriding other things happening on the same wire.  It is closely related to the output impedance of the source (what is sending the signal).  For things like buttons and switches that is basically the value of the pullup resistor used.

To actively sense if a pin is disconnected or not you need to temporarily connect it to a known signal level at the same time as it's connected to the wire (or not connected if it happens to be not connected).  This known signal level has to be of a weaker drive than the source signal by several orders of magnitude.  This ensures that if you try superimposing your test signal over the incoming signal the incoming signal swamps out the test signal and you don't see it at all.  For instance, if your source has 10KΩ impedance (say a button with 10KΩ pullup resistor) then a test signal with source impedance of 1MΩ would be suitable.

Each pin to be tested can be connected to its own 1MΩ (in this example) resistor, and those resistors are all connected to the same extra IO pin:

In this example pin D2 is the test pin, and pins D4-D7 are your inputs.

So under normal circumstances pin D2 is set as an input and completely ignored.  When you come to test the pins, though, you set it as an output.

You then set D2 to be HIGH and read each of D4 through D7.  Any that read as HIGH are candidates for being not connected.

You then set D2 to be LOW and read the pins that read HIGH before.  Any that now read as LOW are disconnected.

You then set D2 back to being an input again so it doesn't interfere with normal operations.

If you just want to know if current is flowing in a wire you can use what is called a shunt resistor.  This is a small resistor (maybe 1Ω) that is placed in-line with the wire and you measure the voltage (using Arduino analog inputs) at both sides of the resistor.  The voltage dropped across the resistor is directly proportional to the current flowing through it thanks to Ohm's Law:

  I=V/R

For instance:

If the voltage read by A1 should be 5V (the voltage the wire is connected to) and the voltage read by A0 should be 4.93V, the voltage dropped by the resistor would be 5-4.93 = 0.07v.  With the 1Ω resistor the current would be 0.07/1 = 0.07A, or 70mA.

With the wire at OUT disconnected there will be zero current flowing since there is no circuit.  So re-arranging the formula above we can prove that we can tell it's disconnected.

If I=V/R then V = RI.  Therefore V = 1Ω × 0A = 0V.  So the voltage dropped across the resistor would be 0V, so A0 and A1 would be equal (discounting any noise). A0 and A1 would both read 5V.  Similarly, if the wire IN was disconnected instead then A0 and A1 would both read 0V.

For sensing higher currents you use a smaller resistance, and for sensing smaller currents you use a larger resistance - this allows for a voltage drop to be generated that is within a suitable range for the sensitivity of the ADC doing the reading.  For the Arduino that's a 10-bit ADC, so it can sense (with a 5V VREF) 5/1024=4.882813mV per LSB.

Note that if you are working with voltages above that at which the Arduino operates you will need to separate or otherwise scale those voltages.  There are special devices designed especially for this task called high side current shunt amplifiers.  They also allow you to use a smaller resistance than you would otherwise need which is less intrusive to your circuit (less voltage drop).


nrf24l01+ does not work with a battery, or very unreliably

According to the datasheet of another 9V battery, I should not expect more than 30 - 50 mA of constant current. This is probably the reason why.

Long story made short: One can not power a NRFL01+ reliably with a 9V battery.
I'd be better off using 2xAA batteries.


After pressing sw1, the first if works. After releasing sw1 (it's a pushbutton), the line while (digitalRead(sw1) == HIGH); will make the code just sit there forever without continuing with the rest of the code until you press sw1 again, which will be caught by the first if unless you release 'sw1' inhumanly fast.
So, once you have pressed and released sw1, the rest of the code with the next two ifs will never run.


You have an ENC28J60 based module. Your code is for the Wiznet-based module. The two are not interchangeable.

See this: http://nathanhein.com/2013/02/getting-arduino-online-with-an-enc28j60/

Good luck.


Resolved: ESP8266 works when arduino UNO reset pin is grounded

The RESET of the UNO puts the ATMega328P (the MCU of the UNO) into an electrically inert state when it is connected to GND.  It is not supposed to be running your sketch when it is being held in reset.  It is, roughly speaking, electrically disconnected from everything else on the board.  This allows you to use the UNO as though it were a USB to TTL serial cable.
If you want to be able to run a sketch on the UNO while it uses the ESP8266, you'll need to not hold reset to GND and you'll also, practically speaking, need to choose a different set of pins for communicating with it, as D0 and D1 on the UNO are the same signals used to for the ATMega328P to talk to the host and used for programming the UNO via its bootloader.  On the UNO, you'd instead need to use SoftwareSerial (or something similar) and pins other than D0 and D1.  [Update: see the original poster's own answer containing the guide they ultimately used, making use of SoftwareSerial on pins 10 and 11]
The ESP-01 can run Arduino sketches using the ESP8266 Arduino core and it may make a great deal more sense to not involve the UNO at all, and instead connect the distance sensor more or less directly to the ESP8266.


As already mentioned by @chrisl, you are creating a new local variable which overshadows your class member.

An easy way to get what you want is to memcpy your initial values into the array:

Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
  NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
  NEO_GRB               + NEO_KHZ800)
{
  begin(); // start the matrix
  show();

  int initialSnakeBoard[5][8] {{1,1,0,0,0,0,0,0},
                        {0,0,1,0,0,0,0,0},
                        {0,0,1,0,1,1,-1,0},
                        {0,0,1,1,1,0,0,0},
                        {0,0,0,0,0,0,0,0}};
  memcpy(snakeBoard, initialSnakeBoard, sizeof(initialSnakeBoard));
}

You can achieve the same thing by utilizing C++11 constructor lists to initialize your members (see here):

Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
  NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
  NEO_GRB               + NEO_KHZ800),
  snakeBoard {{1,1,0,0,0,0,0,0},
                        {0,0,1,0,0,0,0,0},
                        {0,0,1,0,1,1,-1,0},
                        {0,0,1,1,1,0,0,0},
                        {0,0,0,0,0,0,0,0}}
{
  begin(); // start the matrix
  show();
}

You also have an error in your drawSnake routine: You confused the order of the indexes. With snakeBoard[5][8] you declare 2-dimensional integer array with 5 rows containing 8 elements each. Then, snakeBoard[0] will be a pointer to the first row (which has 8 elements). So the first index is y and must only range from 0 to 4 inclusive. The function must be:

void Snake::drawSnake() {
    for(int y = 0; y < 5; y ++)
    {
        for(int x = 0; x < 8; x ++)
        {
            Serial.println("X: " + String(x) + " Y: " + String(y) + " Value " + String(snakeBoard[y][x]));
            delay(100);
        }
    }
}

This then prints all the expected array elements to the the Serial port, as tested on my Arduino Nano.


Why AnalogRead shows value (395) when its on HIGH State ? why not shows 1023 when its high State

There are two problems here - one immediate and one which will be come apparent.
First off, you appear not to have connected the ground pins of the two boards together. This is important. Voltage is not an absolute value, it's a value relative to some other point in the circuit. This is why "voltage" is sometimes called "potential difference". Normally the point in the circuit that voltages are referenced to is termed "ground". Note: there is nothing special about ground, it's just an arbitrary point in the circuit - usually, but not always, the point where the voltage is lowest.  If the ground of the Arduino that it's using to compare incoming voltages against is not the same as the ground that the ESP8266 is using to create its output voltage in relation to, then the Arduino really can't know what the voltage is.
You can think of it as a person standing on the ground. Now I am about 6 feet tall. When I am stood up the top of my head is about 6 feet above the ground. But to someone who is stood on a nearby rise in the ground my head is only maybe 3 feet above the ground. Their ground is not the same as my ground.
The second problem, which will become apparent once you have connected the grounds, is that the Arduino measures voltages between 0 and 5V as values between 0 and 1023. However the ESP8266 doesn't operate at 5V, it operates at 3.3V. The highest voltage it can ever put out is 3.3V. The Arduino can never read that as 1023 because it's not 5V.  Instead it will read somewhere around 675. That is, 3.3V is two thirds of 5V, and 675 is two thirds of 1023.


hexadecimal 1 to float 1 - Compare the float 1 with a predefined float 2 - If the float 1 and float 2 are the same - Print hexadecimal 2

Comparing floating point values is notoriously difficult. This is because floating point is only an approximation.

You should first define an error margin - a value which is how close together the two values need to be before you consider them to be the same.

For example 1.000000 and 1.000001 could be considered to be the same value in many circumstances.

The simplest method is to just subtract one value from the other, take the absolute value of the result, and see if it is below the error margin.

bool almost(float a, float b, float margin) {
  float diff = fabs(a - b);
  return (diff < margin);
}


What is happening when digitalWrite(pinname, LOW) is invoked after pinMode(pinname, INPUT_PULLUP)?

It's pretty explicitly stated there in your quote: if you write a LOW when in INPUT mode it disables the pullup resistor. That's all it does.
pinMode(4, INPUT);
digitalWrite(4, HIGH);

is exactly the same as:
pinMode(4, INPUT_PULLUP);

And
pinMode(4, INPUT_PULLUP);
digitalWrite(4, LOW);

is exactly the same as
pinMode(4, INPUT);

Of course this exploits a peculiarity of the AVR's IO block, but any decent core will emulate that functionality for compatibility with older code.


Not really the answer to your question, but an alternative solution, which has proven to work in my case.
We were working on a line-following robot with an ATMega 328P (Same as arduino, but withouth shields) and thus we wired an shield directly. For the shield we used, we only needed 4 inputs (pwm left, pwm right, direction left, direction right). Try to find out what your shield is using, on which pin, and you can drive the shield directly withouth stacking them (as they then would use the same pin).

My alternative solution would be to use 1 driver. And wire the motors parrallel.
If you choose to use 1 shield, you can stack it. But for other shields you have to check which pins to use. There is no drawback on using one shield, the only thing is that the motor driver will draw more current, but they're basically designed for this.


It is blinkInterval, not blink Interval. You have an space in the name in the declaration:

unsigned long blinkInterval=250; // number of milliseconds for blink
// ....
if((unsigned long)(currentMillis-previousMillis) >= blinkInterval) {


Is there any way to run binary code from RAM?

In my opinion the interpreter idea is much more feasible. The notion of writing, in assembler, code that itself generates machine code, in RAM, and then executes it, is itself incredibly complex.

You haven't said why you want to do this, so this is somewhat of an X-Y problem.

  I don't want an o.s. in the way ...

The normal Arduinos do not have an OS in the way - basically the code you write is what gets loaded onto the chip.


Is it difficult to do high voltage parallel programming using Nick Gammon library?

I have not tried with those instructions, as I have an AVRDragon, but it's a good exercise for precision, since you have to wire lots of pins.

20+ iirc

My guess is that if anything fails, it's likely to be because of a mistake in the wiring.

If you are planning to do it often, you might consider soldering the wires and the ZIF socket to a prototype board, to preserve your mental sanity.


Can we generate 20kHz tone with normal buzzer in arduino?

An arduino is very well capable of producing a 20KHz signal. You can use a PWM signal on one of the PWM pins, generate the signal by alternating a pin high and low with a few microseconds in between or you can use a buzzer with an input signal that can play a continuous tone at a specified frequency. I really can't see if the module you show can generate a tone based on the input.
Detecting a tone, however is somewhat difficult. You need an analog microphone amplifier, an ADC (analog-to-digital-converter) and some processing to detect a frequency in the signal data.
The usual microphone modules that are sold for arduino's are mostly just noise detectors and generate a signal when loud noise is present.


Is it problematic to 'check an input pin' or 'set an output pin' each step?

It does not hurt the Arduino to set an output pin to high if it was already set to high.  If you are concerned about performance, it is more efficient to just set the output pin compared to reading the pin and then setting it only if it's different


No need for a resistor. Just connect black to ground, and red to a IO pin. Use the tone function to specify a frequency.


I tried compiling your three snippets with avr-gcc 4.9.2 at the -Os
optimization level (standard with Arduino) but without -flto. The
results were:

The first snippet generated inefficient code: the ands and shifts were
translated in assembly quite literally, the shifts were done on
16 bits even though chan was declared uint8_t, and the last
shift was even implemented as a loop roughly equivalent to
uint16_t tmp1 = chan & 15; uint8_t tmp2 = 3; while (--tmp2) tmp1 <<= 1;
The second and third snippets were translated identically and
efficiently, using the bst (bit store) and bld (bit load)
instructions to copy the relevant bit of chan into the second
argument of the digitalWrite() call.

Personally I would just write

digitalWrite(_S0, chan & 1);
digitalWrite(_S1, chan & 2);
digitalWrite(_S2, chan & 4);
digitalWrite(_S3, chan & 8);

as digitalWrite() expects an integer as its second argument, and it
interprets it just like the (bool) cast does. If you want to be sure
to always call digitalWrite() with either 0 (LOW) or 1 (HIGH),
then use either your second of third form. The first form seems formally
equivalent to the second, but since it is not an usual C idiom, the
compiler could not catch the optimization opportunity.


Why is Serial.Write that slower when writing x+1 characters than when it is writing x characters?

The Arduino core has a 64 byte transmission buffer.  Characters are sent out of that buffer by the hardware.

When you blast lots of characters out of serial the first 64 just get put into that buffer - almost instantly.

Once that buffer is full your sketch blocks until the hardware has sent a character to make room.

Since it's sending right from the moment you place the first character into the buffer you get a little more than 64 bytes worth of buffering time (64 + the number that have been sent by the time the buffer fills).

From that point on you are entirely at the mercy of the baud rate you have chosen.

To get more predictable throughput (and maximise the speed) you should bypass the Ardiuno core and manipulate the UART registers directly.


arduino suddenly shows “avrdude: ser_open(): can't open device ”\\.\COM3" after last upload

my arduino revived the next day.... don't know why but it works!


Working with Seed BLE Shield and Adafruit Feather BLE

Although the nRF51822 supports Central (master) mode, the Adafruit Feather's firmware only support's Peripheral (slave) mode.

  The Bluefruit LE firmware from Adafruit is currently peripheral only,
  and doesn't run in Central mode, which would cause the module to
  behave similar to your mobile phone or BLE enabled laptop.

  At some point we might consider a new firmware image offering this,
  but since 98% of the uses cases for BLE involved running as a
  peripheral we've concentrated all of our development effort there for
  now.

  https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/faq#faq-2

The HM-11 on your Seeed shield is capable of Central (master) mode though. This means your Uno will play the part that your Android phone was playing when you connected the Feather to the terminal app.

To set your HM-11 to Central mode, run the following AT command.

AT+ROLE1

Example code for the HM-11

Alternatively, you could burn the S120 Soft Device and your own custom firmware onto the Feather's nRF51822. You can find all the docs, tools, and Soft Device images on Nordic's website.


Try to reset manually just after compiling end


I've not done events on an Arduino so this could be a bum steer, but shouldn't the state variable be volatile and protected with a semaphore?
You are accessing it in the main program and in your event/ISR.

Secondly, no offence intended, could you replace your hardware with a bit of tried and trusted hardware to eliminate the remote possibility that your hardware is at fault.


Can the Arduino Uno become an AVR programmer and use the ICSP header to program the target board

First of all, as configured, the RESET pin can not be used as an output pin. In order to use it as an I/O pin, you would have to program the RSTDISBL fuse. But once you do that, as jippie said, it becomes near-impossible to reprogram your Arduino (if you have the socketed through hole variety of the MCU, you could pull it out and put it into a high voltage programmer; in all other cases, it's effectively impossible).

So in theory, you can use the ICSP header the way you suggest. In practice, it's under almost any conceivable circumstance a terrible idea.


Making two points on a tm1637 display blink [ Solved ]

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

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

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

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


I was able to solve the issue with by adding  twi_stop(); to twi.c

base on this website
enter link description here