Arduino IDE unable to see serial connection on OS X El Capitan

I ran into a similar problem years ago on an ATMega128 (before Arduino) and you just have to be aware of alternative functions for the port. In this case PD0 is Hardware Serial RX which is a receive pin.

Here's some relatively older code based around the same idea:

  Yes, you can use the RX/TX pins as regular IO. Just don't call the Serial.begin() in your code, and make sure you call a pinMode() for them.

from: http://www.societyofrobots.com/robotforum/index.php?PHPSESSID=b928292f91c78b57b5683484af0f635e&topic=12396.msg93239#msg93239

Another interesting post, fourth post: http://www.nerdkits.com/forum/thread/536/
where they disable the serial functionality once the code begins, downside (a above) you will lose serial comms, so it depends on how much you need them.

UCSR0B = 0;

I'm not sure how successful that would be in today's arduino, I know a lot (if not all) of the prior functionality is maintained, but I haven't used them in a long while.

The pin should become active again as the bootloader will automatically reenable it upon reset (although I haven't personally tested it). It will just make debugging that little bit harder if you need to.

As I mentioned in my comment, if you have another pin available to you, use that instead.


Why should a pin be set as an input if it can read input when set as output?

The reason for this is because analogRead() has absolutely nothing to do with what mode the pin is in.  That mode only has any meaning in the scope of digital operations - i.e., when using digitalRead() and digitalWrite().  When using analogRead() the Arduino code switches the pin into analog mode first and then reads from it.


Is it possible to specify a pin upon which the data sent over i2c can act?

You can use a struct to send multiple things, like this:

#include <Wire.h>

const byte SLAVE_ADDRESS = 42;

struct t_message
{
  byte pin;
  byte speed;
} message;

void setup ()
{
  Wire.begin ();   // initialize master
}  // end of setup

void loop ()
{
  // set desired parameters
  message.pin = 10;
  message.speed = 50;

  // send the message
  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write ((byte *) &message, sizeof message);
  Wire.endTransmission ();
}  // end of loop

More information about I2C - Two-Wire Peripheral Interface - for Arduino

On that page is mentioned how to Send and receive any data type. This includes structs. Using the code there you could send a struct, and receive a struct.


can arduino on output mode sink current?

Ok, I just found it.

from the arduno docs:

Atmega pins set aa output can source (provide positive current) or sink (provide negative current) up to 40 mA (milliamps) of current to other devices/circuits.


SSD1306 allocation failed when adding a constant

Your display needs 624 bytes of RAM for its internal buffer (128 * ((32 + 7) / 8)). The periodicSystem array needs a massive 360 bytes of RAM just for the objects. That doesn't include the memory used to store the actual string data, which by my reckoning is 168 bytes.

So far we're up to 624+360+168 = 1152 bytes of a maximum of 2048.  Over half way and we haven't touched on the serial buffers or other objects that you're using.

An array (const or otherwise) of String objects is by far the least efficient way possible of storing constant string data on an Arduino. You're using 528 bytes of RAM to store what could be stored in 121 bytes of flash.

Personally I would store the data thus:

const char periodicSystem[] PROGMEM = "H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNd";

Each symbol consists of exactly two bytes, and the PROGMEM forces it to stay in flash and never be copied to RAM.

You can get the two bytes of each symbol with:

char b1 = pgm_read_byte(periodicSystem + (i * 2));
char b2 = pgm_read_byte(periodicSystem + (i * 2) + 1);

Then either print them separately, or combine them into a C string:

char symbol[3] = { b1, b2, 0 };

That will include the space character, of course. So you could remove that if you like:

if (symbol[1] == ' ') symbol[1] = 0;

Theoretically you could also change the spaces in the original data to be character 0 if you like - depending on what you do with it, it shouldn't cause any issues:

const char periodicSystem[] PROGMEM = "H\0HeLiBeB\0C\0N\0O\0F\0NeNaMgAlSiP\0S\0ClArK\0CaScTiV\0CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY\0ZrNbMoTcRuRhPdAgCdInSnSbTeI\0XeCsBaLaCePrNd";


LCD Display Flicker When Arduino Main Board Supply Voltage to GSM Shield Board

This sounds like either your GSM Shield is drawing to much power (from time to time) and thus your Vin drops resulting in flickering or your GSM Shield induces ripple on top of your Vin.

To debug this I would recommed to have a look at Vin with an oscilloscope and see how stable Vin is. Additionally some capacitors between Vin and GND (100nF and 10-100µF) and a ferrit between Vin and the GSM Shields Vin might help.


Arduino Nano uploading gives error: avrdude: stk500_recv(): programmer is not responding

Know this is old but I ran onto it during my search for Nano(V3)'s not uploading so thought might help someone else.  Problem is the bootloader - Arduino IDE BUT I Found an easy solution (right under my nose).

I realized that my nano's had been uploading just fine then I had finally updated the Arduino AVR Boards from 1.6.20 to 1.6.21.  I didn't think there was any problems because it still showed my Nano and ATmega328 etc in the board manager after the change.

But the new boards manager has a new ATmega328 processor choice for the Nano. I changed processor: In the Arduino IDE select TOOLS > PROCESSOR > pulldown menu from ATmega328P to  "ATmega328P (Old Bootloader)".

Since then, I have uploaded many programs to several different Nano's V3 (Prolofic interace Chipset) without issue.


I’m having a tough time trying to program 2 fsr sensors

Call your second FSR "fsr2" connect it to analog pin A1 and add to your existing code. Sort of like this:

int fsrPin = 0, fsr2Pin = 1;     // the FSR and 10K pulldown are   connected to a0
int fsrReading, fsr2Reading;     // the analog reading from the FSR resistor divider

void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);
  delay(5);
  fsr2Reading = analogRead(fsr2Pin);

  Serial.print("Analog reading = ");
  Serial.print(fsrReading);     // the raw analog reading
  Serial.print("\t");
  Serial.print(fsr2Reading);


How to remote control Arduino using an old 2.4Ghz toy remote controller?

You have two options:

Use an nRF24L01+ on the Arduino and dismantle the controller to rip out the innards, replacing them with another Arduino and another nRF24L01+.
Do not use the nRF24L01+, instead, rip apart the car and salvage the receiver from it, then work out how you can wire that to the Arduino.

The car's controller will not talk to the nRF24L01+. Yes, they may be in the same frequency band, but they do not talk the same language. After all, your WiFi is on the same band and that doesn't talk to the car, and your microwave, which is also 2.4GHz, doesn't sit and watch satellite TV all day. As you can see the 2.4GHz band is used by a huge number of devices (the band is actually getting quite crowded) and everything talked to everything else in the same band it would be utter chaos.


Measure Natural Gas Pressure with arduino?

This is a fantastic idea, but you should be a bit more informed before you start the project.

I do not think the people suffocate into CO2 because CO2 is not inflammable under normal conditions so it is not used to feed the heaters. It's produced by the heater while it burns. Most probably the heater uses methane (CH4), ethane (C2H6) or propane (C3H8).

To measure the pressure, you have to insert the sensor within the gas pipe. If this is done incorrect, there is much more danger. So you have to find a fool proved method to add the sensor.

The selection of the sensor depends also on the pressure that can be considered as normal. Another value you have to find out is: how much decreases the pressure if the burner (or more burners) are switched on. i.e at which pressure do you assume the burner's flame to go out. This value must be well known.

When you know the max and min pressure values, you can look for a sensor that can safely measure this values. It should also be included in an enclosing that can be attached to the gas pipeline.

Attention: If the pressure drops just for a small moment, the flame might go off and the sensors might not be aware of that event.

Do you know, there are alternatives to measure the pressure?

A Gas Sensor in the room checks, if there is methane, ethane or propane in the air in the room. ( this is the most secure method ) There are cheap gas sensors from china, (e.g. MQ-02), but I do not know much about them. You can also combine them with a CO2 and/or CO sensors to sense whether the chimney is clogged.

A high temperature sensor near the flame recognizes if the flame is out. But this is difficult to accomplish, because you have to build the sensor into the heater.

EDIT

I want to point you to the comment of @Gerben. Checking the light of the pilot flame or the flame might also be interesting.

Having thought about this a bit,  I still find that measuring the air with gas sensors and starting a acoustic signal is the best way of doing it. If you want to close a valve in case you detect gas, the Arduino can start a siren and control the valve.

Attention: Again, working with gas installations is nothing a beginner should do. You want to save life ...


Is there a way to detect if Arduino, Stino or another IDE/toolchain is in use?

As Stino claims to use the installed Arduino IDE you already have, which means you can not differentiate at compile time.


According to the Arduino - ReleaseNotes,

  ARDUINO 1.5 BETA - 2012.10.22

  First release for the unified IDE for both AVR 8-bit and ARM 32-bit   (SAM3 CPUs) architectures.
  This release include the SAM Arduino Core used in the Arduino Due   Board.

So your 1.0.5 version does not allow for Due compilation. Download the most up-to-date version and you will be fine (you will be able to install SAM support).

Then you will be able to at least compile. If you have other problems with your code, please open another question here (in order to keep the one-question-per-post behavior of this website).

Don't install arduino from the debian repository, since that version is not updated regularly. Use the website version


Creating a library of C++ classes for Arduino; How to #include "Arduino.h", "WProgram.h"?

The libraries from Adafruit and elsewhere assume you are using the Arduino IDE. If you choose not to use that you will have difficulties compiling your own code. The header files you ask about are in the IDE download. You can always grab a copy of that and put the appropriate .h files into your "include" search path.

  However, in my io.h file, there is a long list of #if defined (AVR_various_names).

Well, do a test compile using the Arduino IDE, using "verbose compiling" and see what defines are generated for your particular board (which you haven't mentioned). There won't be that many of them. Then you can put that on the build commands for your IDE.

  Or can I avoid all this and somehow create C++ classes independently?

You can create C++ classes inside the Arduino IDE. I don't see how this relates to your other issues.

The Arduino IDE basically generates build commands for avr-g++ - it isn't some horrible beast you should avoid using.


The Tiva C LaunchPad is comparable to the Arduino Due in power and capabilities, but is incompatible with the stock Arduino ecosystem. It uses "BoosterPacks" rather than Shields, and Code Composer Studio (or other [some non-gratis] tools) instead of the Arduino IDE and libraries.

The Energia IDE is a port of the Arduino IDE and significantly simplifies configuration and programming Tiva C launchpads.

Beware of odd quirks with the Tiva C Launchpad board, such as the 0-ohm shunts that must be removed if you want all pins to be completely independent.


Connecting Arduino Uno to a smartwatch via bluetooth

HC-05 is a Bluetooth 2.1 SPP only chip (BR/EDR). Your bluetooth watch will be Bluetooth Low Energy 4.x (BLE Single Mode).

The two are not compatible.

You will need a BLE module for the Arduino which is capable of running as a "Central Device".


You don't.

A basic ATmega lacks the computational (and perhaps memory also) resources for mp3 decoding.  And even if you do decode to a linear PCM format, you do not have a good way to output it.

You can playback linear PCM data by pulse width modulating a pin, but the limited clock rate will result in limited resolution, and thus poor fidelity.  You will also end up with a low sample rate, making it hard to avoid audible artifacts.

The situation can actually be somewhat better with an ATtiny85 - still no MP3 decoding of course, but you can clock the counter/time block at a higher rate and so playback PWM audio with higher fidelity, provided you are willing to tolerate the inaccuracy of the onboard clock oscillator that may shift your audio frequencies by a small amount.

If you want to do MP3, you will need either a more powerful processor (often no more expensive than the one you have, and typically cheaper as a module than anything "-duino"), or else a dedicated function chip to act as a coprocessor for that purpose.


Arduino is meant to be easy way for non-technical people and so it hides as much as it can from plain view to be simple.

For simple project it works at the cost of overhead of copying libraries here and there and using Arduino's "IDE". Calling programs "sketches" and manipulate it to hide, that it is in C++. And so on and so on.

If you want to make more complicated projects, version control, good environment and such, you need to leave "simply Arduino way" and start using more powerful and complicated tools.

I personally use
https://github.com/sudar/Arduino-Makefile
https://github.com/ladislas/Bare-Arduino-Project
and have it in GIT repositories.

This way I can share libraries between projects in group, also links to libraries outside the tree works, as well as gits submodules, both allowing you to have updated libraries from 3rd party aviable to all projects, also those old ones.

I still use a lot of Arduino (like setup/loop, digitalRead and such), but also I use "normal" g++ constructs on the way. Later I will diverge even more to plain C/g++/.. code probably, using some RTOS or so, but now my needs are not so far yet. (google "arduino rtos" I am currently reading https://github.com/greiman/NilRTOS-Arduino )

Arduino is not meant to be "best practice" anyway. It is meant to be "fast and easy way to do something, when you know nothing". And it works, as anybody and his dog can start with Arduino and if interested, he can go more far on his own, or he can stick with easy and have fun anyway.


Feasibility of project with 50 leds working independently

depending on how you want to control your LED's there are several options.
firstly to be clear you could not feasibly connect that many LEDs to an arduino that could all be turned on at once (if that was needed) without damaging the arduino.
if all you need is on/off level of control then you could look at shift registers or if you have pre built arrays of LEDS in a grid type layout you could look at the MAX7219/MAX7221
if you also wanted to be able to control the brightness individually then you could look at the TLC5940
if we look at the pros and cons of each approach:
74HC595
pros:

cheap to buy
simple to use

cons:

each LED needs its own resistor
cannot vary brightness
if not using the hardware SPI pins can be slow for large numbers of outputs

MAX7219/MAX7221
pros:

lower current draw than 74HC595
only needs one resistor per IC which can drive 64 LEDs

cons:

actually flashes LED's really fast to look like they are always on
costs more than 74HC595

TLC5940
pros:

can vary brightness with a high number of steps (4096 steps from fully off to fully on)

cons:

uses more output pins than either of the above methods
requires resistor per LED
costs more for the IC than 74HC595

so to sum up, each method has its merits. if you are driving individual LEDs the the 74HC595 is probably the best/simplest route, if you are driving an array then the MAX7219/MAX7221 is best, and if you need variable brightness then the TLC5940 is probably best.


Using an Ethernet Shield and a tlc5940 together

When using multiple SPI devices the normal way to have them share a bus is to assign them distinct slave select lines. The problem here is that although the '5940 libraries use SPI to send data to it, the '5940 is not actually a proper SPI device and so lacks any sort of slave select line.

All is not lost, however. Since the '5940 responds only to SCLK (and GSCLK of course, but you should be running that one separately) all you need to do is inhibit it while nSS for the Ethernet module is active. This can be done with just a little bit of external circuitry. Since nSS must be high in order for the Ethernet module to be inactive, we can AND SCK with nSS to derive SCLK from it.

Using a 74HC08 for this would work, although it leaves 3 of the gates unused. A 74HC02 will let you do it with no wasted gates, but with a slightly higher propagation delay.

And of course, the requirement to clock in the grayscale data before the grayscale cycle completes is still there; properly interleaving this with the Ethernet communications is left as an exercise for the reader.


M0 pro: SPI communication, code works on Uno, but not in M0. Using ICSP port

Which version of the Arduino IDE are you using ? If its an older one, try to get the latest one, sometimes that solves issues like the one you have.


Waking Arduino from sleep with an ultrasonic sensor

In order to make the ultrasonic sensor work, the Arduino has to run some code to control it.  So it won't do anything while the Arduino is asleep.

What you can do is have the Arduino sleep for some reasonable amount of time, wake up and read the sensor, and then go back to sleep.  Maybe wake it up once every few seconds.  Do you really need to react to a car in the lot the millisecond it pulls in?


How to use ESP8266-12E with PCF8574 as an I/O extender

Found the answer .
The data sheet of ESP8266-12E explains everything.
The pin diagram has the given tags which shows which pins we can use.


Arduino - Ultrasonic Sensor for use instead of analog potentiometer for proximity control

The HCSR04 module is a digital proximity sensor, needing a microcontroller to read values from it. If you really want to use this then you will have to use a microcontroller as a digital to analog converter and map distance values from the HCSR04 to voltages.

However, a better solution would be to use some kind of analog distance sensor. I have used the Sharp IR distance sensors before (with Pololu carrier) and have had great success. This model also comes in a 3V flavor which might simplify your circuit design. You would now only need some analog circuitry to get the voltage values into the correct range.


Arduino Ethernet Shield: May I connect it to a PC connected to the internet via wifi?

Assuming an Ethernet port on the PC, the Ethernet shield can be connected to it using an Ethernet crossover cable:

(source: Wikipedia)

Many recent PC network interfaces have automatic cross-over (Auto MDI-X), with which even a regular (straight) Ethernet patch cable will work.

This merely addresses the physical Ethernet connectivity.

For actually routing IP packets between the Arduino and the rest of the Internet, some software router or software bridge is required to run on the PC. Several open source routing products exist, especially for Linux and FreeBSD, but that is outside the scope of this StackExchange.

Finally, the Ethernet shield does not need a router, it an as well be hooked up to an Ethernet switch or hub.


The image on the linked tutorial has the middle pin of the TMP036 going to the analog input, whereas you have it going to 5V, so that is not going to help one bit.

In other words, it is wired wrongly.


How can I know how far a button is pressed?

Following on from Mark's comment, I'm not convinced that you can measure the size of the beam, using a single optical (analogue) device - generally optical switches, like other switches, are binary, either on or off, and as such would use one of the Arduino's digital inputs.

The type of (hypothetical) button that you describe, taking a mechanical analogue (rather than your optical beam example), would require the use of an analogue input pin, and your "switch" would actually be a linear potentiometer, i.e. a slider, or lever, and the analogue input could then measure the input voltage, which would be proportional to the amount that the button (or lever) has been pressed (or moved). However, the usual linear potentiometer is not spring loaded, so the button would not really have the usual expected push button behaviour, unless, of course, you rigged up some sort of spring loaded button, with a long throw, mechanically connected to a linear potentiometer.

An analogue version of this sort of set up, as far as I am aware, does not exist for a optical solution.

What you could use is a series of optical digital (not analogue) switches (or a single light source and a series of receivers), arranged in a line (perpendicular to the base along which the coin is rolled along) in such a way that they can detect the size of the coin*. If the light is broken for a particular detector, then you know that the radius/size/width of the coin is at least the same as that detector's distance from the base.

These optical detectors are then connected to a series of digital inputs, i.e. D5, D6, D7 and D8, and a series of if statements would enable your code to determine the size of the coin.

Assuming that the broken light beam results in a low, then the pseudo code would be something like this:

if D5 = low & D6 = high
 then coin is a cent
if D5 = low & D6 = low & D7 is high
 then coin is a nickle
if D5 = low & D6 = low & D7 = low & D8 = high
 then coin is a dime
if D5 = low & D6 = low & D7 = low & D8 = low
 then coin is a quarter

Obviously you would need a trigger when to take the "snapshot" of the coin passing the detector at the correct time, when it is fully blocking the lights, and not just partially blocking the light beams (which could result in a false reading).

* I have just realised that this is exactly what Jot described in his comment.


This is not an Arduino specific topic, but here is just a pragmatic answer:

Use the output of the PID controller directly as your reference velocity, subtract your actual velocity and use it as input for the PID velocity. Units do not care in this case.

You have to make sure that the paramters of your PID position are well adjusted, this will set the problem with the units.

Here is an example to understand (only P gain considered):

If you want to drive from A to B with your car and the distance from A to B is 10 km, then your desired position is 10km and i would choose to drive about 100km/h. So in this example you start with a control deviation of 10km - 0km = 10km. If you choose a P gain of 10 the output of the PID will be 100, which is an ideal refernce Velocity, if velocity is given in km/h.

But if you are measuring your distance not in km but in m, the control deviation will be (10.000m - 0m = 10.000m), with a P gain of 10 you will end up with a refernce velocity of 100.000km/h, which is not an appropriate reference velocity in this case.

Now someone may object that in my example if you want do drive from A to C and C is 1.000km away, you will end up with an reference velocity of 10.000km/h, which is also not appropriate, but that is where the limitations in a PID controller are usefull, just set them for this example to 130km/h and you will end up stil with an appropriate reference velocity, and also your integrator part will not wind up endlessly.

You can look at I and D gain in a similar manner.


Each pin on any Arduino (with some exceptions) can only handle 40mA MAX. Even the 5V and similar output sources can't handle more than 600mA, So I suggest you use them to power a MOSFET or Darlington to connect them in appropriate series and parallel connection counts.

Both the above transistors can handle high voltage, but you need to choose ones that correspond to a voltage that an Arduino can provide.

This is the most robust method if you want all the LEDs to light up at the same time. However for array addressable LEDs you might need extra BJTs coupled with resistors for each led, maybe along with two decided that would be appropriate for your application.


Help compiling multiple .ino file code with code! (I'm not sure what to name this)

One of the .ino files is likely the main code file.  Name the enclosing folder with the name of the .ino file, then compile it as normal.

In this case, AbHhGD.ino is the main file, and its folder should be named 'AbHhGD'

The comments indicate there are missing libraries you likely need to install.


I suspect its stream.print() that is causing the problem.  Write the data into a string and then use a SINGLE call to stream.print() to send the data.  It looks like it is trying to send it as soon as possible to prevent delays and this is what is causing fragmentation..


Arduino continuously reading ADC value using interrupt

reset the resultNumber to 0 after you have written it to serial. and turn interrupts back on

void loop () {

  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
  {
    Serial.println (results [i]);
  }
  resultNumber = 0;
  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF)| bit (ADPS2) | bit (ADATE);
   // turn ADC back on
}


Reading NFC card (PN532) with Arduino Uno

The default behaviour of readPassiveTargetID is to wait "forever" for a card - which is why your code only sees when there is a card present

So, in setup() add nfc.setPassiveActivationRetries(0x10); as follows - comments came from my own code, but I'm sure they were originally in some example or other :p

// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.
nfc.setPassiveActivationRetries(0x10);

// configure board to read RFID tags
nfc.SAMConfig();

As for "detecting" removal

void loop()
{
  static bool wasSuccess = false;
  uint8_t success = 0;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
  if (success)
  {
      wasSuccess = true;
      Serial.println("Card Detected!");
  }
  else if (wasSuccess)
  {
      wasSuccess = false;
      Serial.println("Card Removed!");
  }
  else
  {
      // you may want to remove this, it will flood the output :p
      Serial.println("Card Not Detected!");
  }
}


Arduino sketch behaves differently depending on version of Arduino IDE

There are also some warnings in the older IDE that are not present in
  the newer version.

It is a huge mistake to disregards those warnings, especially:

  warning: array subscript is above array bounds

You declared an array int useColor[2]. Its length is 2 and its indices
can be either 0 or 1. Yet you are using useColor[2], which is out of
bounds and likely to corrupt memory.

From the language point of view, this is called undefined behavior,
which means that anything can happen. In particular, it could very
well happen that the program behaves as you expect... which seems to be
the case with IDE 1.0.5. Simply changing the compiler version, or event
the compiler settings, can change the behavior.


Nodemcu is connected to 5v relay with logic converter but still not working

To make that work you'd need to connect the HV connection to the Vin of the NodeMCU (as well as to the relay board) which should be the 5 V coming form the USB port. You'd also need to connect the GND on the HV side to the GND of the NodeMCU.


It's pure conspiracy, paranoia, or people just generally not having the slightest clue what they have bought. By default the ESP8266 is in Access Point mode, and named ESP_[last 6 chars of MAC address]. It will have an IP address in the range 192.168.4.x. And that is all.

It can't do anything else until you actually program it to do something.

Part of the "problem" is probably that the ESP8266 remembers WiFi settings independently of the sketch that is running on it. It's only the WiFi settings it remembers, though - not what to do with any data that travels over WiFi. That is purely down to whatever sketch you install.

Unless you manually program it so it connects to your WiFi, or add extra hardware for other communications, the device can not, and will never be able to, send any data to anyone, anywhere, ever. Full stop.


i2c slave write to ARM powered device master

It is important to understand, that Wire.write() will not actually send data over the I2C bus. It will only put the data bytes into the send buffer of the library.

The normal way of the Wire library to send data as a slave is to implement the onRequest callback function. It will be called from an I2C ISR when a master on the I2C bus requests data from this slave. In the callback, you use Wire.write() to fill the buffer with data, which then get's send out to the master.

I'm not quite sure about the following: My guess regarding your previous code is, that the Wire library clears the send buffer at some time during the send or read code. That would mean, that the data written in the onReceive callback will simply be lost, instead of used for transmission of requested data. That might be meant that way, so that the users will stick to implementing the onRequest callback, which is the correct way of doing it.

Note: In your code, you call Wire.onReceive(receiveEvent) on every void loop() iteration. That isn't necessary. The Wire.onReceive() method only set's a function pointer to the callback function. It does NOT execute this callback function, which only will be called by the corresponding I2C ISR, when data is actually received. You should use this line only once in setup() to setup the callback function. Though using it multiple times does not break things here. It's just useless.


What are the applicable processor for the ATmega32u4? And what are higher versions of ATmega32u4?

The Arduino Uno cannot use the Keyboard library. The microcontroller needs to have a native USB interface. The Uno uses the Atmega328p, which does not have one.

You can use the Arduino Micro or Arduino Leonardo for this.

For more experienced hackers: If you need to use the Uno, but still want to use extended USB capabilities (more than USB to Serial), it is possible to reprogram the Atmega32U4 on the Uno, which is only used as USB to Serial adapter chip, but of course has native USB capabilities and could create a HID/Keyboard input on the USB interface. Since that is not a task for beginners, it is not applicable for this question, but should be mentioned for future readers.


Nothng Written to Serial when using sprintf

When you use sprintf(), you need to have some space allocated for it to write the result to. At the moment, you're just passing an uninitialised pointer (result), meaning the behaviour of sprintf() is undefined. It might appear to work under some circumstances, but not others (and even if it did seem to work, it could have some nasty side effects on other parts of your code).

The simplest approach is to allocate a static char buffer. You need to be sure it's big enough to contain all of the text you want it to store though (plus an extra null character at the end).

For example:

char* myTemplate = "";
char result[64] = {0};

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

void loop() {
    myTemplate = "Welcome %s. You have slept %s times";

    sprintf(result, myTemplate, "Jane", "many");
    Serial.println(result);
    Serial.println("hello");
}

As a side note, it's usually a good idea to initialise your variables. This is especially true for pointers.


How do I connect a temperature and heartbeat sensor to an Arduino Uno?

If you separate your code into functions you may understand what you want to do better.

In the listing above, you have code that reads the temp and prints the temp.  So creating two functions ReadTemp() and ShowTemp() will make the code in loop look cleaner and easier to read.  i.e.

void loop()
{
    const float cel = ReadTemp();
    DisplayTemp(cel);
    delay(1000);
}

float ReadTemp(void)
{
    val = analogRead(tempPin);
    float mv = ( val/1024.0)*5000;
    float cel = mv/10;
    // float farh = (cel*9)/5 + 32;
    return cel;
}
void ShowTemp(const float& cel)
{
    Serial.print("TEMPRATURE = ");
    Serial.print(cel);
    Serial.print("*C");
    Serial.println();
}

In you sketch for the hearbeat monitor you should have some code that reads the heartbeat and some that prints it.  If you create two functions ReadHB() and ShowHB() you will be able to easily add them to the above loop function.

I've never used the serial plotter, but if you wrap it in a function called PlotTemp() and PlotHB() then you can slot them in instead of the Show functions.


How to connect NRF24 receiver and Micro SD Card Module to Arduino UNO

SPI is a multi-drop bus protocol. That means that multiple devices can share the same physical communication medium (wires).

The only thing that needs to be "unique" for a device is its chip select pin which the master device (Arduino) uses to choose which of the devices on the SPI bus it's talking to.

So you can share pins 11, 12 and 13, but choose a different chip select pin for each device.

However, SD cards are notorious for not working well with other devices (especially with some cheap breakout boards) and your mileage may vary.


For this you will have to implement a finite state machine. This is a
very common paradigm in the embedded world. I recommend you start by
studying this tutorial: The Finite State Machine, by Majenko.

Four your particular problem, I would implement a machine with three
states: IDLE, ARMED and ALARM, the ALARM state being the only one in
which the buzzer is on. The transitions would be:

ARMED → ALARM when the level hits 100%
ALARM → IDLE after 15 seconds spent in the ALARM state
IDLE → ARMED when the level gets below 90%

Note that the only difference between IDLE and ARMED is that the IDLE
state will not go into ALARM when the level reads 100%, as you have to
go through the ARMED state before. The threshold at 90% percent is meant
to add some hysteresis. You can tweak the threshold value to your
taste.

I leave the implementation to you. It should be easy one you have
studied Majenko's tutorial.

Edit: Just to illustrate the generality of the concept, I would like
to point out that the code in Look Alterno's answer can be thought of as
a finite state machine where the state is implicitly encoded into the
variables lastBuzzer and percentage. The implicit state is:

ARMED when lastBuzzer == 0
ALARM when percentage > 99 && millis() - lastBuzzer < 15000L
IDLE when  percentage > 99 && millis() - lastBuzzer >= 15000L

The line lastBuzzer = 0 establishes the ARMED state as soon as
percentage ≤ 99. Note that this lacks hysteresis: if the reading
fluctuates between 99% and 100%, the alarm will sound again and again.

I personally prefer using an explicit state variable, as it makes the
code clearer to me. But then, the best approach is whichever makes the
code clearer to you.


Need to read/send both values of a button push

Change

else if (isButtonPressed==0 && flag==0)
    Blynk.notify("Alert : Water level has risen");

to

else if ((isButtonPressed==0) && (flag==1))
{
    Blynk.notify("Alert : Water level has risen");
}

Otherwise, when flag == 1, it will never revert back to 0.
Also it's best to add brackets, and use parenthesis.

Also, change the variable name flag to something more meaningfull.


What is the best type of Arduino board for simple delivery robot?

ANWSER

I would suggest you to use the Arduino UNO for all the shields that it has. Most Arduinos are so similar that it wont make a difference but the UNO has many shields to it, including a motor/servo shield which is going to be great for your project.

But at the end of the day, it's your project and you can pretty much use any of the boards listed below. They are just advantages and disadvantages of many popular board. Hope it helped you!

The summary has been removed for the sake of respecting Stack Exchanges rules.


Can the Adafruit PN532 NFC/RFID be used to read Gen-2 EPC class RFID Tags?

It can not. The frequencies are different: 13.56MHz vs.868–956 MHz.


Powering fans and arduino pro mini from single 12v supply

If you want to minimize power usage, the best thing would be to start with devices that use more power! :D

It's time for math! I'm going to use the generic L7805CV 5V, 1A linear regulator. Poking in the datasheet, we find that the quiescent (standby) current is max of 6 mA. I'm assuming this power drawn is 12V, not 5V.

Since a linear regulator is basically a variable resistor, we can figure out that the efficiency is:

Vout / Vin

...thus, our efficiency in this application is...

5V / 12V = 0.416666667% efficiency

... Read more here.

So, we can use the inverse of the efficiency function (Vout / Vin → Vin / Vout) to establish the amount of power it'll use. Final equation:

Power Used (W) = (12V / 5V) * Current Draw + (0.006A * 12V)

...which simplifies to:

Power Used (W) = 2.4 * Current Draw + 0.072 W

So, all we need to find is the power consumption of the Arduino. This forum post states the power consumption of different sleep modes:

SLEEP_MODE_IDLE: 15 mA
SLEEP_MODE_ADC: 6.5 mA
SLEEP_MODE_PWR_SAVE: 1.62 mA
SLEEP_MODE_EXT_STANDBY: 1.62 mA
SLEEP_MODE_STANDBY : 0.84 mA
SLEEP_MODE_PWR_DOWN : 0.36 mA

Let's give the Arduino a generous 15mA to sleep:

Power Used (W) = 2.4 * 0.025 + 0.072 W = 0.132 W

So, 132 milliwatts, idle. A bit further, we can calculate that, if your wall wart has an efficiency of 10%, it will actually draw 1.32 W from your wall socket. Using a general cost per killawatt hour ($0.125), we can calculate that it will cost you about $1.45 a year for that Arduino to be ran in sleep mode 24/7 (given that we used the maximums for everything).

It's pretty cheap, so I wouldn't worry about that power. A good switching regulator will cost more than to run it for a few years with a linear regulator. I'd use the onboard one.

If you still want to optimize things, the wall wart or the fan should be looked at first. Consider getting a switching wall wart instead; this will give you a higher return on your investment since both the fan and the logic use this.


Creating variable inside if statement (conditional signed vs unsigned int)

You could try something like this:

int16_t readRegister(byte thisRegister) {
  int16_t result;

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  // return the result:
  return (result);
}

uint16_t readUnsignedRegister(byte theRegister) {
  return (uint16_t) readRegister(theRegister);
}

Another alternative is to define a "universal" data type, i.e. a union and necessary cast operators.

union univ16_t {
  uint16_t as_uint16;
  int16_t as_int16;

  univ16_t(int value)
  {
    as_int16 = value;
  }

  operator uint16_t()
  {
    return (as_uint16);
  }

  operator int16_t()
  {
    return (as_int16);
  }
};

This allows the function to have the following form:

univ16_t readRegister(byte thisRegister) {
  int result;

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  // return the result:
  return (result);
}

With the two possible assignments.

uint16_t reg1 = readRegister(...);
int16_t reg2 = readRegister(...);

Cheers!


If you use the DS3232RTC library then you can setup an alarm which is like an alarm. I have put a good tutorial on how to do that below.
https://thekurks.net/blog/2018/2/5/wakeup-rtc-datalogger
There is also other threads on arduino.cc you should check out. They might have additional work-arounds.
https://forum.arduino.cc/index.php?topic=333654.0
https://forum.arduino.cc/index.php?topic=99588.0


led h_red = {0,0,255,0,300};

Here, you are defining a variable, and at the same time giving it an
initial value. This is called an initialization.

led leds[LEDS];

Here you are defining an array. Since it is in global scope, and not
explicitly initialized, it is implicitly initialized to all bytes zero.

leds[0] = {0,0,0,0,0};

Here, you are trying to give a value to an element of the array that has
already been defined previously. This is thus not an initialization,
but an assignment. Unlike initializations, assignments cannot exist
outside a function. If you want to assign initial values, you can do it
in setup().
Alternatively, you can initialize the array while you define it:
led leds[LEDS] = {
    {0, 0,   0, 0,   0},
    {0, 0,   0, 0,   0},
    {0, 0, 255, 0, 300}
};


What is the proper wiring for relay module?

A relay is a simple switch controlled by an electromagnet coil. The "NO" (normally open) side is off until you apply power to the coil. The "NC" (Normally closed) side is on until you supply power to the coil, at which point it turns off. Switches don't have polarity. If you connect the common into one part of a circuit and the "NO" side into the other, it doesn't matter which goes where.
Edit:
As another poster pointed out, you should wire the relay so it switches the hot leg from the plug, not the neutral (Assuming you're in the US or another country with polarized plugs.) That is much safer, since it means when the relay is off, the lamp is only connected to the neutral line. If, instead, you wire the relay to switch the neutral leg then the lamp will ALWAYS be connected to hot, and if somebody touches the wires they could get a shock.
Important:
What does matter is how you power the relay. If you try to drive a simple relay directly from a logic pin, it will likely damage or destroy the Arduino.
If you're using a "digital" relay that takes a constant 5V source, and a logic level control, such relays have built in transistors and protection diodes that prevent the relay coil from destroying solid state electronics.
If you're using a simple relay, you'll need an appropriate transistor to boost the current to the coil, as well as a "flyback diode" to protect the transistor from back-EMF when the coil is disconnected.


Which Arduino microcontrollers are able to drive a parallel 8-bit ILI9341 display at 320x240@60fps with DMA or extra CPU core or both and how?

The problem is the whole concept of running an ILI9341 TFT screen at 60FPS from a microcontroller. You can't. It's just not fast enough.

To get those kind of speeds you need to directly interface the TFT panel with the microcontroller. And that takes a special microcontroller with a TFT interface built in.  As well as that you need the memory to store the image that you are displaying on the screen.

There are microcontrollers available that can do it quite happily.  But they aren't in the "maker scene". Simply because they aren't a common thing to do.

For many years now there has been the PIC24 "DA" range of microcontrollers with a built in GPU and TFT interface - but there is no free C++ compiler, so no Arduino support - so no easy route to using them for beginners.

There are now, though, the PIC32MZ "DA" rage which are more accessible - though still very hard to use.  These are much more viable for the kind of thing you want, with 32MB of built in DDR, a TFT panel interface, and available in a 144 pin TQFP chip that is possible for an experienced maker to hand solder.

But the barrier is still software.  While chipKIT has full support for the PIC32MZ "EF" range of chips the "DA" range is not yet supported.  That's not to say you can't work with them, just not with the Arduino API and IDE.

The more common way to make a games console like device is to take an ARM SoC and interface it with a TFT panel directly. The simplest way for a maker to do that is to put a TFT on a Pi and install Retropie.

And we're not against open discussion as people. It's the site. It's not a site for open discussion. It's a question and answer site. You ask a technical question that you need assistance with, and we tell you the answer. It's not a forum for general discussion.  As such, this question will be closed as either "top broad" or "primarily opinion based". However your question does deserve an answer anyway.


Arduino auto power of circuit possible issue with higher voltage agains output pin?

No.  It is not possible for a modern IC such as an MCU having I/O protection diodes to enable/disable its own power using a single external N-Channel or P-Channel device.  The reason is that the path broken by the single switch ends up being partially completed through I/O pin's internal protection diode and your pulldown resistor, and depending on the voltage drop that results across that, partial turn on the FET itself.  This is enough to have the processor at least partially on - perhaps not enough to operate, but enough to keep consuming battery, and in some cases also enough to make clean startup on manual operation of the power switch unworkable.

To make this work, you need two stages of switching - two fets are a possibility.

However another easy one is to use one of the USB power switches chips intended to be included in the rarely seen "full" USB hubs that have software control of the downstream ports' power.  These are hardly ever fitted in the hubs sold, but they exist as a part, are easy to apply, typically have low leakage, and are often specified to operate correctly both substantially below and somewhat above the 5v they would see in a USB application.  Most importantly, they are multi-stage solutions in a single package - typically they function as high side switches, but they are enabled by an input going high, and as result, they do not suffer the parasitic partial turn on issue via the MCU's protection diodes in the way that a high side switch enabled by an input going low would.  I believe the RT9701 that I used in the past to do this with an ESP8266 is officially discontinued, but still available and likely replaced by newer similar parts.

Given your input voltage, another thing to consider would be using a regulator with an active-high enable input.  But realize that a linear regulator is an inherently wasteful device, and a lot of the compact switchers don't have very high input voltage allowance.


I have a diagram of my Arduino circuit. How do get it ready for PCB manufacture?

You can find the parts on fritzing.org. Anyway. You can get rid of some parts and save money if you pick the right ones. Instead of an Arduino Uno take an Arduino Pro Mini with 3.3V and HC-05 without a breakout for 5V Arduinos.

Doing that everything will smaller and running on 3.3V thus getting rid of the DC-DC converter.


Standalone 328p Programming with CH340G programmer

I have confirmed that everything on the board works and that I could upload Blink through my arduino Uno via ArduinoISP but I would like to use this adapter.

Because the ATmega family does not support a partial flash erase via ISP, loading a sketch via ISP removes the bootloader.

Therefore you must (re)load a suitable bootloader using the ISP connection, before you can perform a serial upload of a sketch using that bootloader.


Arduino Uno Constantly Resets with WiFi and 4 Relay Module

It Will be a power issue you need to supply power direct to the relay modules VCC independent of the arduino, ensure the earths are connected and just use the digital outputs from the arduino to control the relays. Digital low normally switches the corresponding relay on.


Using millis() and micros() inside an interrupt routine

The other answers are very good, but I want to elaborate on how micros() works. It always reads the current hardware timer (possibly TCNT0) which is constantly being updated by the hardware (in fact, every 4 µs because of the prescaler of 64). It then adds in the Timer 0 overflow count, which is updated by a timer overflow interrupt (multiplied by 256).

Thus, even inside an ISR, you can rely on micros() updating. However if you wait too long then you miss the overflow update, and then the result returned will go down (i.e you will get 253, 254, 255, 0, 1, 2, 3 etc.)

This is micros() - slightly simplified to remove defines for other processors:

unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;
    cli();
    m = timer0_overflow_count;
    t = TCNT0;
    if ((TIFR0 & _BV(TOV0)) && (t < 255))
        m++;
    SREG = oldSREG;
    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

The code above allows for the overflow (it checks the TOV0 bit) so it can cope with the overflow while interrupts are off but only once - there is no provision for handling two overflows.

TLDR;

Don't do delays inside an ISR
If you must do them, you can time then with micros() but not millis(). Also delayMicroseconds() is a possibility.
Don't delay more than 500 µs or so, or you'll miss a timer overflow.
Even short delays may cause you to you miss incoming serial data (at 115200 baud you will get a new character every 87 µs).


Is every Arduino comes with onboard compass?

No current Arduino board comes with an on-board compass. That function description comes from the documentation for the Arduino Robot, which is a retired product.

There may be other "maker" dev boards, such as the Adafruit Circuit Playground Express which have on-board compass peripherals.


Trying to do hello world app for Nokia 5110 LCD with arduino yun and johnny five

Arduino Yun is a ATMega32U4-based board, like other ATMega32U4-based Arduino boards, such as Arduino Leonardo, Micro, the SPI is only available on the ICSP header:

MOSI - Yun has it on ICSP Pin 4
MISO - Yun has it on ICSP Pin 1
SCK - Yun has it on ICSP pin 3
SS - Yun has no dedicated pin, use any digital data pin

You can find out the ICSP header pin assignment at Arduino SPI reference page. So here is the connection between Arduino Yun and LCD5110

Yun               LCD 5110
ICSP pin3         CLK(SCK)
ICSP pin 4        DN(MOSI)
any GPIO pin      D/C (see note 1)
RST               RST
any GPIO pin      SCE(SS) (see note 1)
any GPIO pin      Backlight (via a 330 ohm resistor) (see note 2)
GND               GND
3v3               VCC

  Note 1: Although you could use any GPIO for D/C and SCE, you should consult the library that you are using to see what pin the library used for the data/command line and SS line.

  Note 2: Connecting to a GPIO pin allows you to turn on and off the LED backlight, you could ignore the connection if you don't want the backlight, or you could connect it directly to 3v3 via a resistor if you want backlight on permanently

If you still have problem in using the LCD5110, please update your question with complete code and the library that you are using.


Loading Leonardo bootloader to Atmega32U4 running at 8 MHz

The bootloader does USB. I don't think you can do USB on the 32u4 on only 8mHz.

You can however set the system clock prescaler to divide the main clock by 2, making it run at 8mHz. The bootloader will however still run at 16mHz, but that's probably still fine (though out of spec).

  The AVR USB has a system clock prescaler, and the system clock can be divided by setting the “CLKPR – Clock Prescaler Register” on page 38. This feature can be used to decrease the sys- tem clock frequency and the power consumption when the requirement for processing power is low. This can be used with all clock source options, and it will affect the clock frequency of the CPU and all synchronous peripherals. clkI/O, clkADC, clkCPU, and clkFLASH are divided by a factor as shown in Table 6-10.

To divide the system clock by 2, set the CLKPS0 bit in the CLKPR register. The code for this would be something like this:

void setup()
{
  cli();
  CLKPR = _BV(CLKPCE);
  CLKPR = _BV(CLKPS0);
  sei();

  ...

just note that everything runs twice as slow. So delay(1000) will take 2 seconds. You'll have to update F_CPU somehow to fix this if this causes a problem.


Does your nodemcu directly feed the relay?
If so, 3.3v (nodemcu output high level) is not enough to activate it.
I would use a transistor like a s8050 to Power it (do not forget the freewheel diode on the relay coil)


There are two main possibilities.

The first one is to make a GUI on the Arduino itself. Add a TFT screen, touchscreen if you want the user to interact, or a non-touchscreen (cheaper) if you just want to display. Then, within your Arduino code, you can display the temperature data, and if you go the touchscreen route, interact with the user.

I own a couple of Arduino Esplora devices, and they would be near perfect for this, as they have a non-touch TFT screen, a joystick, buttons and a pot. All the equipment you need to display the temperature. Oh, and it has temperature and light sensors onboard.

The second way would be to make a GUI on your desktop/laptop machine. In your Arduino code, you could send your temperature data through USB (Serial), Bluetooth (SoftwareSerial), WiFi, Ethernet, nRF, etc etc etc. If you don't mind having the Arduino tethered to your computer by a cable, USB<-->Serial is the easiest solution. The software on the computer listens on a serial socket and when it receives temperature data, it displays it within its GUI.

HTH


I can only think about two things:

(least probably): the entrance (VCC) voltage is too high.
(most probably): the resistors to the LEDs are (too) low .. Recalculate the values and check the max amperes which can be handled by the output pins of the shift registers.


The PWMs on pins 10 and 11 of the Arduino Nano run at 488 Hz. That's what you are seeing on the scope. The code you are using was meant for an Arduino Due, which has real digital-to-analog converters.

Edit: You can tune the PWM to run as high as F_CPU/256 by
reconfiguring the timers 1 and 2 to “fast PWM” mode, instead of phase
correct PWM, and setting their prescalers to 1 instead of 64. This
should raise the PWM frequency to 62.5 kHz, given that the Nano has
a 16 MHz clock.

The following code should do exactly this. You can put it somewhere
inside your setup(). Warning: I have not tested this code. This
will change the PWM frequency on pins 10 and 11, but also on pins 3 and
9, which share the same timers. It will probably break the tone()
Arduino function.

// Set PWM frequency to 62.5 kHz on pins 3, 9, 10 and 11.
TCCR1A = 1<<WGM10;
TCCR1B = 1<<WGM12 | 1<<CS10;
TCCR2A = 1<<WGM21 | 1<<WGM20;
TCCR2B = 1<<CS20;


Help with coding Arduino Nano to run fan through slide switch at specific intervals

You can't run the fan directly from an Arduino pin. The fan will require to much current for that to work. Instead connect the fan, via a transistor/mosfet to the Arduino.

Also add a (flyback-)diode to the fan, as turning of the fan can create huge (but short) voltage spikes, which can damage the transistor/mosfet.

Pseudo code would be something like:

for( byte i=0; i<48; i++ )
{
  digitalWrite(fanPin, HIGH);
  delay(20000);
  digitalWrite(fanPin, LOW);
  delay(1780000);
}

You could also put the Arduino in sleep mode, during those half hours, as well. You could use the LowPowerSleep library. Then replace the delay(ms) with LowPower.sleep(ms).

Lastly, some powerbank will automatically shut down, if the detect nothing is using power. The Arduino, without the fan on, will use so little current (compared to charging a phone) that such a powerbank would shut of.


You are right: Serial.write() is non blocking: it puts the data in a
buffer and waits for an interrupt routine to send it through the UART.
If you want to wait for the transmission to complete, you can call
Serial.flush().


Menu with switch case not behaving correctly

Summary: I tested @noospy project (with some modifications) and it works flawlessly.

I had to rename Button.h to ButtonM.h due name conflict with another button library. Also, I'm using new version U8g2, so I had to change some types and eliminate some calls. Finally, I used the I2C version of the OLED screen.

This is my adapted code:

#include <ButtonM.h>  // https://github.com/JChristensen/Button.git
#include "U8g2lib.h"
#include <Wire.h>

#define PULLUP true
#define INVERT true
#define DEBOUNCE_MS 20

Button ok(2, PULLUP, INVERT, DEBOUNCE_MS);
Button menu(5, PULLUP, INVERT, DEBOUNCE_MS);
Button down(3, PULLUP, INVERT, DEBOUNCE_MS);
Button up(4, PULLUP, INVERT, DEBOUNCE_MS);

//U8GLIB_SSD1351_128X128_332 u8g(8, 9, 7);
// Screen
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);

uint8_t screen = 0;
uint8_t menu_current = 0;

void setup() {
    u8g.begin(); // Added
    u8g.setFont(u8g_font_unifont);
//  u8g.setDefaultForegroundColor();

    drawScreen();
}

void loop() {
    ok.read();
    menu.read();
    up.read();
    down.read();

    if (menu.pressedFor(1000) && screen == 0) {
        screen = 1;
        menu_current = 0;
        drawScreen();
    }

    if (screen == 1) {
        if (up.wasReleased()) {
            if (menu_current > 0) {
                menu_current--;
                drawScreen();
            }
        }

        if (down.wasReleased()) {
            if (menu_current < 2) {
                menu_current++;
                drawScreen();
            }
        }

        if (ok.wasReleased()) {
            switch (menu_current) {
                case 0:
                    screen = 2;
                    break;
                case 1:
                    screen = 3;
                    break;
                case 2:
                    screen = 0;
                    break;
                break;
            }
            drawScreen();
        }
    }

    if (screen == 2 || screen == 3) {
        if (menu.wasReleased()) {
            screen = 1;
            menu_current = 0;
            drawScreen();
        }
    }
}

void drawScreen() {
    u8g.firstPage();
    do {
        whatToDraw();
    } while( u8g.nextPage() );
}

void whatToDraw() {
    switch (screen) {
        case 0: {
            u8g.drawStr(0,getFontLineSpacing(),"Init");
        } break;
        case 1: {
            const char *menu_strings[3] = { "option1", "option2", "Back" };
            uint8_t i, h;
            int w, d;

            u8g.setFontRefHeightText();
            u8g.setFontPosTop();

            h = u8g.getFontAscent()-u8g.getFontDescent();
            w = u8g.getWidth();
            for( i = 0; i < 3; i++ ) {
                d = (w-u8g.getStrWidth(menu_strings[i]))/2;
//                u8g.setDefaultForegroundColor();
                if ( i == menu_current ) {
                    u8g.drawBox(0, i*h+1, w, h);
//                    u8g.setDefaultBackgroundColor();
                }
                u8g.drawStr(d, i*h, menu_strings[i]);
            }
         } break;

         case 2: {
             u8g.drawStr(0,getFontLineSpacing(),"Option1");
         } break;

         case 3: {
             u8g.drawStr(0,getFontLineSpacing(),"Option2");
         } break;

         break;
    }
}

int getFontLineSpacing() {
  return 24;
}

Hardware

Arduino Pro Mini 3.3v 8MHz
1306 0.96 inch White Color I2C IIC Communication 128 * 64 OLED Display.
4x push buttons with 1K pullup resistors.

So, I don't know what your problem is, but your code is impecable.


dmesg should be the tool to help you.

Run:

$ dmesg -w

Then hit return a few times (to get some blank lines).

Next plug in your Nano.  Some text should appear on the screen, which will give you a clue as to what is going on.  I don't have a Nano to try with, but a typical working device would look something like:

[29125.599800] usb 9-1.4.1: new full-speed USB device number 13 using ehci-pci
[29125.694742] usb 9-1.4.1: New USB device found, idVendor=04d8, idProduct=0208
[29125.694747] usb 9-1.4.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[29125.694749] usb 9-1.4.1: Product: Lenny
[29125.694751] usb 9-1.4.1: Manufacturer: chipKIT
[29125.694753] usb 9-1.4.1: SerialNumber: CK1660A05353C5
[29125.695213] cdc_acm 9-1.4.1:1.0: This device cannot do calls on its own. It is not a modem.
[29125.695240] cdc_acm 9-1.4.1:1.0: ttyACM0: USB ACM device
[29125.695768] cdc_acm 9-1.4.1:1.2: This device cannot do calls on its own. It is not a modem.
[29125.695791] cdc_acm 9-1.4.1:1.2: ttyACM1: USB ACM device
[29125.697772] input: chipKIT Lenny as /devices/pci0000:00/0000:00:1a.7/usb9/9-1/9-1.4/9-1.4.1/9-1.4.1:1.4/0003:04D8:0208.0004/input/input19
[29125.698394] hid-generic 0003:04D8:0208.0004: input,hidraw2: USB HID v1.11 Mouse [chipKIT Lenny] on usb-0000:00:1a.7-1.4.1/input4

If it doesn't know what the device is it will give you a fraction of the information, and probably tell you it can't attach a driver.

If the device is faulty and not recognisable you will get messages similar to:

[29125.698394] usb 2-2.1: device not accepting address 5, error -71

If you get absolutely nothing displayed then it can't even recognise that anything has been attached to your computer.  Try different USB sockets and different USB cables to see if that helps.

Note: some cheap USB cables used purely for charging small batteries don't have any data wires in them - just power. Using one of these will fail for sure.


Uno - error during uploading with library

You have a conflict of interrupts. Both the internal tone() command and the NewPing.h use Timer 2 by default, which makes them mutually exclusive.

However you can change NewPing to not use a timer by editing the src/NewPing.h file and setting TIMER_ENABLED to be false:

    #define TIMER_ENABLED true      // Set to "false" to disable the timer ISR (if getting "__vector_7" compile errors set this to false). Default=true


Neo 6M + ESP32 unable to take a fix on battery but works fine with laptop USB

With full battery charge to 3.7V this issue was resolved also using 10uf capacitor between vcc and ground help to improve


Arduino UNO R3 + SIM800L / NodeMCU via Hadware Serial. Possible?

If all you need to do is communicate between the NodeMCU and the SIM800L, what do you need the Arduino for?

Connect the SIM800L directly to the NodeMCU and program the NodeMCU to do whatever communication is needed for the SIM800L.


Am not able to call C++ function pointers from inline assembly

It seems you got confused by the pointer indirections, which is
confounded by the implicit indirections made by the compiler.
Here:
extern "C"
void __attribute__ ((used, noinline)) call(func_ptr *ptr) {
    (*ptr)();
}

The parameter ptr is not a function pointer: it's a pointer to a
function pointer. You have to dereference it twice in order to get the
function: (**ptr)();. Note that the compiler implicitly dereferences a
function pointer if you call it like a function: that's why you get no
error by explicitly dereferencing the pointer only once. In the
generated assembly, the lines
ld  r30, X+
ld  r31, X

dereference ptr in order to get the address of the function to call.
You probably wanted to write
extern "C"
void __attribute__ ((used, noinline)) call(func_ptr ptr) {
    ptr();
}

And then use it as:
call(tasks[0]);

If you just call(tasks), the array identifier decays to pointer, and
the compiler handles this as a shortcut for call(&tasks[0]);, which
turns out to be compatible with your initial implementation of call().
Now, in your inline assembly you have
lds r26, (tasks)
lds r27, (tasks + 1)

The assembly treats tasks as a symbol representing the address of
the tasks array. The linker replaces those symbols by the actual
address (0x0200). Those instructions read the RAM at this and the
following address. These slots of RAM hold the first item of the array,
namely &func_a. So now you have this address in the X register pair.
No need to read RAM again: you can movw r30, r26 and do the indirect
jump. Or, better yet, load into Z to begin with:
lds r30, (tasks)
lds r31, (tasks + 1)
eijmp

See also Majenko's answer: here I am assuming EIND is somehow
correctly set up to begin with. On an Uno, you would just use ijmp
instead of eijmp and not worry about EIND.


Not able to convert String to Integer when receiving data from pubnub?

This is the code which worked for me:-

        msg.remove(0,1); msg.remove(msg.length());
        pos = msg.toInt();
        Serial.print("value of servo angle: "); Serial.println(pos);
        myservo.write(pos);

I had to remove this character (" ") by using msg.remove(0,1) & msg.remove(msg.length()) that removes starting and ending string.


Unable to load sketch: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x41

AVR programmer helped.

Meaning the bootloader somewhat got corrupted and I had to burn new one.


If you're connecting the button from pin 2 to ground and not using an external pull-up, it can lead to trouble. Either use an external pull-up or set the internal one:

pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input:

Also, you need to debounce the button.


int firstcomma = inputString.indexOf(',');
int secondcomma = inputString.indexOf(',',firstcomma+1);
String r = inputString.substring(0,firstcomma);
String g = inputString.substring(firstcomma+1,secondcomma);
String b =  inputString.substring(secondcomma+1);
red = r.toInt();
green = g.toInt();
blue = b.toInt();
Serial.print("R");
Serial.print(red);
Serial.print("G");
Serial.print(green);
Serial.print("B");
Serial.println(blue);

This solved my problems.


I don't know exactly how your display is wired exactly, but it is certain that some sort of multiplexing is going on, since A: there is no wired ground, and B, you are controlling more LED's than you have pins going to the display.

Multiplexing manages this by using some trickery and persistence of vision. The pins for each part of the segment are all wired together. For example, the top segment on each of the three segments are all connected to one arduino pin. The common anode/cathode (depending on your specific display) for each of your three displays are wired separately however. Turning only one of the common pins on will cause only one display to function when the other pins set which segments are on. The micro controller then changes which common is active and what segments are on to illuminate the next character very quickly. It pulses between segments so quickly you cannot tell they are only on one third of the time each.

The wiring inside the display will likely look similar to this:
http://www.modd3d.com/articles/wp-content/uploads/normal-multiplexing-s.gif


You could try changing the corresponding pin from output to input.
To be sure not to disturb other comfigurations you could do direct port manipulation.

void servo_off() {
  DDRD &= ~(1<<PD5);
}

void servo_on() {
  DDRD |= (1<<PD5);
}

This assumes you use pin PD5 for the pwm signal. Adjust the "D" in DDRD and PD5 so it matches the port in use as well as the pin number.

Of course, you need some additional user input like a button to trigger calls to those functions.


Surely there's a command along the lines of .. invoke in .. 2000 .. method.

Not "a command" but you can make up something like that easily enough. Example:

// Function scheduler demo
// Author: Nick Gammon
// Date: 11 July 2015

typedef void (*GeneralFunction) (); // function pointer type

GeneralFunction wantedFunction = NULL;  // function to call
unsigned long functionTimerStarted;     // when the timer started
unsigned long delayPeriod;              // how long to wait (ms)

void functionA ()
  {
  Serial.println ("Function A");
  }  // end of functionA

void functionB ()
  {
  Serial.println ("Function B");
  }  // end of functionB

void functionC ()
  {
  Serial.println ("Function C");
  }  // end of functionC

void functionX ()
  {
  Serial.println ("Function X");
  }  // end of functionX

void scheduleFunction (GeneralFunction f, unsigned long when);  // prototype
void scheduleFunction (GeneralFunction f, unsigned long when)
  {
  wantedFunction = f;
  functionTimerStarted = millis ();
  delayPeriod = when;
  }  // end of scheduleFunction

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

  functionA ();  // call this now
  scheduleFunction (functionX, 2000);  // call this later
  functionB ();  // call this now
  functionC ();  // call this now

  }  // end of setup

void loop ()
  {
  // see if time to call the delayed function
  if (wantedFunction && millis () - functionTimerStarted >= delayPeriod)
    {
    wantedFunction ();
    wantedFunction = NULL;  // don't call it again
    }  // end of if time up

  // do other wanted stuff here

  }  // end of loop

This uses:

A function pointer to remember which function to call in the future.
A global variable to remember when you wanted this timing interval to start.
A global variable to remember how long to wait.

In setup() I called a function to save this information for future use:

  scheduleFunction (functionX, 2000);  // call this later

Then in loop() we see if the time is up, and then call the function.

This example just calls functions with no arguments, things will get more complex if you want to call a function with an argument. It would even be possible to remember the argument, but it may be unnecessarily complicated to explain how to do that, since your example did not ask for it.

You could also even schedule multiple functions, but again, showing all that adds to the complexity of the explanation.

For more information about function pointers, see Function pointers / function callbacks / function variables.


TL/DR: Your LEDs without resistors are diverting all the current away from the transistors so they are unable to switch.

In detail:

Let's take a quick look at just one small portion of your circuit in more detail:

simulate this circuit – Schematic created using CircuitLab

I have added an extra resistor into the circuit - Rw - which represents the resistance of the wires and pins of the LED, and I have given it a nominal 0.1Ω value.

Now, let's say you set the GPIO HIGH, so it outputs 5V. The LED, D1, is a typical red LED with a forward voltage of, say, 2V.  Let's calculate the current through the LED.

I = (VCC - VF)/R = (5 - 2) / 0.1 = 3 / 0.1 = 30A

30A?! But the GPIO can't provide more than 40mA absolute maximum. So all that can come from the GPIO is being sent straight through the LED leaving nothing (much) for the transistor.

Oh and yes, all that current demand is doing unspeakable damage to the Arduino's GPIO pin.

The transistor's Base-Emitter junction has about a 0.7V drop across it, and, if it weren't for the LED, with the 1kΩ resistor that gives (5-0.7)/1000 = 4.3mA. Which with a hFE of around 100, would give a collector current of around 430mA. And that should be fine for most small relays.

But with all the current being dumped through the LED what can get through to the transistor won't be enough to turn on the relay.

So increasing the resistance of the wire to the LED will decrease the current demands of the LED. And of course you do that by adding a resistor. So let's make that 1kΩ - a decent enough value for a simple indicator LED:

simulate this circuit

Now let's do the calculation for the LED's current:

I = (VCC - VF) / R = (5 - 2) / 1000 = 3 / 1000 = 3mA

Add that to the 4.3mA that wants to go through the transistor, and we have 7.3mA in total.

Now that is way below what the Arduino's GPIO can provide, so the IO pin is happy, the LED is happy and, most importantly, the transistor is happy.


How do I measure watts without a CT clamp?

You can't use a CT sensor to measure power.  CT sensors measure current.  Measuring Watts is the correct unit if you want to know the rate of energy consumption (power) from an outlet.

Response to a Comment: There are consumer devices that cost only $12.95 that might be ideal, if the only usage scenario is to compare various devices for steady state power draw and you are fine with 3% (1.5 digit) accuracy.  For the 220 VAC (whether split phase or single phase) you would need to gang two of them together appropriately.  These plug-outlet designs are nicely miniature, but will not support checking past values, providing feedback to a control system, or Wattage plotting against date, time of day, or tay of week.

Measuring of Wattage accurately (to two or three significant digits) is not trivial if the 220 Volt source is an AC power grid, thus the length of this answer.

The basic EE formula for power is P=IV for DC, meaning power is the product of current and voltage.  But you can't just go with Watts = 220 X current and expect any more than one significant digit of accuracy.  Grid Voltage may not be a clean sine wave and may vary five or ten Volts under normal conditions.

If you want more than one digit of accuracy, you'll need to calculate RMS (root mean square) power in Watts by sampling both Voltage and current and using the AC principles that extend the simple P=IV relation.   I don't know if you have knowledge of what electrical engineers call RMS.  In case you don't, the articles in the result set of This Search [1] may be helpful.

Let's hypothetically say you are considering doing the work necessary to get the two or three significant digits of accuracy in determining power consumption.  To get a sense of what that would entail, here's some information on doing that properly.  You will want to consider line voltage fluctuation, reduce your noise levels, protect your Arduino board from over-voltage, and follow electrical code reasonably well.

The below measurement fixture design is not small, but it could be miniaturized.  Unfortunately the design of a miniaturized version is large project FAR outside of the scope of an answer in this forum.  You may be one of those that likes the challenge, so I'll share a design for a larger version and leave it to you or other answering parties to think of a miniaturization that meets all these other reasonable goals.

Off the shelf parts to fabricate a full sized power measurement fixture to interface with an embedded board like the Arduino Due, for example:

Two electrical boxes
A length of electrical conduit at least 50 cm long
Electrical hardware to connect the two boxes and secure the AC cord leading to the plog and to the devices being powered.
Two lengths of 2-conductor 18 AWG shielded twisted pair cable with at least 500V rating
Code compliant AC cabling
Wire nuts
Box for the buffering circuit
A good quality digital Voltmeter with RMS AC as one of the options

Fabricate this way, but using proper code-compliant electrical practices in addition to these basic instructions for the main circuits:

Connect the plug to one of the boxes with properly rated AC cord.
Connect the two boxes with the conduit and properly rated power and return wires (white and black).
Connect the second box to the device
In each box, connect the 2 conductors of the shielded twisted pair in parallel to the AC circuit passing through the box with the wire nuts.  You must leave the shields of the two twisted pair lengths isolated (not connected to the box or the ground wire in the AC circuit.
Bring both twisted shielded pairs into the buffering circuit box.

The buffering circuit would condition each of the two AC voltage in three stages.

Surge protector
Resistor divider (see other Arduino articles for this)
Zener diode to further protect the A-to-D converter on the board

The Zener diode and the resistor divider would drop the voltage from 400 V down to below the max voltage of the Arduino board, which any of the voltages might be relative to the ground potential on the Arduino board under certain conditions.  The Arduino Due might be a good choice, because of multiple built in true A-to-D channels and the higher accuracy (digits resolution) than most other Arduino options.

The output of the box for each of the FOUR voltages would be connected to FOUR analog inputs.

Vph = the hot (black) coming from the plug
Vpr = the return (white) coming from the plug
Vlh = the hot (black) going to the load (devices to be powered)
Vlr = the return (white) going to the load

In the software you would probably want to measure the above four voltages in immediate succession (no delay between the four analogRead calls) every millisecond for a second, which will capture 60 cycles of data in 1,000 samples, enough to get three significant digits of accuracy in your power measurement.  The 60 samples of 4 channels can be thought of as 1,000 vectors of 5-dimensional data.  The fifth dimension is the time offset in milliseconds.

The software goal would be to calibrate the conversion of the 4 by 1,000 element array of analogRead integers to a 2 by 1,000 element array of doubles that represent instantaneous Voltage and current. Then power in Watts can be calculated from the Voltage-current data set.

When dealing with the 1,000 sample vectors, your loops will start with "for (int index = 0; index < 1000; ++ index) { ...".

You will need to convert your digital values representing the Voltages coming from your resistor divider to physical units.  These are the operations you would do on each sample.

V = Cv * (Vph - Vpr)
I = (Cih * (Vph - Vlh) - Cir * (Vlr - Vpr)) / R

V and I are the doubles that represent instantaneous Voltage and current respectively.

Cv, Cih, Cir, and R are also doubles. They are the calibration constants to convert the analogRead values to line voltages and currents.  A typical way to calibrate their values is to measure the RMS voltages across the three node pairs represented by each subtracted voltage pair in the inner parentheses above and the current, using some constant load.  A good load option would be some non-digital device that is fully warmed up and in some steady state.

From the voltages and currents and the digital values acquired from the four analog channels in the Arduino, with some algebra skill, one can determine the scaling factor C for each of the three cases, by dividing: (V1 - V2) / V, where V1 and V2 are the RMS values measured with the digital Voltmeter and V is the calculated RMS voltage from the samples.

R can be calculated by dividing the Voltage and current values V/I in accordance with the principles discussed in the articles referenced above.

Once you have calibrated your measurements for V and I in your block of 60 samples, the articles above give you some direction as to how to calculate your power in Watts RMS in a loop.

[1]: Search for "calculating rms watts from samples of voltage and current" via Google.


Can you query the current serial port's speed?

There is not a top level, easy to use way. Sorry. It is probably easier to just store your chosen baud rate in a variable when you setup the serial port.

Anyway, What you can try to do for the AVR-based, hardware UARTs is undo what Serial.begin does to set up a particular baud rate, but its a bit of a pain. This is the code for setting the baud rate:

  // Try u2x mode first
  uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
  *_ucsra = 1 << U2X0;

  // hardcoded exception for 57600 for compatibility with the bootloader
  // shipped with the Duemilanove and previous boards and the firmware
  // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
  // be > 4095, so switch back to non-u2x mode if the baud rate is too
  // low.
  if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
  {
    *_ucsra = 0;
    baud_setting = (F_CPU / 8 / baud - 1) / 2;
  }

  // assign the baud_setting, a.k.a. ubrr (USART Baud Rate Register)
  *_ubrrh = baud_setting >> 8;
  *_ubrrl = baud_setting;

You can find the results of this by reading the right UCSRA, UBRRH, and UBRRL registers. On an uno those are the correct register names, on an mega its UCSR0A, UBRR0H, UBRR0L for Serial, UCRS1A ... for serial1 and so on. Non-avr boards (and Serial on a leonardo) will be totally different.

There will be a single state for those three registers on an AVR hardware serial port for a particular board (and frequency of that board) at each baud rate. You can try and make an equation to get the original baud rate out, but I recommend just comparing the direct values with a lookup of some kind because the integer arithmetic rounding errors will make it a huge mess.

For example, on my mega UBBR0H, UBBR0L, and UCSR0A are 0, 207, 2 at 9600 baud, but they are 0, 51, 2 at 38400 baud and 0, 16, 0 at 57600 baud.


'Keyboard' not found when trying to use Keyboard.write from the  library

The Mega2560 can't be a keyboard. It lacks the required hardware.

Instead you need to use one of the pure USB boards, like the Leonardo.


The 5v of an ATX power supply will be perfectly adequate for powering an Arduino.

It will already be very heavily filtered and stabilised.


Nano clone not working over USB, no data, no power, but can power via Vin (CH340 chip? schottky diode?)

Either you have a cable problem or that board is just not working well.

What you call the CH340 chip - when they go bad you get power but NO communications, in my experience.  You can test voltages at the various points like 5V, 3.3V, etc., to see if it getting power.  If it is and you're still not communicating, then if it were me it would go on the shelf for the kids to see.

It no longer can trusted.

Rather than troubleshooting the board it would be worth getting another to compare with.

And if you have more than one cable on hand, try them and see if there are any differences.

But my prediction is that a new board will work and this one will continue to not work.


Is there any option to connect XDTouch IrTouchScreen to Arduino?

Looks like your touch screen may talk RS-232. It uses the SP232EEN (a MAX232 clone) to interface with an MCU (Cypress CY7C63803) to get USB.

Connect wires to T1 IN and R1 OUT (I assume it's on channel 1) to your Arduino for UART communication. You would most likely need to disconnect those pins from talking to the Cypress chip, or they will interfere. Use the +5V and GND pins of the USB interface to power it direct from the Arduino.

Alternatively cut that board off and use a cheap MAX232 interface board to connect to the Arduino - that may be cheaper.  T and R are TX and RX (though from which PoV is anyone's guess).


Quick start on Arduino for experienced embedded programmer?

As far as I know, there is no tutorials about using Arduino's for, e.g. "multi-tasking, real time response". That is not the focus of the Arduino community.

The Arduino UNO development board is built around Atmel's ATmega328. The Summary datasheet gives an overview of its hardware capabilities on the first page. If you are familiar with MCU development, that should give you a feel for its hardware capabilities. The complete ATmega8/168/328 datasheet is over 600 pages, and describes every feature, with all registers in detail.

The Arduino IDE uses gcc under the covers. So you likely already know how to use that. When you download and install the Arduino IDE, gcc and gnu binutils for AVR will be installed too.

The Arduino IDE has all of the Atmel header files, so much of the code in the datasheet should compile, link and upload.

The IDE is really designed for beginners. It is to easy to use, but has very few features beyond basic editing, compiling and loading. It does support a serial-monitor to see text printed by the uploaded application, but it doesn't support a debugger like GDB out-of-the-packet.

However, it doesn't prevent you writing C++ code and header files, and it will build the whole collection of files.

Because the IDE lets you create and edit C++ directly, you can install the IDE on any of the three main platforms, and get started very quickly.

You will probably want to visit AVRFreaks who tend to focus at a lower level than Arduino.

There is also AVR LibC library which points you at the documentation for the AVR upload tool, avrdude, and debugger.

Summary: Install Arduino IDE, do a couple of quick projects to get a feel for the system. Then start writing C++ as normal. Install AVR LibC library for a more traditional library, and visit AVRFreaks forums for more technical help and information.


Uploading Temperature data (DHT22) to Thingspeak with an ENC28J60

Try this:

/*
| Post temp. values from a DS18B20 to ThingSpeak using the Ethercard interface based on the
| ENC28J60 chip.
| Based on the Ethercard example from www.jeelabs.org
| Phil Grant Jan 2014
*/
#include <EtherCard.h>
// change these settings to match your own setup
#define APIKEY  "xxxxxxxxxxxxxxxx"

//DHT Setup
#include "DHT.h"
#define DHTPIN 2     // what pin we're connected to
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE);

// ethernet interface mac address, must be unique on the LAN
byte mymac[] = { 0xXX,0xXX,0xXX,0xXX,0xXX,0xXX };

char website[] PROGMEM = "api.thingspeak.com";

byte Ethernet::buffer[700];
uint32_t timer;
Stash stash;

void setup () {
  Serial.begin(57600);
    dht.begin(); //Initializate DHT
  Serial.println("\n[webClient]");

  if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
    Serial.println( "Failed to access Ethernet controller");
  if (!ether.dhcpSetup())
    Serial.println("DHCP failed");

  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);

  if (!ether.dnsLookup(website))
    Serial.println("DNS failed");

  ether.printIp("SRV: ", ether.hisip);
}

void loop () {
  ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 60000; //Transmit every minute
    delay(2000);  // Wait a few seconds between measurements.
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity(); // Read temperature as Celsius (the default)
  char h_buffer[10];
  String Hstring = dtostrf(h,0,5,h_buffer); //Convert Humidity value to String

  float t = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true)
  //float f = dht.readTemperature(true);
  char t_buffer[10];
  String Tstring = dtostrf(t,0,5,t_buffer); //Convert Temperature value to String

    byte sd = stash.create();
    stash.print("field1=");
    stash.println(Hstring);
    stash.print("&field2=");
    stash.println(Tstring);
    stash.save();

    // generate the header with payload - note that the stash size is used,
    // and that a "stash descriptor" is passed in as argument using "$H"
    Stash::prepare(PSTR("POST /update HTTP/1.1" "\r\n"
                        "Host: $F" "\r\n"
                        "Connection: close" "\r\n"
                        "X-THINGSPEAKAPIKEY: $F" "\r\n"
                        "Content-Type: application/x-www-form-urlencoded" "\r\n"
                        "Content-Length: $D" "\r\n"
                        "\r\n"
                        "$H"),
            website, PSTR(APIKEY), stash.size(), sd);

    // send the packet - this also releases all stash buffers once done
    ether.tcpSend();
  }
}


Global memory reduction when using SPI/SD

Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes

The Arduino SD library uses an internal file block caching (512 bytes) to improve performance. It is possible to read directly from a file block on the SD but that would be very slow. Every 16 bytes read would require reading from file block, discharging all preceding bytes (as the file block is read serially), reading the 16 bytes, and then stopping the block read.

There are a few tiny SD libraries that actually use this technique. See for instance Petit FAT File System http://elm-chan.org/fsw/ff/00index_p.html

Another technique is to block copy from the SD directly to the external SRAM without going through additional buffers. This requires a refactoring of the SD library so that it uses a callback instead of the internal buffer.

Cheers!


Help in "An error occurred while uploading the sketch"

The upload to esp8266 with esptool used in IDE doesn't work good on slow baudrate. It fails for larger sketches. You can upload to NodeMcu at 921600 baud.


Technically, yes: If you hook up this shield to the car buses through OBD-II, and know which messages to send (e.g., ones that the car will accept and work with), then it will work.

The problem is: There are some "official" messages, basically emission related stuff, that are mandatory on every cars. There are lists of these out there.
Unfortunately, most messages are OEM dependent (including those that may control the basic features you mentioned), and they don't want you to mess around this.
Said differently: The semantic of CAN frames/messages varies from one car to another.

Being able to send receive CAN frames (which this shield is) is like being able to emit sounds & hear them: Mandatory, if you want to discuss with someone, but useless/not enough if you do not speak the same language.


Button to stop a stopwatch not working correctly!

There are several issues here. First and foremost, your button is wired
incorrectly. If you connect one end of the button to +5V, then the other
end should have a pushdown to GND, like here:

(Image from the Arduino Button example).
The second issue is the lack of debouncing. You should ignore the rising
edges you sense for a few milliseconds after you record one.
The third issue is the timekeeping. As explained by Sim Son, your
seconds will not be very accurate. It's better to just count the
milliseconds elapsed since the button press, and then break the count
into full seconds and remaining milliseconds.


How can I get a unique ID for all my Arduino boards?

There are a number of techniques you could use here to get a unique ID.

FTDI chips have a unique serial number programmed onto them. This can only be accessed from the PC side of the connection as far as I am aware.
Some of the chips with built in USB (e.g. ATmega8U2/16U2/32U2) have a unique ID in the signature data, normally used for USB. Can easily be accessed from both sides of the connection. This includes the ATmega16U2 that is used as the USB->Serial bridge Arduino Uno R3.
Some of the chips with built in USB but no unique ID in the signature will still have a unique ID programmed into the USB stack (e.g. LUFA) used for the bootloader or DFU (Device Firmware Upgrade).
There are many chips with globally unique serial IDs in them e.g. the Microchip 11AA02E48, all of the Dallas 1-Wire sensors (including the common DS18B20 temperature sensor), and other serial EEPROMS. I've used these in production hardware that must have a unique MAC address.
You could modify the standard Optiboot bootloader (or whichever boat loader you use) so that it can hold and respond with a unique ID.

The problem with these is that there is no option except 5 that will work across all boards.

If your solution is going to be a generic one, I would suggest that using a USB ID is not the way forwards. I have ~30 Arduino-based boards, and only 5 of them have built in USB hardware. All the rest of them need an external FTDI cable to be programmed. This means they would all have the same ID.


How can I use arduino board for AC mains?

Try the PowerSwitch Tail II.

This is suitable if you are living in the USA (120VAC power).
You will find 240VAC versions as a kit on that web page as well.


Pro Micro - Measuring voltage between two pins, without using GND

No, you cannot - the ATmega's ADC is referenced to its ground, and there are also some strict limits on providing inputs more than a little bit outside of the range between its power and ground.

You may be able to read two analog inputs and subtract them for a sort of "software differential" analog input, but the signal on an LED is unlikely to be meaningfully "analog" anyway - it might be pulsed with a duty cycle, but it will probably not have a steady reduced voltage.

It's actually quite likely that the anode of the LED is connected to the toy's positive supply, and it is the negative path to the cathode which is being switched - this is the most traditional way of doing things, because historically semiconductor switches suitable for "low side switching" have had better performance than those suited for "high side switching".  There will probably be a resistor on one side or the other of the LED.

With care and verification of suitable voltage ranges, you may be able to read the voltage on the LED cathode as a digital signal and invert it in software.


(Its not circular shifting, its bit shifting, the bits don't go round in a circle they disappear off the end and are lost forever.)

So in the library you are using you are writing bytes to the SD Card.
If you write the data 0x1954 on the card you get 0x5419.
So what is happening is you are writing the least significant byte followed by the most significant.  This is because you have take your int 0x1954 and cast it to a char[2] which contains c[0] = 0x54 and c[1] = 0x19  and then you write that out in the order c[0]c[1] et voila you have reversed you number.

The solution is to reverse the buffer before you write it:

char tmp = buf[0];
buf[0] = buf[1];
buf[1] = tmp;

HOWEVER - If you are only reading and writing from this code, who cares.  As long as you read it in backwards does it matter how it is stored on the SD Card?


Your button and pull-up configuration is not correct, so when the button is not being pressed, the pin D1 is floating, being pulled neither HIGH nor LOW.

Instead, use a pull-up resistor as shown. When the button is not pressed, D1 is connected to GND through a resistor. When the button is pressed, the 3.3V source has a direct path to D1.

simulate this circuit – Schematic created using CircuitLab


You are not reading from any analog pins. You are just printing out the digital pin number of the analog pin.

Look at some basic examples on how to read analog values.

/*
  AnalogReadSerial
  Reads an analog input on pin 0, prints the result to the serial monitor.
  Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.
*/

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}


Share data between the two processors of the Arduino Yun

Given that my Python script printed the following

[10, 20, 30, 40]

This is the sketch I used to retrieve the array

#include <Bridge.h>
#include <Process.h>

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

void loop()
{
   Process proc;
   int i=0;
   size_t dim = 1;
   int* array = (int*)malloc(dim);

   Serial.print("Running process...");
   Serial.println("done!");
   proc.runShellCommand("python /script.py");

   while (proc.available()){
     if((char)proc.read() != ']'){
        array[i] = proc.parseInt();
        dim++;
        array = (int*)realloc(array,dim);
        Serial.println(array[i]);
        i++;
      }
      else
        break;
   }

   Serial.println();
   delay(1000);
}


connection between two ARDUINO with xbee

Probably you are getting a new character/carrier return (\n or \n\r) in your receivers' string, that is why it won't match exactly "on" or "off", it will be "on\n", "on\r\n" or similar.