Why is this RISING interrupt repeatedly triggering? I've set up an ISR to trigger on the RISING edge of pin #2, but I find that if pin 2 is held high, the ISR triggers repeatedly.

Here's a trace of the voltage measured right at the pin:

I can see a little bit of noise, but it shouldn't be enough to trigger multiple pulses. I've tried both INPUT and INPUT_PULLUP modes for the pin; behavior is the same.

constexpr byte kClockPin = 2;
constexpr byte kReadWritePin = 3;
constexpr byte kLedPin = 13;
constexpr int kNumAddressPins = 16;
constexpr byte kAddressPins[] = {/* MSB */52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, 30, 28, 26, 24, 22};
constexpr int kNumDataPins = 8;
constexpr byte kDataPins[] = {/* MSB */45, 43, 41, 39, 37, 35, 33, 31};

volatile bool dirty = false;
volatile uint8_t data = 0;
volatile uint16_t address = 0;
volatile bool read = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(kClockPin, INPUT_PULLUP);
  pinMode(kReadWritePin, INPUT);
  for (byte pin : kAddressPins) {
    pinMode(pin, INPUT);
  }
  for (byte pin : kDataPins) {
    pinMode(pin, INPUT);
  }
  pinMode(kLedPin, OUTPUT);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(kClockPin), OnClock, RISING);
}

void loop() {
  // digitalWrite(kLedPin, digitalRead(kClockPin));
  if (!dirty) return;
  char output[15];
  sprintf(output, "%04x %c %02x", address, read ? 'r' : 'w', data);
  Serial.println(output);
  dirty = false;
  // digitalWrite(kLedPin, digitalRead(kClockPin));
}

void OnClock() {
  read = digitalRead(kReadWritePin);
  data = 0;
  for (byte pin : kDataPins) {
    data = (data << 1) + (digitalRead(pin) ? 1 : 0);
  }
  address = 0;
  for (byte pin : kAddressPins) {
    address = (address << 1) + (digitalRead(pin) ? 1 : 0);
  }
  dirty = true;
}

Turns out the short answer is that I'm still not great at using an oscilloscope.

Longer version is that the noise was very visible at smaller time scales. A filter capacitor had come disconnected from the breadboard in a way that was hard to see, and that was causing a whole bunch of noise. Replacing it fixed the problem.


How to make a custom character on a TFT LCD display? (128x128) I'm currently using the ucglib library. I'm new to arduino and I'm wanting to simply display a lcd smiley I made with the byte generator. I still have some of the original 'font hello world' stuff down the bottom but I'm curious how to make my character work.

I want to make different smileys in different colours but I'm unsure how to go about this as every guide is on a 16x2 lcd and not a tft one. I have an arduino nano that is just hooked up to that lcd display. I'm going to make pressing buttons change the smiley after I've figured out how to actually put a smiley into it. Hope someone can help.

 * LED =   3.3V
 * SCK =   13
 * SDA =   11
 * A0 =    8
 * RESET = 9
 * CS =    10
 * GND =   GND
 * VCC =   5V

    #include "Ucglib.h"  // Include Ucglib library to drive the display

// Create display and define the pins:
Ucglib_ST7735_18x128x160_HWSPI ucg(8, 10, 9);

int smiley = byte customChar[] = {
  B00000,
  B01010,
  B01010,
  B00000,
  B10001,
  B10001,
  B11111,
  B00000
};

void setup(void)  // Start of setup
{

  //ucg.begin(UCG_FONT_MODE_TRANSPARENT);  // It doesn't overwrite background, so it's a mess for text that changes
  ucg.begin(UCG_FONT_MODE_SOLID);  // It writes a background for the text. This is the recommended option

  ucg.clearScreen();  // Clear the screen

  ucg.setRotate180();  // Put 90, 180 or 270, or comment to leave default

  ucg.setColor(0, 255, 255, 255);  // Set color (0,R,G,B)
  ucg.setColor(1, 0, 0, 0);  // Set color of text background (1,R,G,B)
  ucg.setPrintPos(0,24);  // Set position (x,y)
  ucg.print("Welcome");  // Print text or value

  // Draw smiley:
  ucg.setColor(0, 255, 255);  // Set color (0,R,G,B)
  ucg.drawFrame(0, 58, 60, 30);  // Start from top-left pixel (x,y,wigth,height)

void loop(void)  // Start of loop
{

  Variable1++;  // Increase variable by 1
  if(Variable1 > 150)  // If Variable1 is greater than 150
  {
    Variable1 = 0;  // Set Variable1 to 0
  }

  // Convert Variable1 into a string, so we can change the text alignment to the right:
  // It can be also used to add or remove decimal numbers.
  char string[10];  // Create a character array of 10 characters
  // Convert float to a string:
  dtostrf(Variable1, 3, 0, string);  // (<variable>,<amount of digits we are going to use>,<amount of decimal digits>,<string name>)

  // We are going to print on the display everything that is dynamic on the loop, to refresh continuously:

  // Write to the display the Variable1 with left text alignment:
  ucg.setFont(ucg_font_inb16_mr);  // Set font
  ucg.setColor(0, 255, 255, 0);  // Set color (0,R,G,B)
  ucg.setColor(1, 0, 0, 0);  // Set color of text background (1,R,G,B)
  ucg.setPrintPos(9,81);  // Set position (x,y)
  ucg.print(Variable1);  // Print text or value

  // There is a problem when we go, for example, from 100 to 99 because it doesn't automatically write a background on
  // the last digit we are not longer refreshing. We need to check how many digits are and fill the space remaining.
  if(Variable1 < 10)  // If Variable1 is less than 10...
  {
    // Fill the other digit with background color:
    ucg.print(" ");
  }
  if(Variable1 < 100)  // If Variable1 is less than 100...
  {
    // Fill the other digit with background color:
    ucg.print(" ");
  }

  // Write to the display the string with right text alignment:
  ucg.setFont(ucg_font_inb16_mr);  // Set font
  ucg.setColor(0, 0, 255, 0);  // Set color (0,R,G,B)
  ucg.setColor(1, 0, 0, 0);  // Set color of text background (1,R,G,B)
  ucg.setPrintPos(76,81);  // Set position (x,y)
  ucg.print(string);  // Print text or value

}  // End of loop

Simple: you don't.

You only need to create a "custom character" on character-only displays (where you are actively programming a new character into the display's internal character set).

With a graphical display there is no "character" - only graphics.  The graphics library has fonts, which it then uses to convert text into graphics.

To display something that isn't in your currently selected font, just draw it. That could be from a bitmap graphic (there will be examples in your chosen graphics library) or using primitives, like circles and lines.


Communicating to arduino as fast as real-time I'm trying to control some pneumatic cylinders with arduino. I want to do the calculations on pc and then send the command to arduino to control the air flow to pneumatic cylinders. It's very important that arduino receive these commands super fast (in real time if it's possible) so that I can control air flow in millisecond precision.

What is the fastest way to communicate to arduino (Read and write). I tested serial communication and it's very slow in compare to real-time. Is there any specific settings for serial communications that i need to do to increase it's speed? Should I use LAN connection? Or maybe I should use for example Arduino YUN with an OS?

Going over USB will add about a millisecond of jitter to your data in both the sensing and command directions.  Using a part with direct USB rather than then needing to go through a serial link from USB chip to processor could help limit what is added on top of that, but it will still be there.  If you could get a USB high speed solution that would reduce this as the polling interval is shorter, but there are few such solutions for simple microcontrollers.  Ultimately, USB is meant to move a lot of data in a reasonable amount of time - it is not designed to move small messages promptly.

True realtime systems put the processing and the actuation in tightly connected local circuitry. With the increasing isolation of PC processors from external I/O by multiple layers of intermediate architecture on the chip and motherboard, you see very little realtime use of PCs today.  An embedded board with a decent processor and good direct I/O (Beaglebone, maybe the Linux side of a Yun or comparable) would be better, but be aware that multi-tasking operating systems like Linux or Windows are fundamentally in conflict with real-time performance - it takes very complex hacks to make that work, for example running a realtime scheduler directly on the hardware  and having it run an ordinary operating system as a low priority task.

The architecturally cleanest solutions would be to find a way to fit your calculations on a fast single processor - in the realm of Arduino-style solutions perhaps one of the latest in the Teensy series.  Beyond that you are really out of the realm where this could be considered an Arduino question - trying for example to run a realtime scheduler on the Linux half of a Yun is really not related to "Arduino" at all.

One thing that is not clear however is if your system needs to react in real time, or merely to sequence with precise timing.  Mere sequencing is a far easier problem, as you can send the data a bit in advance of need and hold it in a buffer, so that communication latency doesn't delay operations.  A 3d printer could be an example of this - the really complex  calculations are done on a PC, then commands are drip-fed a bit in advance of need to a simpler executive traditionally running on a repackaged Arduino Mega, and that moves the motors with sub-millisecond pulse precision.  Given that there are no realtime inputs to the calculations, their results can also be stored on an SD card for use months later with no PC connection at all.  If your need does reduce to such pure non-reactive sequencing then things are a lot simpler; if it doesn't, then the rest of the explanation here applies.


Good voltage and resistor value for string of LEDs I building multiple parallel strings of 4 LEDs in series.

Since the four LEDs in series have a combined forward voltage of 12.56V at 20mA, and it's powered by 2 AA batteries, I have added a voltage booster.

Now my question is, since I can both choose the output voltage of the boost converter, and the resistor added to each string of 4 LEDs, what would be a reasonable value for both?

I could set the voltage to exactly 12.56V and not use a resistor, but that would probably lead to uneven current spread between the sets of 4 LEDs, as their forward voltage can differ slightly due to manufacturing differences.

On the other hand, I don't want to set the voltage too high, and wast a lot of power.

So what would be an acceptable voltage drop over a current limiting resistor?

Since the relation between voltage and power is quadratic, the obvious answer is "as little as possible".

Allowing for 3% variance in VF gives us just under 13V, so that is a reasonable starting point. Solving for R gives 22ohms, a E24 value. This will result in a 8.8mW loss, which even a 0201 resistor can handle.


Will 5V 2A current input to the power port kill my Arduino? I want to power my Arduino with a mobile charger, the out put is 5V 2A, will it kill my Arduino? And what's the max input current as power source?

"I want to power my arduino with mobile charger the out put is 5v 2apms will it kill my arduino?"

No! It won't. Even tough the reason has been already explained in this other post, I want to add something.

First of all, your question is really common among the ones who, like you (and me), have little/none electrical/electronic knowledge: if you ask such a question, it means you lack the "basic". This is perfectly ok, as we're here to learn "Arduino"... and this (typically) means we're here as the first step towards the electronic world. This is the very reason why I'm writing this answer. So... back to your question....

You're missing a key point, here: the maximum current that your power supply can provide.... is a maximum! And this does NOT means that such a maximum will be given always, and regardless of the devices connected to it!

In other words:

if you have a device that requires a very little amount of current to properly operate (as an example, this DHT22 sensor, requires as little as 2.5mA, or 0.0025 A) and connect it to your 2A power supply, what will happen is that along the wire from your power-supply to the DHT22 will flow only 0.0025 A of current;
if you have 100 (one hundred) DHT22 connected in some exoterical network/schematic, each one requiring 2.5mA of current, in order to power the all of them, concurrently, you need 2.5mA * 100 = 0,25A (or 250mA), that means that again, your power-supply, will be more than enough (to power the all of them, concurrently);
if you have 1000 (one thousand) DHT22, than you'll need 2,5A (or 2500 mA) and... if you need to power the all of them, concurrently, and if you need to stick with your power-supply (capable of "only" 2A)... you'll have problems, as your power supply will not be able to provide the amount of current required by your equipments (Which kind of problems you'll encounter is a matter for a different question!)

To be more specific:

a common/base Arduino MEGA, without any external component connected, requires around 170mA of current;
an common/base ethernet shield, requires 180mA of current;

So, if you plug your 2A power-supply to the USB socket of a MEGA which has an Ethernet shield mounted on its top, than your power-supply will have no problem at all in powering such two devices (as they jointly requires 350mA of current).

you'll be able to power up to 6 of those MEGA+EthShield, as 6 x 350 = 1900mA, which is lower than 2A. Anyway, it's common practice to not require the maximum! It's good-style to not exceed 75/80% of the maximum, as sometimes, based on the quality of your power-supply, some "strange" things start happening when reaching the top!

In the above discussion we talked about "current", without taking into account the "voltage". Anyway, "voltage" is another key-point as "voltage" and "current" are strongly related.

In your OP you mentioned "mobile charger ... 5V" so I bet that you've an USB power-supply, rated at 2A/5V.

People starting playing with Arduino, should use such 5V power-supply to power Arduino trough the USB socket: it has been designed exactly to be connected to a 5V power source, being it an ad-hoc power-supply (with an USB termination) or an USB cable connected to a computer. As for this last case (a computer), please note that:

as for the USB2 specification, every USB2 "host" should be able to provide at least up to 500mA of current at 5V;
as for the USB3 specification, every USB3 "host" should be able to provide at least up to 900mA of current at 5V;

So, supposing you have an USB2 port on your PC and that you connect an USB "simple hub" (an hub without an explicit power-socket) to such port, you can connect only one MEGA+EthShield as this will require 350mA (of the 500mA available). If you have an USB3 port, you can connect 2 of them (and you can also try with three... but with unexpected results).

As for voltage, please note that you can power a tipical Arduino (eg: UNO or MEGA) also via a barrel-jack, providing a voltage inline with what specified by official documentation:

  [...]
  The board can operate on an external supply of 6 to 20 volts. If
  supplied with less than 7V, however, [...] the board may become unstable. If using more than 12V,
  the voltage regulator may overheat and damage the board. The
  recommended range is 7 to 12 volts.
  [...]

The above statement introduce the "voltage regulator". This is another key-component that you should be familiar quite soon. At a very high-level, think to the "voltage regulator" as a magic box that:

from one side (the external world) receive a not-so-stable-and-clean current, flowing in the range 7V-12V;
apply some "magic" to such a current and bring it down _to_a_very_precise_ 5V flow;
provide the resulting 5V potential to the "internal world" of Arduino.

In other words, the voltage-regulator is responsable for providing the exact/constant 5V required by Arduino components, by relying on some "unstable" external current.

You might wonder how is possible to "lower" a 12V "input" to a 5V "output". I really don't know (and, actually, I don't care!). Anyway, a fundamental concept to be kept in mind is that such a reduction will produce "heat"! And the more you lower... the more heat it will produce! And the more current you'll "transform", the more "heat" it will produce! ...and if such heat will not be dissipated properly, chances are high that... something will stop working quite soon!

Having said all the above, please note that I'm well aware that lots of other concepts should have been discussed/introduced and that I have done some big oversimplification in the above description. Anyway, I really think that.... should someone had told me those concepts when I did my first steps in Arduino, my experience would have been shorter (...and easier). Nevertheless... don't blame me if you'll discover that those above will result mostly useless once you'll get slightly expert :-)


Powering USB device from arduino uno? I'm wanting to power a USB device from an Arduino Uno. Forgetting about the two data pins, it just requires power. Using a power meter, I can detect the 5v pin at about 4.95 volts, however I don't have access to any resistors at the moment so cannot test the amperage because it just shorts.

The USB device I want to power requires ~300mA (can't remember specifically). First of all, does the Arduino get 100mA or 500mA when getting power from the USB? Is this changeable depending on the setting on the USB Host (High 500mA, or Low 100mA)?

Secondly, how much would actually be usable? I assume the Arduino itself would require some of that current? Even more if a program where running on it at the same time? (I have no idea how computers utilize power) I would like to just hook up my usb device to ground and 5V with whatever resistors (and any other electrical components) in between to bring it down from 500mA to the required ~300mA.

You'd have to test this but there's a chance you could supply the Arduino using a DC power supply on it's 5V pin. In this case DO NOT TURN YPUR SUPPLY HIGHER THAN 5V, as I don't believe there is any protection and will send the full voltage to the USB.

A safer option would be the Vin pin. Normally you'd want to put 7-12 Volts to this pin but you may want to start at 5V and work your way up just to be safe.

Someone please corrects if I am wrong, but if you never apply more than an external 5V your worst case scenario would be burning out the Arduino but not the USB device.


Why PIN3 stays at 1v3 in a IR emitter project? Here is my very simple IR emitter circuit.
OSI5FU5111C-40 is an infrared LED.

I am using the IRremote library from here
in this simple sketch,

#include <IRremote.h>
unsigned int raw[100]={... *SOME RAW SIGNAL* ...};
IRsend irsend;

void setup()
{
  Serial.begin(9600);
}

void loop() {
  if (Serial.read() != -1) {
    for (int i = 0; i < 3; i++) {
      Serial.print("Start sending ...");
      irsend.sendRaw(raw, 100, 38);
      delay(40);
    }
  }
}

The problem is when I send 1 to serial monitor,

it outputs triple Start sending ... and LED emits no signal.

So I test the voltage between PIN3 and GND before and after sending the 1.
The voltage stays around 1V3.

Would someone please give me some advice? Thank you!

A few things. As somebody else suggested, try a normal red LED and make sure that works first.

Note that your resistor is allowing too much current through the LED. A high-current LED might tolerate 20 mA (thousandths of an amp.) With a 47 ohm resistor, you're pumping 5/47, or about 106 mA into the LED, which is likely more than 5 times what it is designed to handle. You will quickly burn out your LED. You should use a 270 ohm resistor instead.

Also try just setting pin 3 to an output with this line:

pinMode(3, OUTPUT);

And then manually setting that pin to on:

digitalWrite(3, 1);

If the LED lights up, you know the pin is working correctly. Then use the code you posted with the same setup, and make sure your LED flashes. If THAT works, try putting your IR LED back in the circuit.


Microcontroller software shutdown with transistor 2N4401 I am trying to understand why connecting, say, an Arduino digital pin 4 to a 2N4401 pin 2 as well as 5V PSU to 2N4401 pin 1 and Arduino VCC  to 2N4401 pin 3, won't keep power.

When shorting pin 1 and pin 3 on the 2N4401 the MCU is powered on and in-software pin 4 is set to pinMode OUTPUT and HIGHwhich should allow the 2N4401 to let power flow to the MCU for as long as power is available even when the short circuit between 2N4401 pin 1 and 3 is cut.

Instead what happens when the short between pin 1 and 3 is cut, the MCU is turned off instantly.

It's as if the transistor isn't reacting to the pin 4 MCU signal at all.

Could anyone explain why this is happening?

I'm sure I lack a lot of knowledge here and I want to know how I could utilize a 2N4401 to make a SW shutdown system.

Why 2N4401? Why not a MOSFET?
MOSFET's circuits that do SW shutdown are available, but no transistor base SW shutdown circuits are to be found anywhere, and the 2N4401 is all that I have right now.

Update

void setup(){
  pinMode(4, OUTPUT);
}

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

  delay(3000);

  digitalWrite(4, LOW);
}

Your question is rather confusing, but some problems are evident just from looking at the schematic:

The schematic is crap.  I have no idea what you're trying to say with the dotted line between the - terminal of the the battery and the processor GND pin.

The line going thru the middle of the transistor is apparently meant to be the connection to the base, but this is sloppy at best.

It took me a while to realize you have the positive power connection at bottom and the ground at top.  Don't do that.

All these things make your schematic hard to read.  Now that I've had to waste time deciphering the schematic, I'll be more brief once we get to talking about the circuit itself.

You say the transistor is a 2N4401, which is NPN, but you show a PNP.  Huh?  Which is it?

There is no base resistor.  The E-B junction looks like a diode to the driving circuit.  When the digital output tries to go low, it will be held one diode drop below power.  That could damager the digital output or collapse the power supply.

Update

You have edited the schematic to show a NPN, but now you have a chip trying to drive itself thru a emitter follower.  The switch also does nothing at all since both its ends are already shorted together.


Arduino IDE menu doesn't display properly (missing letters) I have just installed newest version of Arduino 1.7.10 from arduino.org.
It has this problem that its menu are not displaying properly - when I hover mouse over items in menu they either disappear completely or some of the letters are missing. Sometimes the whole menu (like 'tools' menu) won't even display. Dialog windows (like "Do you want to save your changes") also suffer from this problem.

I have Windows 7 and I just installed newest version of Java to see if this helps, but it doesn't.
Have any of you had such problem?

I've never had this problem, but here are some things you might want to look at.

Did you install it from an administrator account and use "run as administrator"?  If not, uninstall and reinstall.
Its possible that you are missing a font, god knows which one.  Go and look at the Arduino source on GitHub(?) and find any TTF files and install them.
Does this version support Windows 7?
What version did you have previously? Did you uninstall it before installing this?
If you didn't have a version before this one, uninstall this version go and get 1.5 or 1.6 and install that, then install 1.7 over the top.

Good luck, and keep monitoring the Arduino.org forums because if it is a problem with the app then they will start screaming quite quickly.


What is the difference between file.print() and file.write() From here I think I understand the difference between Serial.write and Serial.print, but is it the same when writing to a file in a SD card for example. Does it mean that File.write saves bytes in the file instead of text?

The File class inherits from the Stream class, which in turn inherits from the Print class.

The Serial class inherits from the Stream class, which in turn inherits from the Print class.

print() and write() are defined by the Print class.

So yes, File.print() and Serial.print() are the same, as are File.write() and Serial.Write().


How to find the difference between two timestamps I'm using this time library to access the properties of unix timestamps like hours / minutes / etc. What I want to do is get the current time, and an estimated arrival time, and find the difference between them in minutes.

Here's my code: (My estimated time is coming from an API as an INT)

time_t timeEstimated = timeInt;
time_t timeNow = now();

But how do I find the difference between these two timestamps in minutes? I'd like to try and avoid all of the conditionals / math that would come with converting to hours / minutes / seconds / dates and subtracting each component if possible.

Unix timestamps are just a count of seconds since a standard
origin (1970.0 UTC), thus a simple subtraction, followed by a
conversion from seconds to minutes:

float minutes_remaining = (timeEstimated - timeNow) / 60.0;


SIM800 or SIM900 library for Arduino I have a SIM 800L module which I am using to send /receive SMS calls.

I just wanted to know whether there is any library suitable for the SIM800 for arduino. I don't need GPRS functionality . I see mostly the arduino shield library but not sure whether it works with the SIM800 module bought from aliexpress.

Can someone help me in get me a library which can be used for the SIM800 .I have tried a lot but not getting a simple library for the same.

Actual Issue :

I am able to make it work with the AT commands using the Serial3 in the arduino MEGA. But when i started integrating with the existing project of ESP8266 and DS3231 somehow the Serial3 read() is not working properly. I tested with Serial3.readString()/ Serial3.read() and all. The CNMI for the SIM800 is 2,3,0,0 which is to direct the incoming message to the Terminal.
If my project is having a simple loop with only Serial3.read, then all messages contents are read properly. If I include the other Serial2 readings which is for the ESP8266, then I am not able to read the full messages from Serial3.I have tried with timer to read serial from the Serial3 for 3-5 secs but now way it is working.

Most likely, the Serial3 buffer is being overrun because you are not reading fast enough. That is why when you use a simple loop, everything works and you get the whole message; very little time passes between reads. The simplest solution to this is to increase the size of the Serial buffer to, maybe, 256 bytes. Search for HardwareSerial.h in your Arduino installation and look for the #defined variable SERIAL_RX_BUFFER_SIZE in the file near the top. Change its value to 256 and save. This should provide enough buffer space to store the entire SMS until you read it.
Alternatively you could change your CNMI settings to push only SMS notifications, which are a lot smaller in size, to the Arduino. Then you can parse the notifications, extract the SMS index and then request the SMS from the SIM800 using the index whenever you wish, making sure to read quickly (you will need to craft a while loop to do this efficiently, with timeouts and all).


How to compose an HTTP GET request URL with key/value parameters I am experimenting with some code running on an ESP8266 board to retrieve data using a web API. I would like to store the host address and key/value parameters (API key etc.) of the GET request as constants/variables (I'm not sure which is better) and then use them to compose the full GET URL.

How can I compose the full URL from separate strings/char arrays including the correct syntax for the key/values pairs?

EDIT: Just adding that I am using the ESP8266HTTPClient library.

The example I have been following uses a basic API URL with no parameters and stores the host URL as follows:

const char* host = "http://somehost.com/dir/1";

(Side question: please explain the difference between const char* host and const char *host if there is one)

Using this simple URL I can successfully retrieve the JSON data using this method:

HTTPClient http;
http.begin(host);
int httpCode = http.GET();
Serial.print("HTTP RESPONSE: ");
Serial.println(httpCode);
if (httpCode > 0) {
  String payload = http.getString();
  Serial.println("PAYLOAD:");
  Serial.println(payload);
}
http.end()

I am looking into using the "ArduinoJson" library to manage the json data instead of String, but am more interested in figuring out how to compose the URL at the moment.

What I would like to achieve is adding key/value parameters stored as variables to the host URL e.g.:

const char* host = "http://somehost.com/dir/1";
char* app = "123";
char* user = "123456"
char* api_key = "XXXXXXXXXXXXX";

And then join them with strings or char arrays to create the full URL, or simply pass the host address plus the parameter values to a function that composes the URL or sends the full GET request(with the parameter "key=var", question mark, and ampersands etc.):

http://somehost.com/dir/1/?appid=123&userid=123456&key=XXXXXXXXXXXXX

This was very easy to achieve in python using the "requests" HTTP library. I was able to store the key/value parameters as a dict and then pass the host address and the parameter dict to the requests.get function and it would compose the URL automatically.

I guess there is more than one question buried in there, but the main one is "what is the best way to compose the full URL without hard coding the whole thing?" An example would be so I could change some parameters such as appid by user input before making the GET request.

I am unsure if I am using the right approach using the character arrays, constants or variables, whether I am using the right approach by trying to compose it manually, and in general what the best practices are for doing this efficiently and avoiding memory fragmentation (which is a problem when using string variables?). This device will be required to run constantly and periodically make these GET requests.

Side question: please explain the difference between const char* host and const char *host if there is one

There is no difference; n.b. the arduino IDE uses C++! If you don't know C or C++ you should learn that first.

  "what is the best way to compose the full URL without hard coding the whole thing?"

This is basically the same question as how do you manipulate, i.e. compose, composite, concatenate, C strings. c string functions

here is a quick example, without error checking, etc.:

const char* host = "http://somehost.com/dir/1";
char* app = "123";
char* user = "123456"
char* api_key = "XXXXXXXXXXXXX";

char urlout[255];

// we are going to start here
strcpy(urlout, host);
strcat(urlout, "/?appid=");
strcat(urlout, app);
strcat(urlout, "&userid=");
strcat(urlout, user);
strcat(urlout, "&key=");
strcat(urlout, api_key);

// urlout == "http://somehost.com/dir/1/?appid=123&userid=123456&key=XXXXXXXXXXXXX"


Power supply to L293D motor driver I am new to Arduino. I'm making a line-following bot. I need to power my L293D module. I know that I can supply 9/12V directly with a battery but I am not sure whether I can supply 5V directly from the 5V pin of the Arduino or I have to use something like an IC 7805.

I am confused because I read that the L293D can cause currents up to 600 mA but the max current for an Arduino Uno pin is only 50mA. This question might seem too novice but it would be of great help if someone could explain me about this or the concept in general.

Thanks in advance.

Check the L293x datasheet.

The L293D IC has two power supply pins. Pin 16, VCC1, is to power the IC itself, ei., its internal logic. Pin 8, VCC2, is to power the motors.

The maximum logic current (ICC1 MAX) drawn by the driver IC at pin 16 is 60mA. Thus, provided you do not have other things connected to the Arduino that can take the current draw above the limit, it is safe to connect VCC1 of the driver IC directly to the Arduino's 5V pin.

The maximum current you can draw from the 5V pin is around 400 mA, or 900 mA, when the Arduino is powered by an external power adapter.

The maximum current sourced or sinked by each driver input pin (xA) is 100 μA, and by enable pins (EN), it is 10μA, which is well within the limit of the Arduino digital pins, 40mA (not 50 mA!). So you can also safely connect Ax and EN directly to the Arduino.

Coming to the last point, the maximum power current supply by driver outputs (xY) is 600 mA. You cannot source or sink more than 600 mA from the 1Y, 2Y, 3Y and 4Y pins. All of this current will be drawn from pin 8 (VCC2), which is connected to the power supply for the motors, which can be a 9V battery. Note that ICC2 MAX is 1.2 mA. Thus, if the supply voltage of the motors is 5V, you must use another voltage source, like 7805 and not the 5V pin of the Arduino to provide VCC2.

To summarize,

You can connect pin 16 of L293D to Arduino's 5V pin.
You can connect pins 1, 2, 7, 9, 10, 15 of L293D to Arduino's digital pins.
You cannot connect pin 8 of L293D to Arduino's 5V pin.


Does Arduino C++ support dynamic arrays of objects My C++ is seriously out-of-date, and I'm working on a project that will be juggling multiple timed actions at the same time, with a menu system to manage the interface and control those timed actions (A multi-channel power outlet controller.)

To do the control I'm planning to have an array of objects that get serviced every time through the event loop. I'm currently using a static C array of objects, but I'd like to use a dynamic C++ array where I can add and remove objects as needed.

I know that some features of the C++ standard library are not supported on Arduino. I think C++ calls smart arrays vectors, and believe vectors are part of the standard library, which isn't supported/fully supported on Arduino. Is there some sort of dynamic array class available?

Even if it would be possible to use dynamic arrays, I would not recommend it, especially not on an Arduino Uno/Mega with only 2 or 8 KB memory.

Instead, create a static data element (e.g. array) that has a (reasonable) maximum number of created elements. This also has the benefit that the constructor will not be called after initialization, thus no variance in execution time (construction of objects can take time).

To manage multiple items within this data element, you can:

Using a ring buffer, this is the normal way to store items on one side, and process them from the other (so-called FIFO, first in first out).
Using a stack (for LIFO, last in last out).
For arrays, keep one variable that holds the number of elements currently filled.


Control a 5 volt water pump with an Arduino I want to control (only on/off) a small water pump (5 V, 200 mA max.) with my Arduino.

I read something about NPN transistor, because the output pins of the Arduino can't supply enough current to the pump. However, I don't know how to choose the right transistor and how to connect it with my Arduino and my water pump.

To use an NPN, connect a power rail of 5V to the pump's positive terminal, and from its negative terminal wire it to the transistor's collector pin. Wire emitter to GND, and place a >=220 ohms resistor between your arduino control pin and the transistor base.

If instead using an N-channel MOSFET, wire load to drain, source to GND, and use a 4K7 pull-down on gate.

Also add a diode, with its anode at the pump's negative terminal, and cathode (white ring) at the positive terminal.


How to read the serial data from a ATMEGA8 on a PC using Arduino? I want to check if a device is working or not. It is a custom made PCB with a Atmega8. It was given to me along with the AVR code. How do I read the data that it sends on my laptop using a arduino, preferably a Arduino Uno?

I tried connecting the output UART pin to the Rx of the arduino, and then provided the common ground. Then I opened serial monitor on my laptop but I a m not getting anything. Is it because the PCB is damaged or am I doing it wrong?

I have the AVR code which was burned on the IC, so I can provide you with more information if you need.

If you connect the TX pin on your device to the 'TX' pin on the Arduino, then load a sketch such as 'blink' that won't initialize the Arduino's own UART, you can use the Arduino's onboard USB-UART adapter to talk to your device.


Using interrrupts with RC522 I have a project using the RC522 RFID module with my Arduino Uno board and miguelbalboa's rfid library. The example code and every other code I find on the internet work pooling the device in order to know if there is a new card present, but I intend to work with a interrupt-driven approach. I have the proper knowledge to do the hardware/arduino part, but I'm having trouble generating an interrupt in the IRQ pin when the card is present. Have anyone succeded on this?

Edit:
Connection:
RST -> 8

SS-> 9

MOSI -> 11

MISO -> 12

SCK -> 13

IRQ -> 2

Code:

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

#define RST_PIN     8
#define SS_PIN      9

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup()
{
  Serial.begin(9600);       // Initialize serial communications with the PC
  while (!Serial);      // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();          // Init SPI bus
  mfrc522.PCD_Init();       // Init MFRC522
  mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
  mfrc522.PCD_WriteRegister(MFRC522::ComIEnReg, 0x7F); //Enable all interrupts
  mfrc522.PCD_WriteRegister(MFRC522::DivIEnReg, 0x14);
  Serial.println(F("Ready..."));
  attachInterrupt(0, isr, RISING);
}

void loop()
{
}

void isr()
{
  Serial.println(F("Interrupt"));
  mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
}

Result:
I only get the "Ready..." on the Serial Monitor, no matter if there is a card present or not.

From your code:

void isr()
{
  Serial.println(F("Interrupt"));
  mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
}

Do not do serial prints inside an ISR! They will eventually hang it. What you need to do is have a volatile variable (eg. a bool), set that in the ISR, and then check that in loop. If it changes, display it. Eg.

volatile bool cardPresent;

void loop()
{
  if (cardPresent)
    {
    Serial.println(F("Interrupt"));
    mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
    cardPresent = false;
    }

}

void isr()
{
  cardPresent = true;
}

The other thing I would do is put a scope or logic analyzer on the IRQ pin and see if it is actually changing. It should trigger the interrupt if it does.


ESP8266: Is it safe to use pin 0? This (maybe stupid) question is bothering me for a long time...

If the pin 0 has to be connected to the ground for uploading a sketch into ESP8266, and after the uploading the chip automatically starts the uploaded sketch (without waiting for reboot with pin 0 to be disconnected), then won't it destroy the chip if I do digitalWrite(0, HIGH) in my sketch? Correct me if I'm wrong, but it should short 3.3V directly to the ground through this pin... Is this problem secured somehow? Or maybe this pin can be safely used for reading only?

Edit:

I have seen it connected to ground directly on every schematic about ESP8266, but maybe I should just use a pull-down resistor? Or maybe the chip already has a resistor before this pin to solve this problem?

You can absolutely use GPIO0 as an output. The ESP will read the state of GPIO0 once at boot (And never again thereafter) to determine what boot mode to enter. During this time it is an input, so, whatever you hook GPIO0 up to must not hold this pin low (Unless you want to enter bootloader mode, of course), at least until the chip boots. As long as you satisfy this condition, you can use the pin for anything else. On my board for example, I use it to drive a simple status LED, and have never seen any issue from it.


How to run 50 IR LEDs off an Arduino UNO? Hi I have 50 camera devices I want to program. Luckily the camera devices have a param.xml file I can import. I have already loaded the param.xml file on each of the camera devices however, now I need to import the param.xml file.

The devices work on IR waves, Usually I would have to import the params on each individual device with a remote but I decided to try and create a neat project where I would attempt to program all of the devices at once using an Arduino.

I would like to buy 50 IR LEDs, make small booster circuits for each LED and then point each one too the receiving module on the camera devices. All the Signal wires would be connected to Arduino pin 3.

I am mostly concerned about all the signal wires connected to Arduino pin 3. is there perhaps some kind of circuit I can use on pin 3 to ensure that this project will work perhaps someone Knows of a better way or has some advice?

Any suggestions will be appreciated.

I am not worried about power because I will connect the IR LEDs + & - to an external Power supply with adjustable current and voltage.

Booster Circuit:

Link To IR Led Datasheet

Link To Transister Datasheet

simulate this circuit – Schematic created using CircuitLab

This is the code I am using with an Arduino Uno and I have tested it with the IR booster circuit and it does work.

#include <IRremote.h>

IRsend irsend;

void setup()
{
}

void loop() {
    for (int i = 0; i < 3; i++) {
        irsend.sendNEC(0x1067E21D, 32); // Login
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 1
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 2
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 3
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 4
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 5
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 6
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10678877, 32); // Right Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x1067A857, 32); // Enter
        delay(1000);
        irsend.sendNEC(0x1067A857, 32); // Enter
        delay(1000);
        irsend.sendNEC(0x10678877, 32); // Right Arrow
        delay(1000);
        irsend.sendNEC(0x1067A857, 32); // Enter
        delay(1000);
    }
    delay(5000); //5 second delay between each signal burst
}

You should put a current-limiting resistor in series with each LED.
You could then try to drive all of those LEDs from a beefy transistor, like
a power MOSFET or a Darlington. Alternatively, you can use a small
transistor for each LED, and then drive all of them from a PNP transistor,
like this:

simulate this circuit – Schematic created using CircuitLab

This way, if you want to drive some of the LEDs independently, you can just
connect an Arduino pin to its R2.

Beware that the PNP reverses the logic: pin LOW turns the LEDs ON.


Bluetooth sending values from two joysticks Is there any good way of sending values from two joysticks from arduino A to arduino B? I tried sending using if statements, so if the Y- or X-axis' value changed then it would send that, but the servo motor on Arduino B went a little bit crazy.

Here's what I've done so far:

//Master Code
void loop()
{
      yVal = analogRead(yAxis);   // read the value of the Right Joystick (value between 0 and 1023)
      yMap = map(yVal, 0, 1023, 0, 255);
      xVal = analogRead(xAxis);     // read the value of the left Joystick (value between 0 and 1023)
      xMap = map(xVal, 0, 1023, 0, 110);

  if(Serial.available() && !(xVal > 505 && xVal < 510)){
      Serial.print('X');
      delay(10);
      Serial.write(xMap);
      }
  if(Serial.available() && !(yVal > 500 && yVal < 520)){
      Serial.print('Y');
      delay(10);
      Serial.write(yMap);

    }
    delay(10);
}

And the Slave code:

//Slave code
void loop(){
  while(Serial.available())
  {
    c = Serial.read();
    delay(5);
    val = Serial.read();
    if(c == 'X'){
        digitalWrite(13, LOW);
        myServo.write(val);
    }else if(c == 'Y'){
        digitalWrite(13, HIGH);
    }
    }

}

Edit: I was thinking that maybe I should do something like a start and stop bit for X and Y?

Edit2: I wrote an if statement in Arduino B because it was reading the value -1, I don't know why, but after the if statement the servo motor hasn't been going crazy and the program works now. I still would like to know if I can do this in a better way. Thanks in advance!

Arduino A

You can read the values from two joysticks as normal and send it like this. This method ensures of no data loss. Ensure that you read the values and store them in appropriate variables and then send it over serial.

// Setting Sensor pins
const int potPin = A0;
const int pot1Pin = A1;

// Creating variables
uint8_t pot;
uint8_t pot1;

void setup() {
// Declearing the pinModes' for sensors
  pinMode(potPin, INPUT);
  pinMode(pot1Pin, INPUT);
// Begining Serial Communication
  Serial.begin(9600);

}

void loop() {
// reading from the sensors
  pot = map(analogRead(potPin),0 ,1023, 0, 255);
  pot1 = map(analogRead(pot1Pin),0 ,1023, 0, 255);

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

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

}

Arduino B

After the data are packed and sent over the serial. You need to unpack it with the other Arduino/device

The code will look like this:

String data; //Store each line of Serial communication
String pot1String = "0", pot2String = "0";
float pot1, pot2;
void setup()
{
  //initialize Serial communication
  Serial.begin(9600);
  //read first package
  if (Serial.available() > 0)
  {
    data = Serial.readStringUntil('\n');
  }
  //Disregard the first reading
  data = "0";
}

void loop() {
  //start reading from serial
  if (Serial.available() > 0)
  {
    data = Serial.readStringUntil('\n');
  }
  String payload = "";
  if (data != "0")
  {
    int offset = data.indexOf("U*"); //This is the header (0x552A)
    if (offset >= 0)
    {
      payload = data.substring(offset + 3, data.indexOf('\n'));
      char value = data.charAt (offset + 2);
      switch (value)
      {
        case 'A':
          pot1String = payload;
          break;
        case 'B':
          pot2String = payload;
          break;
      //Add more case as the project grow
      }
    }
  }
  //convert strings to float
  pot1 = pot1String.toFloat();
  pot2 = pot2String.toFloat();

// Continue with the rest of your project

}

Make sure to use the same baud rate in both sketches

Hope this helped. Ask me if you have farther questions


Arduino Uno with 6x 5V solenoids + 9V battery - Not enough power? I have 6 5V solenoids connected to an Arduino Uno, each of them with a TIP120 transistor, diode and resistor. Exactly like https://core-electronics.com.au/tutorials/solenoid-control-with-arduino.html but 6 times. I'm using a 9V battery connected to the DC input, as well as USB input to my PC.

Now the problem is that if I activate 5 or 6 solenoids at once, the Arduino seems to get interrupted / lose all power for a second (disconnect sound from the PC and no activity). I've tested them one by one and everything works, but I can activate at most 4 solenoids at once.

What am I missing? Do I need more power?

I'm using a 9V battery connected to the DC input

Well, there's your problem. Those 9V PP3 batteries are barely enough to power the Arduino by itself. Add anything like motors and solenoids and you're going to have problems. Big problems.

Ditch the PP3 battery. It's only suitable for very low current devices, like smoke alarms. For anything more you need at least multiple series AA batteries.

Also the solenoids must be powered direct from your power source (or through their own regulator if needed), since the Arduino's on-board regulator will go into thermal shutdown quite quickly with 9V in and a large current draw.


Using Arduino wireless SD Shield to save data to sd card and send to PC over wireless network I'm using an Arduino Mega to monitor the current & voltage input to four different sensors. This works fine - the sensors work as expected and I can view the results via the Serial Monitor or Parallax DAQ for Excel.

SETUP

I also have an Arduino wireless SD shield (now retired) with an XBee module (shown in the below image):

Arduino Shield page
XBee module page

I would like to do the following:

Save the current/voltage sensors' output locally to the SD card
Send the data over a wifi connection for plotting using plotly API (see example  here)

I've seen a bunch of tutorials on how to get the shield to work but can't seem to figure it out:

Arduino WiFi shield example
Instructables
Can I connect to WiFi with an Arduino, "wireless SD shield" and XBee

Here's my code (removed the current/voltage sensor code for brevity):

#include <SPI.h>
#include <WiFi.h>
#include <SD.h>

void setup() {
  // initialize serial and wait for the port to open:
  Serial.begin(9600);
  while(!Serial) ;

  SPI.begin();

  Serial.println("Checking WiFi status:");
  Serial.print("\tWiFi Status: ");
  Serial.println(WiFi.status());

  if(WiFi.status() == WL_NO_SHIELD){
    Serial.println("\tNo Shield present.\n");
  }else{
    Serial.println("\tShield found.\n");
  }

  Serial.println("Initializing SD card:");
  if (!SD.begin(53)) {
    Serial.println("\tSD card initialization failed.\n");
    return;
  }else{
    Serial.println("\tSD card initialization successful.\n");
  }

  // attempt to connect using WEP encryption:
  Serial.println("Initializing Wifi:");
  printMacAddress();

  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void loop() {
  delay(5000);
  // scan for existing networks:
  Serial.println("Scanning available networks:");
  listNetworks();
}

void printMacAddress() {
  // the MAC address of your Wifi shield
  byte mac[6];

  // print your MAC address:
  WiFi.macAddress(mac);
  Serial.print("\tMAC: ");

  for(int i = 0; i < 5; i++){
    Serial.print(mac[5-i],HEX);
    if(i != 5){
      Serial.print(":");
    }
  }
  Serial.println(" ");
}

void listNetworks() {
  // scan for nearby networks:
  Serial.println("** Scan Networks **");
  byte numSsid = WiFi.scanNetworks();

  // print the list of networks seen:
  Serial.print("number of available networks:");
  Serial.println(numSsid);

  // print the network number and name for each network found:
  for (int thisNet = 0; thisNet<numSsid; thisNet++) {
    Serial.print(thisNet);
    Serial.print(") ");
    Serial.print(WiFi.SSID(thisNet));
    Serial.print("\tSignal: ");
    Serial.print(WiFi.RSSI(thisNet));
    Serial.print(" dBm");
    Serial.print("\tEncryption: ");
    Serial.println(WiFi.encryptionType(thisNet));
  }
}

OUTPUT

Checking WiFi status:
    WiFi Status: 255
    No Shield present.

Initializing SD card:
    SD card initialization successful.

Initializing Wifi:
    MAC: 0:0:0:0:0:
Scanning available networks...
** Scan Networks **
number of available networks:0

Not sure what is going on here.

"Arduino Wireless SD shield" is not "Arduino WiFi shield".

The code you have is for the Arduino WiFi shield. But you have Arduino Wireless SD shield for a XBee module. XBee is not WiFi. Zigbee protocol is different protocol then WiFi.

You can save data to SD card with the SD library. Install the library in Library Manager and try the examples.

Arduino WiFi shield:

Note: the Arduino WiFi library is only for this shield and clones


XBee unstable sensor data transmission I am using two XBee Series 2 modules (Zigbee), an Arduino Uno, and a HC-SR04 Ultrasonic sensor to send distance readings from the coordinator XBee on the Arduino to the XBee connected to my computer. I configured the ArduinoXBee as "Zigbee coordinator AT" and the ComputerXBee as "Zigbee end device AT" with the following networking settings:

Coordinator:
PanID: 1234
DH: 0
DL: FFFF

End Device:
PanID: 1234
DH: 0
DL: 0 (so it can only talk to the coordinator)

The problem I am facing is that when I open the End Device terminal on X-CTU, the distance readings I get are accurate yet very unstable. Like it receives the correct readings but the transmission is unsynchronized as it sometimes receives 5 numbers in one transmission and lags for 10 seconds then receives the next bunch and lags for another 10 seconds and so on...

The arduino code is:

#include <SoftwareSerial.h>
const int trigPin = 13;
const int echoPin = 9;

SoftwareSerial xbee(10, 11); // RX, TX

void setup()  {
   xbee.begin( 9600 );
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
}
void loop()  {
long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  xbee.println( distance );
  delay(500);
}

Can anyone help me?

Probably the end device is set into sleep mode. Check the Sleep Mode(SM) and the sleep period(SP) because what I can see is the XBee gives readings for every 10 seconds.


Running Arduino code for Bluefruit LE on bare ATMega328 I need to hook up Bluefruit LE Breakout (nRF8001-based) to ATMega328 chip (to use it as wireless UART), and it seems like the library provided is for Arduino.

What I have is just bare ATMega328 (note the lack of "p"), which I am going to program (using avrispmkii directly). As I already have the MCU assembled, I do not want to change to, say, Arduino Uno to be able to use the library. Most likely, I will "play" with the Bluefruit on Arduino first to get the feel of it, but the code needs to be run on the "bare" ATMega328. The other part of the program (which prepare data to be sent from atmega) is trivial, so I will have no problem to rewrite it from C to Arduino. Porting Adafruit library from C++ to C is probably much more difficult.

Thus, one of the possible approaches is to compile the my code + Bluefruit LE code for Arduino, but upload to the ATMega328.

And this is where I need help:

How to make Arduino (command line tool is ok) to compile to the MCU I have? I guess, the result should be some kind of hex-file for flash (and eeprom?).

And, may be useful, which flags to use with avrdude, if there is anything specific for the Arduino-generated code. (I do not need any bootloaders on the chip, just the program, and I do not have UART-USB connected to atmega).

Of course, please, mention if there are better ways I overlooked, like some Arduino-compatible gcc toolchain to compile C++/C mix into avr code (avr-g++?). Or maybe there is some C-library for the component atmega needs to talk to.

UPDATE: Similar question: http://www.avrfreaks.net/forum/using-arduino-ide-general-atmel-microcontroller-no-bootloader-no-cristal

The UNO is basically just an ATMega328(P). So you can run the same compiled code for the UNO just fine on a bare ATMega328.

You don't have to worry about the P versus non-P version. They are basically the same except for some minor differences concerning low power settings.

You can just select the Arduino UNO board as you target. Select the avrispmkii as programmer. Then instead of Upload, choose Upload using Programmer (in the Sketch menu).


How to create an inverted PWM on the Due via software Hello I am i need of a piece of code that lets me invert a PWM signal of two PWM pins on the due. Example D1 will be 101010 and D2 will be 010101. Is it possible?

Im pretty limited in my options because, doing it externally is not an option because there will be a time where a change in mode is needed and both pins will be sending signal independently. Manually pulling the pins High and Low is also not an option for me because this will make the code blocking other codes.

Not using the Arduino API, no. But you can by direct manipulation of the SAM3X8E registers.

You should study section 38 of the datasheet, where it mentions in the list of facilities:

  Independent Complementary Outputs with 12-bit Dead-Time Generator (Also Called Dead-Band or Non-Overlapping Time) for Each Channel


Need help with EEPROM not storing array values on ESP8266 after restart I am struggling through a program. I am trying to store my uploaded string into an array then write that array to EEPROM. I run the program, upload the new array and store it in the EEPROM. all values display correctly until I reset or power off the device. I am sure I am overwriting or something obvious, but i am breaking down and asking for help.

The read and write EEPROM subroutines are at the bottom of the code. I call the EEPROM_Write() in server.on after parsing the http get.

EDIT: per feedback, removed all but the function, with the EEPROM.commit(); suggestion included... still not working

void EEPROM_Write(){
Serial.begin(115200);
EEPROM.begin(280);
  // store values in EEPROM
  for (int i = 0; i < pwmarray1Size; i++)
  {
    Serial.println(pwmarray1[i]);
    EEPROM.put( EEPROMStartAdress + (i * sizeof pwmarray1[0]), pwmarray1[i]);
  }
  Serial.println();
  EEPROM.commit();
 // EEPROM.end();
}

The ESP has no real EEPROM. Instead the EEPROM class for ESPs uses the flash memory. There is a difference in the implementations of this class between Arduinos and ESPs:
On an ESP every data, that you write, will first be placed in a buffer in RAM. You  need to call EEPROM.commit() to actually write that data to the underlying flash memory.
So you need to add
EEPROM.commit();

to the end of your EEPROM_Write() function, or the data will stay in RAM and thus be lost on power cycle or reset.

I think your problem (besides the commit) lies not in your EEPROM_Write() function, but in the EEPROM_Read() function. If it doesn't work correctly, you are just not able to see, if the data gets written correctly. In your code (which can be seen in the edit history), you have this function:
void EEPROM_Read(){
   //load array pwmarray1 with stored values in EPROM
  for (int x = 0; x < pwmarray1Size; x++){
    EEPROM.get(EEPROMStartAdress + (x * sizeof pwmarray1[0]), pwmarray1[x]);
        Serial.print("loading program from EPROM: ");
    Serial.println(pwmarray1[x]);
    }
}

While in EEPROM_Write() you are calling EEPROM.begin(280) every time, you don't EEPROM.end() it there and you are also not begin the EEPROM in the EEPROM_Read() function. I'm not sure about the underlying implementation, but it started to work for me, when I began and ended the EEPROM object in both functions.
I've written a test code, that I composed party of your code and that for me correctly saves and reads an array via the EEPROM object into the flash memory. It keeps the data over resets and power cycles just correctly. You can control it via Serial Monitor. Just type c (for clearing the array to zero), r (for reading the array from EEPROM/flash) or i (for incrementing all array elements and save them to EEPROM/flash).
#include <EEPROM.h>

#define EEPROM_SIZE 280

int array[60] = {0};
const unsigned arraySize = sizeof array / sizeof array[0];

#define EEPROMStartAdress 0

void setup(){
  Serial.begin(115200);
  Serial.println("///////////////////////////////////////");
  delay(2000);
}

void loop(){
  if(Serial.available()){
    char c = Serial.read();
    switch(c){
      case 'c':
        for(uint8_t i=0;i<arraySize;i++) array[i] = 0;
        EEPROM_Write();
        Serial.println("EEPROM RESET");
        break;
      case 'r':
        EEPROM_Read();
        break;
      case 'i':
        for(uint8_t i=0;i<arraySize;i++) array[i] += 1;
        EEPROM_Write();
        break;
    }
  }
}

void EEPROM_Write(){
  EEPROM.begin(EEPROM_SIZE);
  // store values in EEPROM
  for (int i = 0; i < arraySize; i++)
  {
    EEPROM.put( EEPROMStartAdress + (i * sizeof array[0]), array[i]);
  }
  EEPROM.commit();
  EEPROM.end();
}

void EEPROM_Read(){
  EEPROM.begin(EEPROM_SIZE);
  for (int x = 0; x < arraySize; x++){
    EEPROM.get(EEPROMStartAdress + (x * sizeof array[0]), array[x]);
    Serial.print(" ");
    Serial.print(array[x]);
    }
  Serial.println();
  EEPROM.end();
}

Removing begin() and end() from EEPROM_Read() and also end() from EEPROM_Write() gives me the same results, that you described as your problem.


Getting all data of my JSON object from Serial.read() at once I'm new to Arduino and I'm building a project that fetches data from a website (using ESP8266) and then transfers them to my Arduino UNO via serial port.
Data coming from ESP8266 every 20s - [{"x": 0,"y": 0,"rgb": [255, 200, 174]},{"x": 1,"y": 0,"rgb": [255, 200, 174]},{"x": 2,"y": 0,"rgb": [255, 200, 174]}]
But when I print the data like this

void loop() {

  if (Serial.available()) {
    Serial.write(Serial.read()); // This line prints only one character out of whole string

    data =  Serial.read(); // so this doesn't work

    DeserializationError error = deserializeJson(response, data);
    if (error) {
      Serial.print(F("deserializeJson() failed: "));
      Serial.println(error.f_str());
      return;
    }
    for (JsonObject elem : response.as<JsonArray>()) {
      int x = elem["x"]; // 2, 2, 2
      int y = elem["y"]; // 2, 2, 2
      JsonArray rgb = elem["rgb"];

      int rgb_0 = rgb[0]; // 255, 255, 255
      int rgb_1 = rgb[1]; // 255, 255, 255
      int rgb_2 = rgb[2]; // 255, 255, 255
      //Serial.print(x);
    }
  }
  delay(1000);   //then it waits 1 second and goes from the start
}

How can I make it to get the whole string and save it into a variable?
Thanks, much for answering.

I was going to put this as a comment, but maybe it belongs as an answer:
For what it's worth, ArduinoJSON seems to be able to deserialize directly from a stream, i.e. Serial, which may obviate the question as asked.  Presumably it knows where to stop deserializing, because it knows when it has received an entire JSON object; being a proper JSON parser, it can probably work this out better than you can without, you know, writing a JSON parser.
The following was just thrown together, now the author is here you should probably just follow their direction, but here's the code anyway:
#include <ArduinoJson.h>

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  Serial.setTimeout(30000);
}

void print_transmission_counter( {
    static unsigned long received_object_counter;
    Serial.println(F("\n\n\n\n"));
    for (int i = 0; i < 30; ++i) {
        Serial.write('-');
    }
    Serial.write('[');
    Serial.print(received_object_counter++);
    Serial.println(']');
}

void loop() {
    static StaticJsonDocument<256> json_doc;
    static bool led_state;

    print_transmission_counter();

    const auto deser_err = deserializeJson(json_doc, Serial);
    if (deser_err) {
        Serial.print(F("Failed to deserialize, reason: \""));
        Serial.print(deser_err.c_str());
        Serial.println('"');
    } else  {
        Serial.print(F("Recevied valid json document with "));
        Serial.print(json_doc.size());
        Serial.println(F(" elements."));
        Serial.println(F("Pretty printed back at you:"));
        serializeJsonPretty(json_doc, Serial);
        Serial.println();
    }

    // Just give some visual indication that the loop is progressing
    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
}

//  vim:sw=2:ts=2:et:nowrap:ft=cpp:


Testing Arduino with Visual Studio Community 2013 raise LNK error I have two projects in my Visual Studio Community 2013 solution.

I created a project for Arduino, and create another project for Test. When I run the project tests without adding the Arduino project reference, it run ok, but when I add the Arduino project reference I get it error:

LNK1561: entry point must be defined D:\VisualStudioArduino\PrinterProject\LINK PrinterProject

What is the entry point for Arduino project?

It does not generate any file like a dll or main file?

What can I do to solve this error?

UPDATE I

I also tried this configuration in the Arduino Project but I get the same error:

Properties -> Linker -> System -> SubSystem to "Windows (/SUBSYSTEM:WINDOWS)"

UPDATE II

I am using Visual Micro extension. But the problems is when I try to compile the Test project. Then I recreate this scenario with a C++ console application and create a simple class, and create a test project and added the console application reference to test project and it worked. Then my doubts is about to how do I configure a Test Project to test my Arduino project.

I use Visual Studio Community Edition 2013 along with the Visual Micro extensions, which I think is what you need as the "missing link" between VS and Arduino.


Arduino ISR timing question Im trying to understand how the Arduino ISR keeps track of timing between pulses stored in a variable, if that variable is latter used.

Say, for example, you have a magnet mounted on a circular object, that passes a reed switch. Using this to trigger the ISR that calls a function that would have something like counts++ in it, then storing that value in a variable.

If that varible is used latter to turn on a motor, for example, according to the count capture, how does the arduino MCU know the freq or timing to output the count or pulses of the magnet passing the reed switch, at the same frequency that the counts were received? For example, a magnet mounted on a 2 inch dia shaft would turn slower past a reed switch than one mounted on a .5 inch shaft, or one could vary the speed of the magnet past the reed as they wish. So how does counter++ keep track of this freq? is it reading the attachinterupt pin (or is the function that is being called, keeping track) or does the ISR time stamp each pulse it receives and store that interval in the declared variable? so when the variable is used again, it has this interval stored in it?

To be more clear, if it takes one second for the magnet to complete one revolution, how does the MCU know it took one second and store this, along with the counts of the revolutions?

Thanks for any help

All the interrupt does is count. It has no concept of time.  For instance:

volatile uint32_t revolutions = 0;
void count() {
    revolutions++;
}
....
attachInterrupt(0, count, FALLING);

will just count up 1 every time the interrupt triggers.

To be able to convert that count into something meaningful you have to manually introduce the concept of time - that is, the count of "revolutions" (for example) between two points in time.  And it's up to your sketch to implement that.

The simplest way may be:

// For anything more than an 8 bit value on an 8 bit machine
// make a critical section to save and reset the count
cli();
uint32_t savedResolutions = revolutions;
revolutions = 0;
sei();

Serial.print(savedRevolutions);
Serial.println(F(" revolutions per second"));

// Introduce the concept of time - this will
// make it get the count once a second.
delay(1000);

Of course, instead of delay() you can use millis() in much the same way as the BlinkWithoutDelay example in the IDE.

It is possible (as long as you're not counting too fast) to incorporate the time element into the interrupt routine by keeping track of the time in a variable:

volatile uint32_t rps = 0;

void count() {
    static uint32_t revolutions = 0;
    static uint32_t timestamp = millis();

    revolutions++;

    if (millis() - timestamp >= 1000) {
        timestamp = millis();
        rps = revolutions;
        revolutions = 0;
    }
}
....
attachInterrupt(0, count, FALLING);

Then you can just reference the rps variable at any time to get the revolutions per second. Again it should really be queried inside a critical section to prevent the value being changed while you're actively reading it...

cli();
uint32_t myRPS = rps;
sei();

Serial.print(myRPS);
Serial.println(F(" revolutions per second"));


Can I connect an SD card shield to Digispark ATtiny85 board? I have a Digispark ATtiny85 Arduino board (as shown in the picture). Can I connect a SD card shield to this board as a normal Arduino? How can I do that I'm new to this field?

In short I am going to say NO.

The flash is too small to adequately run the SD library as well as the rest of your Arduino code.

The RAM is also underpowered for what is needed to properly access files on an SD card.

Having said this, I am sure there are some clever software engineers that could write a cut down SD card library to do limited commands. Overall this is too hard for the beginner - Just buy an Arduino Uno/Mega/Due and avoid the unnecessary hassle.


Can I get the arduino to run ESP8266 code? So I got this water flow sensor that measures the flow of water. I also got an ESP8266 module to help me make HTTP requests.

So as far as I know, one must set the board type to Generic ESP8266 and upload a sketch that the ESP8266 runs.

However, how can I write code in such a way that when the water flow goes over say 30 Litres, it makes a GET request to the Api that alerts the user? I am not able to use both the modules in one sketch. Any possible methods?

I think you have a fundamental misunderstanding of what you are working with.

There are two ways of working with an ESP8266:

Directly program the ESP8266. This involves installing the ESP8266 boards package and uploading the code to the ESP8266. No Arduino is required (unless you want to use one as a USB to UART adaptor for the programming).
Use the ESP8266 as a serial peripheral to an Arduino. You program the Arduino, not the ESP8266, and no special software is needed (unless you want to use an ESP8266 library for Arduino). You send the ESP8266 AT commands to get it to do internet related operations. You are still working with an Arduino, so that is the board that should be selected.

It sounds like you are wanting to do (2) but are mistakenly trying to so (1).

Option 2 does rely on the ESP8266 having the AI Thinker AT firmware installed on the ESP8266, which most come preinstalled with. If you have uploaded code to your ESP8266 using the ESP8266 boards package that firmware will have been replaced with your code and you will need to put the original firmware back on. There's many tutorials on the web showing you how.

If you do want to program the ESP8266 directly then it's the ESP8266 that you need to program, not an Arduino. Everything will be done by the ESP8266 - the GET request, the water flow sampling, the decision making, etc. The Arduino will be relegated to your bits box where it will gather dust.


Serial sensors and the Yun I am involved in a project that is going to measure PH and chlorine in a swimming pool.  The plan is to use a Arduino Yun. The sensors we are going to use are connected using serial.  Since we may be using multiple sensors, is there any difference in reliability, latency, known issues (bugs) of using software serial versus pin0 and pin1? Is it any way to avoid software serial pitfalls (if there are any)?

The Yun is a bit different to other Arduinos. The main microcontroller is a ATmega32U4 with a build in USB interface. This is used for the connection to the PC so the single USART is not used for this purpose.

However, the single USART is used for connecting to the built in wireless processor. This means that you can't use the wireless and hardware serial at the same time. I presume you are using the Yun for wireless, so disabling this is not desirable.

SoftwareSerial is relatively good, but does consume a lot of cycles. You can only listen on a single port at a time. It is possible to use pin change interrupts to listen for activity on multiple ports and switch to the one required, but this requires that the other end can wait for a response.

SoftwareSerial will tie up the microcontroller whilst sending, which can lead to problems when supporting low baud rates. Conversely, because it is CPU heavy, it can also have problems with high baud rates. There is a window, between 9600 and 38400 baud, where it seems to work best.

There is another software serial version called AltSoftSerial. This works faster than SoftwareSerial and can transmit and receive at the same time.

You can use the USART, SoftwareSerial and AltSoftSerial all at the same time. Be warned that because all three of these use interrupts and some use timers, you are highly likely to end up with complex, hard to debug interactions.

Note than in older versions of Arduino (pre v1), SoftwareSerial was very, very poor. It was replaced entirely with "NewSoftSerial".

Sensors are often have very basic USART hardware with limited buffer sizes, and drop data when they aren't serviced in a timely manner.

I am not a massive fan of the Yun. It isn't popular, the wireless is still relatively hard to use (compared to the TI CC3000), and the wireless interface uses valuable pins. Personally, if I was to work on a project that required multiple serial interfaces, I would either

Use a board with multiple USART, such as a ATmega1280 (2 USARTs) or ATmega2560 (4 USARTs) and a CC3000 (SPI connected) wireless board.
Use SPI/I2C->USART bridges. This allows a single SPI/I2C port to control multiple USARTs. Sparkfun sell one, there are many others available.

Be cautious of falling into the trap of using hardware because it is what you have available.


How to use Arduino as RC Receiver I want to use Arduino as my RC receiver. I will generate PPM signal from Arduino. Then I will send generated signal to my OpenPilot CC3D. I fetched following image from OpenPilot GCS. The diagram shows to use input 6.

Following is the image of my CC3D. The cable colors does not correspond to each other.

Which input cable should I connect to Arduino?
How should I connect black(ground) and red(5V) cables to Arduino:

EDIT this answer explains how you can put a Arduino between a (1 ppm pin per channel) RC receiver and a RC receptor. This allows for smart features (like autonomous control with RC overrule, or sensor based corrections,..)
It seems it is not the question of op.

What you want is easy but there are some pitfalls.
I can make a long story short by these links

http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with.html
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with_20.html
http://rcarduino.blogspot.com/2012/04/how-to-read-multiple-rc-channels-draft.html

if you are serious about RC this may be of your interest to
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with_25.html

I also converted this info in a library you can find here:
https://github.com/jantje/ArduinoLibraries/tree/master/RCLib

And for stackexchange policy here the hightlights.
If I look at the picture you added you have a 6 channel ppm receiver. Each ppm channel you want to read must be connected to a interrupt enabled pin of your arduino (The drawbacks of software enabled interrupt pin is another discussion).
The high time of the ppm tells how high or low your lever is on the remote control.
You can then have arduino do with this info what you want. For instance use the servo library to generate a ppm signal out to servo's and ppm driven motors.


Arduino Yun receives UDP packets but prints them with gibberish Arduino Yun is set to receive UDP packets. It receives those data with some gibberish.
How is all set up: Arduino Yun (acts as a server) is connected through Ethernet to a PC which is (through WiFi) connected to the router. Another PC (acts as client), is also connected to the router (through Wifi).
Client uses netcat to connect to Arduino Yun. I write something and press enter. The packets are received by the Arduino Yun with some gibberish. For example, I write "test" and press enter, but this is what I receive on the Arduino Yun:

Sometimes gibberish characters are different, but always exist. This is what Wireshark monitors when I send the "test" packet (with netcat) to my Arduino Yun:

It shows that indeed I send only "test", so the gibberish is created on the Arduino side, I suppose.
This is my sketch (not the entire code, but the important part):
void loop() {
  int udp_received = Udp.parsePacket();
  if (udp_received) {
    char udp_buffer[16];
    udp_buffer[15] = '\0';
    Udp.read(udp_buffer, 15);
    Serial.println(udp_buffer);
  }
}

I use BridgeUdp.h
Any insights appreciated.

You are receiving a small packet of about 5 or 6 characters (depending on your line ending). That is being received into a 16 byte buffer which has contents unknown.  So the first 5 or 6 bytes of the array have valid data in it. The rest is whatever was already in there.
You need to use the return value of Udp.parsePacket() to tell you how many of the bytes in your buffer are actually valid received bytes and only print those.
The simplest way:
Serial.write(udp_buffer, udp_received);


Can we use analog input pins as a parameter of analogWrite() for PWM? int led = A1;

void setup() {
   pinMode(led, OUTPUT);
}

void loop() {
  analogWrite(led, 188.7);
  delay(100);
  analogWrite(led ,0);
  delay(100);
}

Like this and it works! I mean I am getting the exact voltage as calculated while mapping 5V between 0-255

On the Nano, only the pins D3, D5, D6, D9, D10 and D11 are PWM-capable.
If you try to analogWrite() to any other pin, you will get either
0 V (if you write any value less than 128) or 5 V (for any
other value).

If you get 3.7 V when 5 V is expected, that's because either
your power supply is too weak, or you are putting too a heavy load on
the pin.


Why my light meter's values are blank on Arduino Serial Monitor? I tried to represent the values of TSL 2591 Adafruit light sensor on my Arduino Serial Monitor, but for some reason, I could not do that. The Arduino Serial Monitor just enters some blank values and scrolls down.
Here is the code:

uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
y = float(tsl.getLuminosity(TSL2591_VISIBLE));
z = (y, DEC);
Serial.write((byte)z);

x, y, and z are floats initially.

Use Serial.println(x); to print a number as text. Function write() sends the raw byte and Serial Monitor shows the character with that ASCII code, which is not valid or a not visible control character.

For the z = (y, DEC); from Wikipedia:

  In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

so z is always 10 (value of constant DEC), which is ASCII code for the new line character


Is there a library to use Amazon IoT services on any Arduino? I started to work with AWS IoT today, which offers a MQTT based connection to their web service. They officially only have a demo for the Arduino Yún, which is rather expensive. Has someone managed to get it running (e.g. with a NodeMCU with a ESP8266)?

You can try the AWS IoT Embedded C SDK, that is for more general devices.
Other Arduinos requires a crypto library and a device powerful enough, maybe PI, to support the authentication process...
At this time they have no crypto library like the YUN SDK, for other Arduinos...

Try it...


Connecting breakout board to Arduino with UART I'm using a DigiX (Arduino Due based 3.3V) board to connect to a GPRS/GSM SIM908 breakout board. The SIM908 EVB board has the following pins on its RS232:

I've got all three UART TX lines hooked up to the RX Lines (and RX to TX) on my Arduino but the board keeps resetting, which I would guess is some sort of voltage issue (I turned the board off immediately). However there are three MAX3232s on the underside of the board, which I thought would have made it so I could just connect the lines directly to the Arduino. Does anyone know why this might be happening or how to properly connect these two devices?

Additional info:

Pinout of the DigiX.

Schematic of the DigiX.

(The below links are in Chinese):

Here is a SIM908 Hardware guide.

The full schematic of the breakout board.

Both the DigiX and the SIM908 are natively 3.3V boards. They should be able to connect to each other directly.

For some reason, the SIM908 breakout seems to only offer RS232 level serial outputs for the GPRS and GPS. On U3 (the SIM908 module itself) Pins 68/71 offer 3.3V levels for the GPRS (GPRS-TXD and GPRS-RXD) and 15/16 offer 3.3V levels for the GPS (GPS-TXD and GPS-RXD).

These are converted to RS232 levels by the MAX3232 and presented on J3 and J13. I can't see any point where the 3.3V signals are presented on a connector.

You could either:

Breakout the 3.3V signals onto connectors by modifying the SIM908
breakout board.
Build a level converter to take the 3.3V signals from
the DigiX to RS232 and then connect them as before.

You may have damaged the DigiX board connecting RS232 levels directly to it however. The ARM based Arduinos are far less tolerant of voltage abuse than the ATmega based Arduinos.


Constant ADC sampling rate on ESP8266 or ESP32 I want to sample Sound input with either an ESP8266 (preferred) or ESP32. As I'm using a low pass filter anyway, a sample rate of 1000-2000hz would be totally ok. What is more important, is that it is constant. Can I use DMA for that? If so: how? Or should i go via Timer interrupts?
I know about the wifi issue on the ESP8266, but I intend to just turn Wifi off as I don't need it for this project.

You have several options for controlling the sampling rate.

Software only

This is the simplest, and the previous answer got it almost right. Here
is my take:

const SAMPLE_INTERVAL = 500;  // 500 microseconds

void loop() {
    static unsigned long last_sample_time;
    if (micros() - last_sample_time >= SAMPLE_INTERVAL) {  // note 1
         last_sample_time += SAMPLE_INTERVAL;  // note 2
         // Take your sample here.
    }
}

Note 1: On the AVR-based boards, millis() is not accurate to the
millisecond. It tends to get late, then compensate for this by jumping
by two milliseconds at once. For controlling a process that should
happen every 1 ms exactly, millis() is very clearly not
suitable. I do not know how good is the ESP8266's millis(). It may
well be better than the AVR version. However, even a perfect millis()
will not be good for anything faster than 1 kHz.

The solution to this problem is pretty trivial: just count the time in
microseconds instead of milliseconds. The only drawback of using
micros() is that you cannot measure durations longer than about
71.6 minutes, which in turn means you cannot use it for sampling at
any rate slower than 233 µHz. Obviously this is not something you
should be concerned about. Note that the micros() rollover is not an
issue as long as you are sampling faster than the rollover period.

Note 2: It is impossible to have a steady sampling rate if it is
controlled by software. The best you can hope for is a tight control on
the average sampling period. This is accomplished by updating
last_sample_time as

last_sample_time += SAMPLE_INTERVAL;

Note that this variable holds the time when the last sample was supposed
to be taken, not the time it was actually taken. The sample was probably
taken a little bit behind schedule, as anything the CPU does takes time.
Updating last_sample_time this way means that these timing errors are
not cumulative. They would be cumulative if you did it in the “Blink
without delay” style, namely

previousMillis = currentMillis;

The drawback of this software method is that it inherently has a
significant amount of jitter. The program tests the current time only
once per loop iteration, and it may have other things to do within that
loop that adds to its execution time.

Software triggered by interrupts

I have never programmer an ESP timer but, if you can, it should provide
you better timings than the software-only version. Have the timer
deliver an interrupt at the desired sampling period, and use the ISR for
triggering the ADC. You may wait for the result inside the ISR, store it
in RAM, and set a flag to tell the main loop that a new sample is
available, as in

volatile int analog_sample;
volatile bool analog_sample_valid;

ISR(whatever_timer_interrupt)
{
    analog_sample = analogRead(ANALOG_PIN);
    analog_sample_valid = true;
}

void loop()
{
    if (analog_sample_valid) {
        int analog_sample_copy = analog_sample;  // note 1
        analog_sample_valid = false;
        // handle analog_sample_copy here
    }
}

Note 1: On an 8 bit Arduino, you would have to do this with
interrupts disabled. You shouldn't need to disable interrupts on a
32 bit platform.

This method should significantly reduce the jitter compared to the
software-only version. Now the sampling doesn't have to wait for the
program to run through the loop and reach the point when the time is
tested. Instead, whatever the program is doing, it will be immediately
interrupted for doing the sampling. Well... almost. From time to time it
will happen that the interrupt fires when the program is running with
interrupts disabled. This may be the case if it is already servicing
another interrupt. When this happens, the sampling will have to wait
until interrupts are enabled again. You end up with a jitter that is
most of the time a small fraction of a microsecond, and then
occasionally a sample is late by several microseconds.

Hardware only

On an AVR, you can configure the ADC to be automatically triggered by a
timer, or even to automatically trigger itself in the so called “free
running mode”. I do not know the specifics of the ADC in the ESP8266.
You may want to read the datasheet and see if it offer similar
functionality. If you can enable ADC auto-triggering, then you will have
cycle-accurate timings. The steadiness of your sampling will be just
as good as the quartz crystal clocking your MCU. No software solution
can ever come close to this level of perfection. The only drawback of
this method is that you will have to study the datasheet of your ESP in
order to implement it.


When it says the Uno has logic level at 5 V is that also true of a bareduino/breadboard Arduino? I want to hook up ESP8266, which has a 3.3v logic level to my bare-bones Arduino (basically a minimal interface for the ATmega382P IC).

I can power my circuit at 3.3 V without a 5 V regulator so will the voltage of the logic level also be 3.3 V?

I don't think there is a tiny boost converter in the IC... but I'm uncertain.

The logic level is the same as the voltage you supply the chip.

You can think of the IO pins as tiny switches that either connect the output pin to the supply voltage or to ground (when in output mode) or compare the incoming voltage to an input pin to a percentage of the supply voltage (typically <0.3×Vcc for low and >0.6Vcc for high)

So yes, if you run the chip at 3.3V the logic level will be 3.3V logic (or more specifically < 1.1v for low and > 2.2v for high).


MP3 Shield stacked on DMX Shield - Arduino Uno We are using Arduino Uno revision 3, with TinkerKit DMX Shield rev. 4 and Sparkfun Mp3 Shield.

We uploaded the Mp3 Shield example called FilePlayer and after we open the serial monitor, the interface is there and working. The problem is that it won't output the music from the SD card.

If we ONLY stack the Mp3 Shield onto Arduino, it works.

Is there some king od incompatibility between the DMX and Mp3 Shield, and if there is, what would be the solution, maybe some kind of bypass, since we aren't that familiar with what pins the DMX shield uses for it's purpose. ATM the Tinkerit site is down so we can't acess the TinkerKit DMX Shield datasheet.

Yes, overlapping is a problem, by default the MP3 Shield uses digital pins 2(DREQ),6(mp3CS),7(mp3DCS),8(RST),9(SD-CS),11(MOSI),12(MISO),13(SCK)

The Tinkerkit DMX Master Shield R4 uses 2(RE-ENn),3(VTX),4(VRX),5(DE-EN),6(D6)

So there are conflicts with D2 DREQ vs RE-ENn and D6 mp3CS vs D6.

The DMX Master Shield basically converts the UNO's serial to DMX. If nothing is at first included into the Sketch for this, then the problem is with only D6. Leave this jumper OFF. And I suspect the MP3 Shield will work stacked.

To use them together you can move the pins, as demonstrated at https://www.youtube.com/watch?v=behMgV3tUr4. Noting that is for different pins. And of course you will need to subsequently change their definition, in the sketch.


10 bit PWM on Arduino UNO I am using this code to make 10 bit PWM on port number 9, it seems like everything printed is 0,1022 rather than printing 0, 512, 1023. Is there a problem in my code ?

I wired pin9 to A3 to get the output and print it.

  void setup() {
  Serial.begin(9600);
  pinMode(A3,INPUT);
  // Set PB1/2 as outputs.
  DDRB |= (1 << DDB1) | (1 << DDB2);

  TCCR1A =
      (1 << COM1A1) | (1 << COM1B1) |
      // Fast PWM mode.
      (1 << WGM11);
  TCCR1B =
      // Fast PWM mode.
      (1 << WGM12) | (1 << WGM13) |
      // No clock prescaling (fastest possible
      // freq).
      (1 << CS10);
  OCR1A = 0;
  // Set the counter value that corresponds to
  // full duty cycle. For 15-bit PWM use
  // 0x7fff, etc. A lower value for ICR1 will
  // allow a faster PWM frequency.
  ICR1 = 0x03ff;
}

void loop() {
  // Use OCR1A and OCR1B to control the PWM
  // duty cycle. Duty cycle = OCR1A / ICR1.
  // OCR1A controls PWM on pin 9 (PORTB1).
  // OCR1B controls PWM on pin 10 (PORTB2).
  OCR1A = 0x0000;
  delay(500);
  Serial.println(analogRead(A3));
  OCR1A = 0x0200;
  delay(500);
  Serial.println(analogRead(A3));
  OCR1A = 0x03ff;
  delay(500);
  Serial.println(analogRead(A3));
}

The output looks like that:

  0 0 1022 1021 0 1022 1021 0 0 1021 0 1021 1021 0 0 1021 0 0 1022

no data between 0 and 1022 are presented.

thanks.

On your code, you using analogRead but declaring the pin (A3) as output. Change it to pinMode(A3,INPUT);

Aside from that, PWM is basically a digital output which changing (HIGH and LOW) at specified frequency. When the result you got is

  0 0 1022 1021 0 1022 1021 0 0 1021 0 1021 1021 0 0 1021 0 0 1022

There's nothing wrong. 0 --> LOW, and 1021++ --> HIGH
If you want "measure" something from the PWM, use pulseIn() instead, you can check the documentation here.

If you want to measure the PWM value, I suggest you read:
Can I connect a PWM pin on one Arduino to an analog input on another?


Arduino as analog to digital converter for temperature sensor I have an ESP8266 module that must receive some data and send it to a server, my problem is that this data is given by a temperature sensore and a light sensor which must be connected to analog pins and my ESP has only 2 digital pins.

So I thought that I can measure the temperature and the light with an arduino (the sensors are the ones included in arduino starter pack) and then connect my esp digital pins to arduino digital pins and write a sketch to send digital data as output of arduino.

I think this is possible but I can't figure out how to do it because I can only set pins to high or low.

Can somebody help me? Thanks a lot

P.S: I already tried ther solutions like connecting tx and rx of esp to arduino but they didn't work so I prefer to use ESP8266 as standalone

Both the ESP8266 and the Arduino have UART serial interfaces. This is by far the simplest method of communicating between two boards.

Connect the TX of the Arduino, through a voltage divider to drop it to 3.3V, to the RX of the ESP8266. Connect the grounds together. That's all you need. Yes, you can connect the TX of the ESP8266 to the RX of the Arduino but if you are never going to send anything from the ESP8266 to the Arduino then there is little point.

Then, with both devices set to the same baud rate, you can Serial.print on the Arduino, and Serial.read on the ESP8266. Just follow one of the many many tutorials about communicating between Arduinos using UART.


How can I indicate that I am using ATmega2560 so that Arduino libraries understand it? I am developing AVR microcontollers in Atmle Studio and sometimes I am using Arduino libraries(such as LiquidCrystal).

When I initialize LiquidCrystal lcd(12, 11, 5, 4, 3, 2); I don't think Arduino Libraries use registers and ports of ATmega2560, although I am building my code with the device selection ATmega2560 option of Atmel Studio. Atmel Studio works in order to program 2560 but how can I tell Arduino libraries that I am using 2560?

There are two things that have to be considered here.

One is telling the code what board you are using, so it can compile in the right optional parts, and the other is getting the right pin mappings.

The first can be covered simply with a compilation flag:

-DARDUINO_MEGA2560

That defines the macro ARDUINO_MEGA2560 which is used in some places to know which board you are using.

Second is the pin mappings.  These are stored in the file pins_arduino.h and each board variant has its own copy.  You need to ensure that this file (and be sure to get the right one) is included in your code in the right places to ensure that the pins can be mapped right.  If you are including the whole Arduino core (which it sounds like you must be in order for things to even have a hope of working) then you just need to ensure that you have the compiler set up to include the right copy of the pins_arduino.h file.

That means making sure you have an include path in your compile command line which points to where the pins_arduino.h file is before anything else Arduino core related.

-IC:\Path\to\arduino\mega2560\variant

or

-I/path/to/arduino/mega2560/variant


Serial question : Going from Mega to Uno I have a code sample that uses serial3 (RX3 on a Mega) which I want to try and get working on a Uno.  It reads on RX3 and streams to USB.  What I had read, you use Serial for RX0, however Serial seems to be used for USB

 /*
Arduino Neato XV-11 Laser Distance Scanner
Motor control board v0.2 by Cheng-Lung Lee

XV-11 LDS adapter reads LDS data from RX3 then relay to TX. Also extract the speed
data from the data stream to do speed control on LDS motor. Everythin can power
from USB no extra power required.

Change log:
V0.2 Add simple speed control code update PWM 3 times per rev.
V0.1 Opend loop control version.

This code is tested on Arduino Mega 1280
I/O:
Motor drive by low side driver IPS041L connect to PWM Pin4, Motor power from 5V
Neato XV-11 LDS Vcc(red) : 5V
Neato XV-11 LDS TX(Orange) : RX3

 */

const int DesiredRPM=300;  // Setting Desired RPM Here.
const int MotorPWMPin=4;
int inByte = 0;         // incoming serial byte
unsigned char Data_status=0;
unsigned char Data_4deg_index=0;
unsigned char Data_loop_index=0;
unsigned char SpeedRPHhighbyte=0; //
unsigned char SpeedRPHLowbyte=0;

int SpeedRPH=0;
const unsigned char PWM4dutyMax=255;
const unsigned char PWM4dutyMin=100;
unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

 void setup() {
    pinMode(MotorPWMPin, OUTPUT);
    Serial.begin(115200);  // USB serial
    Serial3.begin(115200);  // XV-11 LDS data

  // prints title with ending line break
  Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

  // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
    analogWrite(MotorPWMPin, PWM4duty );
}

void loop() {
    // if we get a valid byte from LDS, read it and send it to USB-serial
  if (Serial3.available() > 0) {
    // get incoming byte:
    inByte = Serial3.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

}

void decodeData(unsigned char inByte){
  switch (Data_status){
  case 0: // no header
  if (inByte==0xFA)
  {
    Data_status=1;
    Data_loop_index=1;
  }
    break;
  case 1: // Find 2nd FA
    if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_status=2;
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      Data_loop_index++;
    }
    break;
  case 2: // Read data out

     if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      readData(inByte);
      Data_loop_index++;
    }
    break;
  }

}
void readData(unsigned char inByte){
  switch (Data_loop_index){
    case 1: // 4 degree index
    Data_4deg_index=inByte-0xA0;
//      Serial.print(Data_4deg_index, HEX);
//      Serial.print(": ");
    break;
    case 2: // Speed in RPH low byte
    SpeedRPHLowbyte=inByte;
    break;
    case 3: // Speed in RPH high byte
    SpeedRPHhighbyte=inByte;
    SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

    SpeedControl ( DesiredRPM ) ; //
//      Serial.print(SpeedRPHhighbyte, HEX);
//      Serial.println(SpeedRPHLowbyte, HEX);
    break;
    default: // others do checksum
        break;
  }
}

// Very simple speed control
void SpeedControl ( int RPMinput)
{
 if (Data_4deg_index%30==0) {  // I only do 3 updat I feel it is good enough for now
  if (SpeedRPH<RPMinput*60)
     if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
  if (SpeedRPH>RPMinput*60)
     if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
  }
  analogWrite(MotorPWMPin, PWM4duty ); // update value
}

Arduino UNO only has one hardware UART, hence only one Serial available, which is linked to USB, but you could still use it for something else by connecting directly to D0 & D1.

However, if you need 2 separate, independent, UART then go for SoftwareSerial for the second one.

Now, if you need to connect 2 devices, one to exclusively get data from, the other exclusively to send data to, then you can use just one UART, i.e. Serial for both devices, as long as both links work at the same speed and settings (parity...)

Also you must ensure that USB won't receive anything otherwise you would get it and confuse it with input from the first device.

The non USB device providing input to the Uno should be connected to D0 (RX).