Combining code for multiple sensors in one program (Arduino)

You need to combine the 3 major area's of the code, the include/declaration section where files are included and global variables are declared.  Then combine the setup() functions and then combine the loop() functions. Ends up looking something like below. However you may have to tweek the timing of your delays

#include <SimpleDHT.h>
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;
int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
  Serial.println("Starting");
}

void loop() {
  int analogSensor = analogRead(smokeA0);
  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

The other way you can do it, which keeps it easyer to read, is move the contents of each main loop into its own function, and then call the two functions from inside loop().  This allows you to easly comment out one of the functions to trouble shoot somthing, or even allow you to call one more often then the other depending upon your needs, (can look at the blink without delay example for how to manage timing)

#include <SimpleDHT.h>
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;
int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

    void setup() {
      pinMode(redLed, OUTPUT);
      pinMode(greenLed, OUTPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(smokeA0, INPUT);
      Serial.begin(9600);
      Serial.println("Starting");
    }

void loop1(){
   int analogSensor = analogRead(smokeA0);

  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

void loop2(){
  delay (250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

void loop() {
  loop1();
  loop2();
}


When you send a GET request in HTTP you get a HTTP response back, not just the contents of the file you requested.

For instance, your request may result in a response of:

HTTP/1.1 200 OK
Date: Thu, 28 Dec 2017 11:02:21 GMT
Server: Apache/2.4.25 (Ubuntu)
Last-Modified: Wed, 05 Apr 2017 09:40:30 GMT
ETag: "2c39-54c682ee19688"
Accept-Ranges: bytes
Content-Length: 3
Vary: Accept-Encoding
Connection: close
Content-Type: text/plain

1

As you can see there's plenty of occurrences of 0 and 1 in there to trigger your LED.

You need to parse the incoming data better. Read it line by line and only start reacting to the content after the blank line that indicates the division between header and body.


For changing the led color or making any other led to glow you have to put the led number instead of leds[led number]  in this case so your code will basically look like.
void loop() {
 // Turn the LED on, then pause
 leds[0] = CRGB::Red;
 leds[1] = CRGB::Red;
 leds[2] = CRGB::Red;
 leds[3] = CRGB::Red;
 FastLED.show();
 delay(5000);
 // Now turn the LED off, then pause
 leds[0] = CRGB::Green;
 leds[1] = CRGB::Green;
 leds[2] = CRGB::Green;
 leds[3] = CRGB::Green;
 FastLED.show();
 delay(5000);
}

Hope this helps


Unfortunately you cannot control that display using that library; the library expects to be connected to a HD44780-compatible driver but the display uses a fully custom control scheme. You may be able to adapt the library to the scheme, but I have not looked at that specifically.

I2C itself only requires 3 connections: SDA, serial data; SCL serial clock; GND, ground reference. Since the display is not powered separately it also requires power, in this case 5V. Since the display can only communicate at 100kHz you don't need to be too terribly concerned about cable quality; Cat3 or even telephone cable is acceptable as long as you don't exceed a few feet in length. Don't forget the external pullup resistors though, on SDA and SCL.


avrdude: stk500_recv(): programmer is not responding

Is it this?

"To upload a new sketch to the Arduino Mini, you need to press the reset button on the board immediately before pressing the upload button in the Arduino environment."

https://www.arduino.cc/en/Guide/ArduinoMini


Can i use PL2303 USB to TTL Serial Converter Module send keystrokes using Arduino nano?

No. That is serial. Just like every other USB to TTL Serial converter. The clue is in the name.
You need an Arduino with a dedicated native USB interface, like those based on the ATMega32U4 chip.
Or dedicated software on the PC that will read serial data and emulate keypresses (which is outside the scope of this website).


Digispark / Digikeyboard code doesn't execute inside setup{}

The (hard to find) documentation on the DigiKeyboard example:
http://digistump.com/wiki/digispark/tutorials/digikeyboard

States:

  It is essential that DigiKeyboard.update() is called regularly (the
  beginning of the loop is good) to maintain USB communication. Using
  DigiKeyboard.delay() will automatically spam DigiKeyboard.update()
  calls during the delay period. If your loop code is fast just using
  DigiKeyboard.delay() will be sufficient.

Without looking deeper into it, I suspect that your initial call to DigiKeyboard.print() fills a buffer and DigiKeyboard needs subsequent repeated calls in order to empty the buffer.

Does the problem still exist if you put DigiKeyboard.update() as the only statement in the loop() function?


Cheapest way to change digital output source

As @Gerben said in the comments, I would also recommend an N-channel MOSFET.  OnSemi has a great application note on how to determine what type of MOSFET you would need based on your given load requirements and how to use it as a switch.  You can find that app note here.

The basic idea is to provide an enable signal from your atmega328 to the gate of the MOSFET to drive it into saturation or to turn it off.  You would connect your 12/24V supply to the drain of the MOSFET and connect your load to the source of the MOSFET.  The basic circuit can be seen in the application note.

Hope that helps!


Are you sure the problem is in the upload time? delay() takes the number of milliseconds you want to wait. In your code, it should take about 3 hours before the Arduino sends some data through the serial port.


Compute yaw from magnetometer and accelerometer

I don't know how all your sensor's axis are lined up, but it looks like you should level the magnetometer readings by rotating them by -pitch and -roll to get back to the global reference frame, instead of rotating the magnetometer readings by the positive angles.

However, The pitch and roll angles in the code are both relative the horizon, not a set of euler angles that define a rotation between two states; because of this, they do not compose to rotate the magnetometer back into the global xy frame like I assume the equations are trying to do. The code is also only using atan for pitch and roll instead of atan2, so their range is only 180 degrees.

You need to make sure the rotation matrix you multiply your magnetometer reading by is based on the same conventions as the equations you use to get pitch and roll from the accelerometer, and that it cancels the observed rotation.

To do this correctly, I recommend you read into euler angles. You might also try searching around for a good library that handles 9-DOF sensor fusion for you.


Arduino: incorrect calculation of long integer

In your #define of B you missed parenthesis (). Change your definition to:

#define B      (A * 62)

Without parenthesis you first divide 6200000 by 200 and then multiply result by 62, which is not what you intend.


Issues converting an uint32_t into a char*

Your code with sendBinary is probably fine, as long as on the other side you also use a function that expects to receive exactly 32 bits of binary data (in little-endian format).
Trying to print (char*)&some_32bit_int on the other hand will not do anything useful.
The short version is this:

if you want to send (or receive) binary data, use functions made for binary data - they will usually take a pointer to char (or uint8_t or something like that) and a length.
if you want to send (or receive) strings, use functions meant for strings. They'll sometimes take String, or std::string or, unfortunately perhaps, char * for C strings.

Never mix both.
Functions that expect a (C) string expect it to actually be a C string, i.e. a sequence of chars ending with a null byte (0x00). The chars are expected to be mostly ASCII printable characters. If you give them just plain raw data like the memory address of an int, you won't get what you want.
Trying to print raw data using a function that expects a C string will result in garbage (or nothing at all, or a lot more garbage than you expected!). (Details in the second part.)
If you want to format your data into a string for sending (using a string/text protocol), then use functions like sprintf to do the conversion. (Or use a library that does JSON if your receiver is a web thing - that's pretty handy.)
e.g.
char buffer[32];
sprintf(buffer, "{data:%d}", payload);

Then send buffer via a function that expects a C string.

Consider this:
uint32_t payload = 0x00323130;

The first line initializes a 32 bit int to a specific value, 0x00323130 in hex. Now let's assume that payload was stored in memory at address 0x0100. The memory after that assignment would look like this:
Addr.  Val
0x0100 0x30  // our same number 0x00323130 stored in little-endian format
0x0101 0x31
0x0102 0x32
0x0103 0x00

When you do:
client.sendBinary(&payload, 4);

Those four bytes get send over the wire (or the air) exactly as they are. Nothing more, nothing less. If that's what the receiver expects you're golden.
Now if you do:
Serial.println((char *) &payload);

Serial.println is an overloaded function. When you give it a char *, it expects a C-string, which is a series of characters terminated by a "null byte", i.e. a byte value of zero. Serial.println will then look at the first byte pointed to by the argument. If it's zero, it stops. Otherwise it outputs that char to the serial line, and moves on to the next character. Repeat until a zero byte is found.
In the specially crafted case here with that specific value of payload, Serial.println would receive address 0x0100 and:

Look at the value at 0x0100, get 0x30, check that it's not zero, and pass it on to the serial line. Serial monitor would receive 0x30 and display that. By lucky coincidence this is the ASCII character code for the digit "0".
Look at the value at 0x0101, get 0x31, check that it's not zero, and pass it on to the serial line. Serial monitor would receive 0x31 and display that. By lucky coincidence this is the ASCII character code for the digit "1".
Look at the value at 0x0102, get 0x32, ... serial monitor displays "2".
Loot at the value at 0x0103, get 0x00. That is a null byte, so it stops there, and sends a newline sequence to the serial.

So in this fabricated scenario the output on the serial monitor would be "123".
Try it with payload = 0x00616263; - serial monitor will display "cba".
In short, Serial.println will output exactly the bytes it finds in memory to the serial, until it encounters a zero byte. The serial monitor will try to display those bytes. But, unless you've crafted those values very carefully, all you'll get out of it is garbage - relatively few 8bit values map to printable characters, and even when they do they won't "look" anything like the raw data you had.
If your number happens to start with a zero byte in its binary little-endian representation, Serial.println won't print anything - like if you had given it an empty string.
If your number doesn't contain a zero byte, it will keep on reading memory past the storage allocated for payload until it finds one - possibly outputing much more "junk" than a 32bit variable could ever contain.


Possibility of installing custom firmware from Arduino Uno R3?

Yes, if your Uno (or other Arduino) uses an Atmega8U2 or 16U2 for its USB interface, you can use dfu-programmer or dfutool within a script to automate downloading of new firmware into the USB interface chip(s).  In general, that new firmware should support USB communication with a host, plus whatever new capabilities you want to provide.


What image formats are accepted for displays?

This is not a question of image format but of what format c accepts data in.

What you have is a python representation of binary data in hexadecimal encoding. That can only be used with python.

C represents hexadecimal values by prefixing them with 0x.

You will have to change your python code to output each byte individually and prefix it with 0x and separate each one with a comma. That can then be wrapped in an array structure.


Can't read data from registers using I2C

The following code shows, how I would read from a STC3100. But I own none of them, so I can not try the code. I would be very surprised if it works directly. Use it as an example. Perhaps we could improve it together. ;-)
#include <Wire.h>

#define STC_ADDRESS 0x70
#define MODE_REGISTER 0x00
#define CURRENT_LOW_REGISTER 0x06
#define VOLTAGE_LOW_REGISTER 0x08

int voltage, current;
int high_value = 0;

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

  Wire.begin();
  delay(100);
  // power on the STC
  Wire.beginTransmission(STC_ADDRESS);
  Wire.write(MODE_REGISTER);
  Wire.write(16);
  Wire.endTransmission();
}

void loop()
{
  Wire.beginTransmission(STC_ADDRESS);
  Wire.write(VOLTAGE_LOW_REGISTER);
  Wire.requestFrom(STC_ADDRESS, 2);
  delay(500);
  if( Wire.available() > 0 )
  {
    voltage = Wire.read();
    //Serial.print("REG 8 = ");
    //Serial.println(voltage);
  }
  delay(500);
  if( Wire.available() > 0 )
  {
    high_value = Wire.read();
    //Serial.print("REG 9 = ");
    //Serial.println(high_value);
    voltage += (high_value << 8);
    //Serial.print("voltage = ");
    //Serial.println(voltage);

  }
  Wire.endTransmission();

  Wire.beginTransmission(STC_ADDRESS);
  Wire.write(CURRENT_LOW_REGISTER);
  Wire.requestFrom(STC_ADDRESS, 2);
  delay(500);
  if( Wire.available() > 0 )
  {
    current = Wire.read();
    //Serial.print("REG 6 = ");
    //Serial.println(current);
  }
  delay(500);
  if( Wire.available() > 0 )
  {
    high_value = Wire.read();
    //Serial.print("REG 7 = ");
    //Serial.println(high_value);
    current += (high_value << 8);
    //Serial.print("current = ");
    //Serial.println(current);
  }
  Wire.endTransmission();

  Serial.print("V= ");
  Serial.print(voltage);
  Serial.print("   C= ");
  Serial.println(current);
}


How can big Arduino programs be analyzed easily?

Although there are programs who can automatically make some documentation (like doxygen), I haven't seen any software so far that can make USEFUL flowcharts or diagrams. The main reason is that such software does not know which are the important parts and which are not.

To do it manually:

Assuming your code contains multiple files, use an UML (Unified Modeling Language) application. Than if classes are used, you can easily port them to UML, otherwise assume each (.c) file is a 'class'.

By adding properties/fields and methods (functions) and drawing dependencies between the classes/files you get a good idea how everything works together.


How to use a variable format in `sprintf`

sprintf cannot be used to write data into String objects. More precisely, it is possible to come up with a "hackish" way to write the result directly into a String object, but the latter is definitely not designed for such use.

The target buffer should be an array of char, not a String. Which is what the compiler is telling you.

char buffer[64];
sprintf(buffer, "%%0%d", i);

or better

char buffer[64];
snprintf(buffer, sizeof buffer, "%%0%d", i);

The format string you used in your sprintf will generate %02 result (since i contains 2 at that moment). Why you are expecting 09 is not clear. Why are you expecting the % character to disappear is not clear either, considering that the format string seems to be deliberately designed to include it.
A String object cannot be used as the first parameter of fprintf. It is not clear what that fprintf is doing in your code.

Apparently you are trying to use sprintf to generate another format string at run time (using i as field width), which is later used to output the d variable. In that case that would be something like

char format[16];
snprintf(format, sizeof format, "%%0%dd", i);
fprintf(file, format, d);

That fprintf will indeed output 09.


Firstly you only have half of the first line of a GET request. Secondly the half you do have is badly formatted.

A GET request does NOT look like this:

GET http://jalambadani.ir/hadi/signal.php?value=10

A GET request DOES look like this:

GET /hadi/signal.php?value=10 HTTP/1.1
Host: jalambadani.ir
Connection: close
[extra blank line]

If you don't send the correct data you can't expect to get any response back.  You should learn the basics of what you are trying to do instead of just throwing random text a a web server.

Here is a full transcript of a GET request to your URL:

$ telnet jalambadani.ir 80
Trying 185.211.56.148...
Connected to jalambadani.ir.
Escape character is '^]'.
GET /hadi/signal.php?value=10 HTTP/1.1
Host: jalambadani.ir
Connection: close

HTTP/1.1 200 OK
Date: Tue, 25 Jun 2019 22:47:07 GMT
Server: Apache/2
X-Powered-By: PHP/5.6.35
Upgrade: h2,h2c
Connection: Upgrade, close
Vary: User-Agent
Content-Length: 31
Content-Type: text/html; charset=UTF-8

New record created successfullyConnection closed by foreign host.

In code that would be:

SerialGsm.print("AT+CIPSEND=83\r\n");
delay(1000); // I hate that. Look for a proper OK instead.
SerialGsm.print("GET /hadi/signal.php?value=15 HTTP/1.1\r\n");
SerialGsm.print("Host: jalambadani.ir\r\n");
SerialGsm.print("Connection: close\r\n");
SerialGsm.print("\r\n);


Analogue input 0 staying at 0 when sensing light with Arduino and a photocell

The two strips on either side of the bread board, color red and blue (typically) are power rails, and each strip is all connected. Your circuit connections that are on that strip are shorted together and will not work. I suggest following his layout exactly to begin with, and once you've learned the basics of breadboard connections, you can start doing your own layouts.


As others have said, an Arduino pin can't handle 12V, and can't handle anywhere near 10A of current directly. A digital pin on an Arduino is limited to 20mA, or 1/500 as much current as you need, at 5V, which is less than half the voltage you need.

If you try to connect 12V to a pin on an Arduino pin you will almost certainly destroy that pin, and may destroy the entire Arduino. If you try to source or sink even 1/100 of the current you are talking about through an Arduino pin, even at 5V, you will also probably destroy that pin and possibly the entire Arduino.

This sounds like a good application for a power MOSFET transistor. With that much current you'll need to put a heatsink on the transistor.

Here's one that would work:

https://www.sparkfun.com/products/10213

You'd use a logic pin from the Arduino to control the gate on the transistor, and the transistor would switch 12V at high current with very little resistance.

If the actuator is inductive, you'll need to protect the transistor with a suitably large "flyback diode" to protect it from the reverse current (or "back EMF") you get from an inductor when you remove power from it:

https://en.wikipedia.org/wiki/Flyback_diode


I can't add comment to your question so I post as an answer even though this is not much an answer. This is just a hint to solve your problem.
8x8 led matrix and 595s are pretty low-level stuff, so I assume you have some knowledge about electronics and programming in general.
I think your wiring is OK but I also think you misunderstand how 595 works.
Here is the flow taken from a library (ESP32) for 64x64 RBG LED panel using bunch of 595s:
uint8_t data[8]; // data for one row

digitalWrite(OE_PIN, HIGH); // disable output, 595 outputs go into high impedance state

for (int i=0; i<8; i++)
  shiftOut(DATA_PIN, CLOCK_PIN, MSBFIRST, data[i]);  // dump data out

digitalWrite(LATCH_PIN, LOW);  // pulse 1 clock
delayMicroseconds(1); // note 2*
digitalWrite(LATCH_PIN, HIGH); // latch is active high

digitalWrite(OE_PIN, LOW); // Enable output

I think now you know how to fix your code.
Note 1: I find those names SER, SRCLK, RCLK (on TI's datasheet) are confusing. I prefer the names SERIAL DATA INPUT, SHIFT CLOCK, LATCH CLOCK (on ONSEMI MC74HC595 datasheet) or better DATA, CLK, LATCH, OE, RESET.
Note 2: Check 74HC595 datasheet to see clock pulse width limit and speed limit. And if you are using UNO or MEGA (@16MHz), you are good without stretching the clock (data clock and latch clock). If you use higher speed MCU, e.g: ESP32@240MHz or STM32@72MHz, you have to consider clock stretching there and also inside shiftOut() function.
To improve your circuit, you should wire both OE of 595s to a Digital pin. You can also connect both latch pin into one digital pin. Every time you latch, botch 595 latch, and every time you enable output, both enable output.
So with your configuration, just shiftOut data normally for the 595 on the left and invert data for the 595 on the right, like this
#define DATA_COL_PIN 11
#define DATA_ROW_PIN 5
#define CLOCK_COL_PIN 13
#define CLOCK_ROW_PIN 7

#define OE_PIN 4 //use digital pin 4 to enable output on both 595s
#define LATCH_PIN 6 // or 12, but you must connect both latch inputs of both 595s together

uint8_t col = 0b00000001; // for the left 595
uint8_t row = 0b00000001; // for the right 595

digitalWrite(OE_PIN, HIGH);
shiftOut(DATA_COL_PIN, CLOCK_COL_PIN, MSBFIRST, col);
shiftOut(DATA_ROW_PIN, CLOCK_ROW_PIN, MSBFIRST, ~row); // ~row = 0b11111110 = invert_bits(row)
digitalWrite(LATCH_PIN, LOW);
digitalWrite(LATCH_PIN, HIGH);
digitalWrite(OE_PIN, LOW);

The code above is just for you to understand how it works. Normally, they would work on a buffer such as
uint8_t row[8]; // each byte is one row

And they do row scanning, turn one row ON at a time and just flip each column ON and OFF following the byte data of that row.
I stop here as this is going off-topic. You just ask what is wrong with your code right?
BTW, 595 can sink/source 35mA on each pin (70mA in total). So if you want to light up one row at a time with your setup, you should choose each current limiter carefully so that not to exceed 70mA in total.

70mA / 8xLED = 8.75mA for each LED (assume red LED)
(5v - 1v7) / 8.75mA = 377R

It's likely the resistors should be at least 377 ohm or 470 ohm for safety.


How to change this function in to a non-blocking function?

make buffer[] and i static.
get rid of the while() loop.

Like this:

int getTheNumber()
{
    static char buffer[4];
    static int i=0;
    // Input up to 3 numbers until we find a * or #
    char key = keypad.getKey();

    // If it's a number AND we have space left, add to our string
    if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
            return(-1)
        }
        // If it's a * or #, end
    else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
            int value = atoi(buffer);
            i=0;
            return atoi(buffer);
        }
}


Changing the analog reference does not change the resolution.  All it does is change the measurement range. It compresses the existing resolution into a smaller voltage range.

If you then compress the voltage range of your signal in the same way to fit into the now compressed analog reference voltage range (for example by reducing the supply voltage to 1.1V) you end up achieving absolutely nothing.

The only time you would use the 1.1V internal reference is if your incoming signal is already between 0V and 1.1V and you would otherwise be wasting the resolution above the highest voltage the sensor gives out.


How to pass 2 parameters with RCSwitch library?

The library you have chosen is not designed for transmitting information between nodes. It is intended for sending simple ON/OFF commands to RF-connected switches.  Bending it to send data in the way you want would be difficult.  Not impossible, but difficult.

Instead you should be considering a more suitable system, such as the popular RadioHead library. It appears to have Raspberry Pi support out of the box:

  Raspberry Pi Uses BCM2835 library for GPIO http://www.airspayce.com/mikem/bcm2835/ Currently works only with RH_NRF24 driver or other drivers that do not require interrupt support. Contributed by Mike Poublon.

Alternatively a small Arduino as an interface between the RF module and the Pi may be another option.


So far I only get 1's and 0's

Before moving into the LED parts, you have to make sure that your system can correctly read the DHT sensor. There are debugging example from arduino-info.wikispaces.com

  How can I change these integer values to output string say RED, GREEN or BLUE?

You can do it by simple if-else statement. This would be better than your original code, because there are multiple if's without any else which is (although not so significant) less optimal.

So, if put together, you can try:

void loop()
{
  int t,h,chk = DHT.read11(DHT11_PIN);

  switch (chk)
  {
    case DHTLIB_OK:
                Serial.print("OK,\t");
                break;
    case DHTLIB_ERROR_CHECKSUM:
                Serial.print("Checksum error,\t");
                break;
    case DHTLIB_ERROR_TIMEOUT:
                Serial.print("Time out error,\t");
                break;
    case DHTLIB_ERROR_CONNECT:
        Serial.print("Connect error,\t");
        break;
    case DHTLIB_ERROR_ACK_L:
        Serial.print("Ack Low error,\t");
        break;
    case DHTLIB_ERROR_ACK_H:
        Serial.print("Ack High error,\t");
        break;
    default:
                Serial.print("Unknown error,\t");
                break;
  }
  //moving on into next parts only if you get "OK" from serial reply, which means you successfully read the DHT11
  t = DHT.temperature;
  h = DHT.humidity;
  Serial.print(DHT.humidity, 1);
  Serial.print(",\t");
  Serial.println(DHT.temperature, 1);

  //----end of sensor reading and debugging

  if (t<=17)
  { //blue
   digitalWrite(bluPin, HIGH);
   digitalWrite(grnPin, LOW);
   digitalWrite(redPin, LOW);
   delay(100);
  } else
      if (t<20)
      {
       digitalWrite(grnPin, HIGH);  // aqua
       digitalWrite(bluPin, HIGH);
       digitalWrite(redPin, LOW);
       delay(100);
      } else
      if (t<23)
      {
        //....
      }
      //....
      //and goes on

 delay(1000);
}

And yes, as @Matt suggest, it would be better if you use PWM to control the RGB led which will give you (mathematically) 255*255*255 colour possibilities instead of 8 combinations from digitalWrite(). For example:

//....
//....
  if (t<20)
  { //aqua
   new_t = map(t,DHT11_min_temperature_reading,DHT11_max_temperature_reading,0,255);
   //you can do self research about DHT11 maximum and minimum temperature reading
   //parameters 0 and 255 is the minimum value of PWM(0) and the maximum value(255)
   AnalogWrite(bluPWMPin, new_t);
   AnalogWrite(grnPWMPin, 255-new_t);
   AnalogWrite(redPWMPin, 0);
   delay(100);
  }
//....
//....

Hope it helps :D


Editing a particular position in a file stored in SD card

The problem is that you are opening the file with FILE_WRITE.  That is a combined macro that is made up of:

#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)

The key one there is O_APPEND.  In the source code (SdFile.cpp) t says:

  O_APPEND - If set, the file offset shall be set to the end of the file prior to each write.

So the seek does nothing if O_APPEND is set, since it is overridden.

So instead you need to open the file without O_APPEND.  In fact you don't need to close and open the file at all, since if opened correctly you can hop around at will reading and writing.  The flag O_RDWR is a combination of O_READ and O_WRITE.

For example:

void update_file() {
  file = SD.open("misc.txt", O_RDWR);
  char character;
  while( (character = file.read()) != '\n') {}
  file.print(" Love, love, love.");
  file.close();
}

The O_CREAT flag that is part of FILE_WRITE will create a new file if you try and open one that doesn't exist. By omitting that SD.open will fail if the file you are trying to modify doesn't exist.


You can use this format to achieve what you described:

http://api.thingspeak.com/channels/(channel_id)/field/(field_id).(format)

Source: http://community.thingspeak.com/documentation/api/

Edit: It seems that there are no available options that can do what you want. But, you can tweak the response like in this example:

  int i;
  String response = "created_at,entry_id,field2 2015-10-22 19:30:00,14878,5";

  for (i = response.length()-1; i >= 0 ; i--)
  {
    if (s.charAt(i) == ',') break;
  }
  String value = response.substring(i+1);
  Serial.println(value); // This will show only 5


Is it ok to power a Wemos D1 R2 placed outside with a smartphone charger?

It might be okay, but it's better to play it safe. I would recommend putting the electronics (wemos/charger/extension cord) in a ziplock bag or plastic container designed to keep food in. You can cut holes for the sensors and power and then seal them in place. Have a look at this post. To answer your question. If water were to seep into the charger, it would have the potential to short the mains power in the charger. It could at the least ruin the charger. It might trip a breaker and or cause damage. Depending on the quality of the charger, water inside could expose the wemos to mains.
The charger may consume a small amount of extra power, but it once again depends on the quality. Apple chargers, for instance, do not. It won't be extreme, and is unlikely to go noticed, regardless of the charger.


How to convert digital signal to analog value

The problem seems to be clear to you: for slow systems a pwm signal can be considered analog, but measuring at higher rates and without a filter reveales the digital nature behind pwm and all you see is either logic high (1023) or low (0).
Possible solutions are:

apply a filter in hardware (LC low-pass)
apply a filter in software (e.g. by calculating a running mean)
attach interrupts to the rising/falling edge of your signal and measure the high/low time to calculate the duty cycle

Which of those options to choose will mainly depend on the PWM frequency you want to measure. For low frequency I recommend option 3 (special cases are duty cycles around 0% and 100% as there are no edges), for higher frequencies I would use option 1/2.


Getting the DS18B20 detected and temperature read

Vdd on the DS18B20 is not connected to anything.

According to the datasheet:

  When the DS18B20 is used in parasite power mode, the VDD pin must be connected to ground

  Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).

That means port 2 would always be high, right?

According to Temperature Sensor DS18B20 this is the wiring for non-parasitic power:

If you want the two-wire version (parasitic power) it would be:


How can I maintain switch state when in sleep mode?

You can get a latching relay. These come in two flavours - Unipolar, where you energise one pin to turn it on, and energise the other to turn it off, and Bipolar, where the direction of the current through the coil turns on or turns off.

Unipolar is easier to drive since you just need two transistors, diodes and resistors. Bipolar is harder, since you need a H-bridge (motor driver), but requires less wires to connect it up (2 as opposed to 3).

In both cases it is just a short pulse that is needed to switch the relay into a different state - there is no need to maintain the output, so is ideal for deep-sleep mode where everything is turned off except the RTC.


Why is the piezo buzzer not making any sound?

Both the code and the circuit have problems.

In the code:

• If the while (buttonState == LOW) loop is ever entered, it will never be left, because buttonState, the controlling variable, does not change within the loop.

The simplest fix is to remove the line bool buttonState = digitalRead(buttonPin); and replace while (buttonState == LOW) with while (!digitalRead(buttonPin)), which says to loop while digitalRead(buttonPin) is not true; ie, while it is false, or low.

• The empty braces, { } at the end of the while loop are superfluous and should be deleted.

In the circuit diagram:

• Neither of the leads of the buzzer is attached to the Arduino circuit, so it won't make any sound.  Note, tone(12,260); tells the Arduino to use pin 12 for tone output.

To fix this problem, run a wire from pin 12 to one side of the buzzer, and a wire to ground for the other side of the buzzer.

• A blue LED in series with a red LED might or might not turn on when supplied with 5 V.  For example, if the red LED takes 1.8 V and the blue LED takes 3.3 V to turn on, the 5.1 V total is too high to be turned on by 5 V signals.  Remove one of the two LEDs, and move the wires to the other LED to complete a circuit.


Problem for control speed of a DC motor with a L298N

You do need the ground wire. The reason it 'works' without it is that enable input effectively then has an aerial connected and is responding in the same was as if you touch the input jack on an amplifier and hear a buzzing sound.

There is a link behind the blue connectors that enables the onboard 5v regulator. I assume you have this fitted, or it wouldn't work with the jumper as you describe.

There is a tutorial here : http://www.instructables.com/id/How-to-use-the-L298-Motor-Driver-Module-Arduino-Tu/

I can't see anything different from what you're doing that would cause it to fail, but perhaps you have a problem with pin 9 from your board - you might have damaged it by misconnection, as certain ways of wiring that schematic could put 12V on the arduino pin.  You could also try using pin 13 : the arduino LED should then be lit in sympathy with the PWM signal and you'll know it's working.


Does restarting Yún configuration mess up Arduino or its SD card?

It sounds like your SD card has likely failed. Try connecting it to a computer with an SD card reader. If it works at all, back it up immediately if you have files you wish to keep. Then try reading and writing files on it. Also if you have a spare SD card, try to use that in the Yun after setting it up appropriately. That should help narrow down the cause to either the Yun or the SD card.


Assigning value inside structure array outside setup and loop functions

You can't access array contents in the global scope like that.  You have to assign the entire block of data in one go:

struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
};

struct trap_game_details trap_game_details[2] = {
    { 10, 5, 1, 100, 4 },
    { 8, 23, 5, 95, 8 }
};

Items in the global scope aren't executed - only things in functions are executed.  Accessing individual parts of an array or struct like you are trying to is a programatic operation, so can't be executed since it's not in a function.


I am new to arduino please help me in understanding this code

client.read() returns exactly one byte from the serial input buffer for the port connected with object client. That is why you use a char variable. The name c is not relevant.

The next line, Serial.write(c) then writes that same character to the main serial port.

The code basically reads from one serial port and writes the same data immediately to the other serial port.


As described in the operation part of the datasheet section, OC1x is double-buffered; the code sets a shadow buffer to a given value and then at some point the hardware copies the shadow buffer to the register that controls operation. "Immediate" means that the buffer is completely transparent since the value is copied immediately.

The difference between modes 4 and 12 is that mode 4 allows the use of ICP1 for input capture and mode 12 allows the use of OC1A for waveform generation.


Why do you need to shift bits when reading from an analog sensor?

You read bytes in the order:

Most significant byte   (let's call this msb)
Least significant byte  (let's call this lsb)

The formula to get to real value is msb * 256 + lsb
256 because this is the value of the maximum value of one byte, + 1. which is bits (2 ^ 8 = 256).

However, a CPU is normally faster in bit operations than in arithmetic operations.

Assume msb is 10101010
and lsb is    11001100

Now below is the table with the calculation order

sensor value             msb         lsb
00000000 00000000        10101010    11001100
00000000 10101010                                sensor value = msb
10101010 00000000                                msb << 8, or msb * 256
10101010 11001100                                (msb << 8) + lsb, or (msb * 256) + lsb

Actually I would expect a cast to an unsigned byte type (8 bits). However, if the values msb or lsb would be floating points/doubles, than the remainder will be removed, leaving an integer (whole) number.


How do you combine 2 different sketches together

This question comes up all the time. I'll explain what you need to do in general terms. Try it, and if you have problems, post a question showing your 2 starting sketches, your attempt at combining them, and detailed info on what goes wrong.

There are 3 basic parts to the main.ino file of an Arduino sketch:

The declarations:

#includes
#defines
global variables

The setup() function
The loop() function.

You need to merge those parts separately.

You should merge the subsections of the declarations together (Put all the #includes together, all the #defines together, and all the global variables together. Remove any duplicate #includes.

If there are any duplicate #defines or global variables, you need to figure out how to resolve that. If the symbol and the name are the same

The same applies to the two setup()-functions you want to merge. Also, duplicate parts usually need to be there only once (considering things like Serial.begin(...)).
Also the two loop()s are combined the same way, but if you make use of delay()s you must keep in mind that these will sum up in the final sketch, making it slower than the initial sketches were. It might also might (probably won't) work correctly. You will likely need to refactor your code to use millis() instead of delay().

After combining two sketches this way your global variables will be shared. You'll need to resolve any naming conflicts, or rename global variables that are different in your source sketches but should be the same. You may also have shared resources like sensors and LCD displays.

(Note that if the 2 sketches use the same resource for different things it gets more complicated, e.g. using the same pin for different purposes, using the same timer in both sketches, or using the same interrupt. Those things will require analysis and case-by-case changes.)


Error: function was not declared in this scope when using a library without classes

When creating a library with functions that are not mentioned in the header file, the order of appearence in the .cpp file suddenly becomes relevant. In order for a function to be used by another function, it has to be declared first.

The first possibility in this example would be to define foo2 before defining foo1 like this:

#include "Lib.h"

// Definition of foo2
static void foo2() {}

// Definition of foo1
static void foo1(){
    foo2();
}

However, this is not only bad practice, it also doesn't always work. If there is any sort of recursive procedure that makes functions call each other, you can't define both of them before the respective other at the same time.

The more elegant and foolproof way to do this is by declaring each function first like you usually would in the header file and then defining what they actually do. The .cpp file of this library would then look like this:

#include "Lib.h"

static void foo1(); // Declaration of foo1
static void foo2(); // Declaration of foo2

// Definition of foo1
void foo1(){
    foo2();
}

// Definition of foo2
void foo2() {}


Do we need another controller when using ArduPilot?

There are a few key points worth making before answering your question:

Ardupilot has undergone a re-branding and is now known as APM; this change was made to reflect that the technology has grown beyond strictly using an Arduino environment. You can see this for yourself at their website.
The term(s) Ardupilot/APM have been used somewhat interchangeably for both the hardware and software. This can be confusing so I'll refer to the hardware as an "APM Kit"

Can I simply program the ArduPilot, connect a Wireless interface to it and merrily be able to control it ?

Yes, 3DRobotics offers APM Kits that are plug-and-play hardware packages with preloaded firmware. They (optionally) supply all of the components needed to operate a small unmanned hobby aircraft including:

Power module
Transmitter and receiver for the APM-to-Ground-Station link
GPS module w/ compass

The user is generally expected to provide:

Airframe
Batteries
Servos
RC transmitter and receiver
An additional voltage-regulator/BEC if using high-torque servos
A computer (groundstation)

However, the unspoken question is:

How easy is it to setup Ardupilot/APM to work safely and correctly?

In truth, it takes considerable effort to put together a properly working system. The plug-and-play hardware saves you a great deal of trouble but tuning and operating an RC aircraft requires a different skillset. If you're experienced in RC, this may not be a problem.

From experience, you can expect to spend a number of weekends configuring and tuning APM (the software) even if you have a perfectly tuned RC aircraft.


very lightweight low power microcontroller with memory?

I made up a small torch locator which used an ATtiny85 powered from a button-cell (CR2032). It looks like this:

Other side:

That currently weighs 5.9g. The battery-holder weighs 1.6g so you could save that by making a more light-weight holder (perhaps a bit of plastic for insulation, and soldering directly to the battery). The chip socket weighs at least 0.5g, so you could save that as well by soldering to the processor pins. So we are down to 3.8g.

The ATtiny85 has 512 bytes of EEPROM which you could use to log readings to. I'm not sure about a clock if you are trying to save weight, but if you start it at a known time, you could have a reasonable estimate of the time by using the millis() function to find miliiseconds since startup.

I made another one a while ago which flashes an LED every couple of seconds:

That is similar. The processor is there (upside down under the chip socket) and the battery is underneath. That weighs 6g. The battery has lasted a couple of years, and that is flashing an LED every couple of seconds!

Instead of the LED you could have a thermistor to read the temperature.

You could program it to take a reading every few hours and save it to EEPROM. Then when instructed (eg. by joining a couple of pins) it could output the readings to another pin (via serial).

You could save more weight by using SMD (surface mounted) devices, and perhaps using a tiny circuit board you could get made up.

Code

The code for my torch locator is below. Of interest is the fact that it sleeps most of the time. Also it sleeps during the ADC sampling. Although in my case I am measuring a LDR (light dependent resistor) the code for measuring a thermistor would be similar. You just need to do some calculations at the end to turn the reading into a temperature.

// ATtiny85 torch detector
// Author: Nick Gammon
// Date: 25 February 2015

// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

/*

  Pin 2 (PB3) <-- LDR (GL5539) --> Pin 7 (PB2) <----> 56 k <----> Gnd

  Pin 5 (PB0) <---- LED ---> 100 R <-----> Gnd

*/

#include <avr/sleep.h>    // Sleep Modes
#include <avr/power.h>    // Power management
#include <avr/wdt.h>      // Watchdog timer

const byte LED = 0;          // pin 5
const byte LDR_ENABLE = 3;   // pin 2
const byte LDR_READ = 1;     // Ain1 (PB2) pin 7
const int LIGHT_THRESHOLD = 200;  // Flash LED when darker than this

 // when ADC completed, take an interrupt
EMPTY_INTERRUPT (ADC_vect);

// Take an ADC reading in sleep mode (ADC)
float getReading (byte port)
  {
  power_adc_enable() ;
  ADCSRA = bit (ADEN) | bit (ADIF);  // enable ADC, turn off any pending interrupt

  // set a2d prescale factor to 128
  // 8 MHz / 128 = 62.5 KHz, inside the desired 50-200 KHz range.

  ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);

  if (port >= A0)
    port -= A0;

#if defined(__AVR_ATtiny85__)
  ADMUX = (port & 0x07);  // AVcc
#else
  ADMUX = bit (REFS0) | (port & 0x07);  // AVcc
#endif

  noInterrupts ();
  set_sleep_mode (SLEEP_MODE_ADC);    // sleep during sample
  sleep_enable();

  // start the conversion
  ADCSRA |= bit (ADSC) | bit (ADIE);
  interrupts ();
  sleep_cpu ();
  sleep_disable ();

  // reading should be done, but better make sure
  // maybe the timer interrupt fired

  // ADSC is cleared when the conversion finishes
  while (bit_is_set (ADCSRA, ADSC))
    { }

  byte low  = ADCL;
  byte high = ADCH;

  ADCSRA = 0;  // disable ADC
  power_adc_disable();

  return (high << 8) | low;

  }  // end of getReading

// watchdog interrupt
ISR (WDT_vect)
{
   wdt_disable();  // disable watchdog
}  // end of WDT_vect

#if defined(__AVR_ATtiny85__)
  #define watchdogRegister WDTCR
#else
  #define watchdogRegister WDTCSR
#endif

void setup ()
  {
  wdt_reset();
  pinMode (LED, OUTPUT);
  pinMode (LDR_ENABLE, OUTPUT);
  ADCSRA = 0;            // turn off ADC
  power_all_disable ();  // power off ADC, Timer 0 and 1, serial interface
  }  // end of setup

void loop ()
  {
  // power up the LDR, take a reading
  digitalWrite (LDR_ENABLE, HIGH);
  int value = getReading (LDR_READ);
  // power off the LDR
  digitalWrite (LDR_ENABLE, LOW);

  // if it's dark, flash the LED for 2 mS
  if (value < LIGHT_THRESHOLD)
    {
    power_timer0_enable ();
    delay (1);  // let timer reach a known point
    digitalWrite (LED, HIGH);
    delay (2);
    digitalWrite (LED, LOW);
    power_timer0_disable ();
    }

  goToSleep ();
  }  // end of loop

void goToSleep ()
  {
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  noInterrupts ();       // timed sequence coming up

  // pat the dog
  wdt_reset();

  // clear various "reset" flags
  MCUSR = 0;
  // allow changes, disable reset, clear existing interrupt
  watchdogRegister = bit (WDCE) | bit (WDE) | bit (WDIF);
  // set interrupt mode and an interval (WDE must be changed from 1 to 0 here)
  watchdogRegister = bit (WDIE) | bit (WDP2) | bit (WDP1) | bit (WDP0);    // set WDIE, and 2 seconds delay

  sleep_enable ();       // ready to sleep
  interrupts ();         // interrupts are required now
  sleep_cpu ();          // sleep
  sleep_disable ();      // precaution
  }  // end of goToSleep


Please note: the question originally had no mention of trying to use c_str() - so I'm not a retard

Point 1 JSON actually is a string
Point 2 your data_json varibale is a String
Point 3 client.publish doesn't work take String as the payload argument, it takes either const char * or const uint8_t *

So, what you can simply do is use Strings c_str method to pas a const char * as the payload

i.e.

client.publish("/devices/data", data_json.c_str());

Point 4 - if you read the pubsubclient documentation, you'll see that

  The maximum message size, including header, is 128 bytes by default. This is configurable via MQTT_MAX_PACKET_SIZE in PubSubClient.h. Longer messages can also be sent with the publish_P() method.

so what you may be experiencing now is a message size too big for pubsubclient to handle - set a larger packet size before including the PubSubClientHeader.h

#define MQTT_MAX_PACKET_SIZE 1024
#include <pubsubclient.h>

If that also doesn't work, try

client.publish_P("/devices/data", data_json.c_str());


it is somehow possible to make a ADC timer interrupt

The ADC and the timers are two different things. If you mean a timer interrupt, I'm not sure why you would want that. If you mean an ADC interrupt, yes you can do do that.

Here is some example code from my page about the ADC which shows using the interrupt (on a Uno):

const byte adcPin = 0;
volatile int adcReading;
volatile boolean adcDone;
boolean adcStarted;

void setup ()
{
  Serial.begin (115200);
  ADCSRA =  bit (ADEN);                      // turn ADC on
  ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
  ADMUX  =  bit (REFS0) | (adcPin & 0x07);    // AVcc and select input port

}  // end of setup

// ADC complete ISR
ISR (ADC_vect)
  {
  adcReading = ADC;
  adcDone = true;
  }  // end of ADC_vect

void loop ()
{
  // if last reading finished, process it
  if (adcDone)
    {
    adcStarted = false;

    // do something with the reading, for example, print it
    Serial.println (adcReading);
    delay (500);

    adcDone = false;
    }

  // if we aren't taking a reading, start a new one
  if (!adcStarted)
    {
    adcStarted = true;
    // start the conversion
    ADCSRA |= bit (ADSC) | bit (ADIE);
    }

  // do other stuff here

}  // end of loop

I should point out that if you do an analogRead it blocks until the read is done, so the very next line to be executed after analogRead will be when the data is ready.


Trinket: Battery + USB at the same time?

From https://learn.adafruit.com/system/assets/assets/000/010/773/original/adafruit_products_trinket3.png?1378223258 it looks OK -- there are blocking diodes D3 and D2 that prevent backfeeding either the battery or the USB +5.

If you are worried, or want to monitor battery-only performance, you could make a special USB cable with the +5 red wire disconnected, and rely on the in-circuit battery to power the device, while still using the USB data lines.  See https://www.pjrc.com/teensy/external_power.html Option 2 for an example of the cable surgery.


Custom built Arduino is not working - double blinks

It's a reasonably clear photo (another couple would help) however I do see at least one major problem. Pin 8 (and pin 22) are Ground, but I don't see any wires running to that. Also the 22 pF (or similar) capacitors connected to the crystal should have their other sides grounded.

I suggest you look at my page Breadboard Arduino which has clear photos and wiring guides. In particular:

Notice the ground wire, and how the capacitors are connected.

I suggest you double-check all wiring, and make sure it is very similar to this:


Accelerometer Z Value off a significant amount, all other values reasonable

Accelerometer static errors are usually not anywhere near that large, so I suspect your scaling code is not behaving correctly. You could verify this by turning the accelerometer on its side and see if the Z axis retains a +7G value, or if the X/Y axis instead becomes too large.


Let's look at a simpler example:

void setup ()
{
  String content = "Basic";

  attachInterrupt (digitalPinToInterrupt (2),
                   []()
  {
    Serial.println(content);
  },

  FALLING );

}  // end of setup

void loop () { }

This gives the error:

/tmp/arduino_modified_sketch_182173/sketch_jan25a.ino: In lambda function:
sketch_jan25a:8: error: 'content' is not captured
     Serial.println(content);

Why? Because you are using a local variable content in a lambda function which runs at global scope. That is, content is not available to it, because it is inside setup.

To capture it, you can put it in the capture list:

  attachInterrupt (digitalPinToInterrupt (2),
                   [content]()  // capture content

However I found that my example doesn't compile even then.

I think the reason for that can be found here: Lambda Functions in C++11 - the Definitive Guide

  How are Lambda Closures Implemented?

  So how does the magic of variable capture really work? It turns out that the way lambdas are implemented is by creating a small class; this class overloads the operator(), so that it acts just like a function. A lambda function is an instance of this class; when the class is constructed, any variables in the surrounding enviroment are passed into the constructor of the lambda function class and saved as member variables.

You can't pass an instance of a class to attachInterrupt because there is a hidden *this variable that needs to be passed to class instances, and ISRs don't do that.

Now your example isn't an ISR, but probably the same remarks apply.

I don't think there is an enormous amount of point of using lambda functions here. If you must, move content inside the lambda, since that is where you are using it.

Or failing that, make it global scope.

The closest I could get to something that compiled was:

void setup ()
{
  const int content = 42;

  attachInterrupt (digitalPinToInterrupt (2),
                   [=]()
  {
    Serial.println(content);
  },

  FALLING );

}  // end of setup

void loop () { }

Honestly though, I think using lambda functions here just makes your code obscure.


not going to pretend i understand why all my keypad numbers are 48 higher than the number printed on the keypad but:
int key2 = key -48;

works


Is this the right way to blink a character on LCD?

To blink a number (alternate between the number and empty space(s)), you could try the BlinkLCD class in this sketch. It only works with numbers from 0 to 4294967295 or text (char array, 16 characters max). It does not work with floating point numbers.

// 4540 bytes.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

class BlinkLCD{

  private:

    byte m_blinkState, m_startPosition, m_dataLength;
    unsigned long m_dataToBlink, m_previousMillis, m_blinkRate;
    char m_text[16 + 1];

  public:

    BlinkLCD(): m_blinkState(0), m_startPosition(0), m_dataLength(0),
                m_dataToBlink(0), m_previousMillis(0), m_blinkRate(500),
                m_text(){}

    void Update(){

      unsigned long m_currentMillis = millis();

      if(m_currentMillis - m_previousMillis >= m_blinkRate){

        byte m_row = 0;
        m_blinkState = !m_blinkState;
        m_previousMillis = m_currentMillis;

        if(m_startPosition > 15){
          m_startPosition -= 16;
          m_row = 1;
        }

        lcd.setCursor(m_startPosition, m_row);

        if(m_blinkState){
          if((unsigned)strlen(m_text) > 0){
            lcd.print(m_text);
          }
          else{
            lcd.print(m_dataToBlink);
          }
        }
        else{
          for(byte i = 0; i < m_dataLength; i++){
            lcd.print(" ");
          }
        }
      }
    }

    void SetBlinkRate(unsigned long blinkRate){
      m_blinkRate = blinkRate;
    }

    void SetNumber(unsigned long dataToBlink){
      m_dataToBlink = dataToBlink;
    }

    void SetLength(byte dataLength){
      m_dataLength = dataLength;
    }

    // LCD top row, columns 0 - 15
    // LCD Bottom row, 16 - 31
    void SetStartPosition(byte startPosition){
      m_startPosition = startPosition;
    }

    void SetText(char text[]){
      strcpy(m_text, text);
    }

};

BlinkLCD TopRowLCD;
BlinkLCD BottomRowLCD;
BlinkLCD BottomRowLCDtext;

void setup(){
  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.print("Temperature 35 C");
  lcd.setCursor(0, 1);
  lcd.print("Num = 4294967295");
}

void loop(){

  // Simulate sensor data.
  static byte counter = 35;
  static unsigned long previousMillis = 0;
  unsigned long currentMillis = millis();

  // Update the temperature reading every 2 seconds.
  if(currentMillis - previousMillis >= 2000){
    previousMillis = currentMillis;
    counter++;
    if(counter > 45){counter = 35;}
    lcd.setCursor(12, 0);
    lcd.print(counter);
  }

  // Blink the temperature reading if it's over 40 C.
  if(counter > 40){
    TopRowLCD.SetNumber(counter);
    TopRowLCD.SetStartPosition(12);
    TopRowLCD.SetLength(2);
    TopRowLCD.SetBlinkRate(250);
    TopRowLCD.Update();
  }

  // Blink a number on the second row of the LCD
  // with a default blink rate of 500ms ON, 500ms OFF.
  BottomRowLCD.SetNumber(4294967295);
  BottomRowLCD.SetStartPosition(22);
  BottomRowLCD.SetLength(10);
  BottomRowLCD.Update();

  // Blink some text with at the default blink rate.
  BottomRowLCDtext.SetText("Num");
  BottomRowLCDtext.SetStartPosition(16);
  BottomRowLCDtext.SetLength(3);
  BottomRowLCDtext.Update();

}


I used a simple optical encoder and the little disks that came with my kit.  The encoders cost < £1 for 2 of them.

Failing that use an accelerometer and measure the lateral motion, should also cost about £1.


Error: Cannot find module 'serialport'. node.js, Arduino Yun

I solved the problem by following these steps:

Make a folder node_modules in mnt/sda1/

cd /mnt/sda1

wget http://wiki.linino.org/lib/exe/fetch.php?media=wiki:serialport-1.6.1_mips-25-ubuntu.tar.gz -O serialport-1.6.1_mips-25-ubuntu.tar.gz

run $ tar xvf serialport-1.6.1_mips-25-ubuntu.tar.gz -C /mnt/sda1/node_modules


What is wrong with my code? Did you forget '()'?

You're trying to assign a value to a function. That is almost certainly wrong.

SimbleeBLE.sendInt(Playp);


Can't program Arduino via Bluetooth (HC-06) with a Mac

The on-board USB-to-serial pulses the reset line to start the bootloader. HC-0x don't have the extra signal available that USB uses for that so you'll have to manually reset the Arduino just as - or very slightly after - you click to start the upload on your Mac; you may need to experiment to get the timing right, but once you know it, it isn't hard to do. Keep Rx & Tx crossed as you do for Bluetooth terminal communication. And even with all that, I've never achieved anything like USB upload speeds (baud rate for baud rate) using Bluetooth.

Update:
In brief, it could be timing, baud-rate, or pairing.

I find it easy to get the timing: hold reset / click (and let go) the upload button / release reset. It doesn't need to be so fast that it's a challenge to coordinate but do it faster than counting seconds.

Your HC-06's baud rate will have to match the baud-rate your boot-loader expects. It looks like Uno's bootloader's use 19200 baud (and there are some way older ones that used 9600). My bare, pre-programmed chips' boot-loaders from Adafruit.com use 57600 baud. Your preferences.txt file should contain a line like 'atmega328o.upload.speed=115200'; assuming you're able to upload via USB, then use this baud rate for the HC-06. (The path to your preferences file is displayed on the Arduino IDE's preferences dialog.)

The 'Resource busy' message sounds like your Mac isn't paired with your HC-06. In the MacOS Bluetooth System Preferences pane, pair the Mac with the HC-06 and be sure HC-06's LED is on steady (not blinking).


I was going to post this as a comment, as it is by no means a definitive answer, but I wanted to include the schematic to help the OP understand what may be happening. When the OP provides further information, I will edit/delete as appropriate.

Without additional information, it is difficult to answer your question:

As Jot asks, how did you determine that you have a short?

Did you test for continuity between VCC and GND, using a DMM?
Or did you encounter the short by connecting to a power supply and blowing a fuse?

If you did perform a check of the resistance between VCC and GND, using a DMM, what was the value that you obtained?
Is it possible that what you think is a short, could be simply a temporal charging of the capacitors by the DMM (if that is what you used to determine the short)?

Here is a schematic of your board, which may help:


There are many comments, but no answer yet. This answer has only a few basic rules.

The first thing to do is to see if the problem can be replicated with a small sketch and to check the voltages.

The arduino mega 2560 works best at 5.0V, or maybe a little less. It is not reliable at 4V. When powering it with a 5V power supply, the usb connecter is the best option to power the arduino board. Powering the arduino board via the 5v pin is not advised. When a strong power supply is connected to the 5v pin, the voltage regulator can be blown.

When something is not working, fall back to something that is reliable. For example a SD module with a HC4050 to shift the voltage levels. The resistors make the signal weaker.

Make a small test sketch without the use of the String object. The more experienced someone is with arduino, the more he or she tells to avoid the String object with avr microcontrollers.

There are counterfeit SD cards. One of those might turn up in your hands someday. Beside that, not every SD card is compatible with the arduino SD library.

In your situation it is suspicious that the file system is okay, the filenames are okay, the first text is okay, but when data is written it suddenly goes wrong. That is a strong indication for a memory problem.

When data to a display or SD card is wrong, then send it also to the serial monitor. You have to know what is actually written to the SD card.


Splitting a float into bytes for storage in FRAM (like EEPROM)

I solved it with the use of UNION:

//---------------------------------------------------------
union Scomp_float {
  // si utilizza union x float
  float temp;
  char byte_s[4];
} S_float;

//---------------------------------------------------------
//-------------------------FLOAT--------------------------------
float mioFlo = 123456.29;
byte f0 = 0;  // contengono i byte del float
byte f1 = 0;
byte f2 = 0;
byte f3 = 0;
S_float.temp = mioFlo;
f0 = S_float.byte_s[0];
f1 = S_float.byte_s[1];
f2 = S_float.byte_s[2];
f3 = S_float.byte_s[3];
Serial.println(f0);
Serial.println(f1);
Serial.println(f2);
Serial.println(f3);
fram.writeEnable(true);
fram.write8(7, f0);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(8, f1);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(9, f2);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(10, f3);
fram.writeEnable(false);
S_float.byte_s[0] = fram.read8(7); // si ricompone il float
S_float.byte_s[1] = fram.read8(8);
S_float.byte_s[2] = fram.read8(9);
S_float.byte_s[3] = fram.read8(10);
float masterFloat = S_float.temp;
Serial.println(masterFloat);
//-------------------------FLOAT--------------------------------


Arduino Serial Monitor displaying weird characters and changes spelling

Your code for the most part looks ok. Your symptoms indicate a Baud mismatch or the receiver is not getting all of the bits. Try doing without the delay's, even reducing them may help. Note when in a delay the processor is committed and cannot do anything else.  See if that helps. 115000 baud is quit hot for the Arduino and software serial. Maybe you can slow things down a little and see if that helps.


Joystick (github.com/MHeironimus/ArduinoJoystickLibrary) lib did the job. @chrisl, thx for the patience.


How to drive Arduino UNO as a counter triggered by 555 timer's output (astable mode)

You need to create a finite state machine with 2 states:

Waiting for input from 555 to go high.  When this happens increment the counter & advance to the next state.
Waiting for the input from the 555 to go low.  When this happens advance to the next state.  That is, the first state.

In the following Arduino "State Change Detection (Edge Detection) for pushbuttons" example / tutorial you do not need the complex code to debounce the switch.  However, the edge detection and state machine portion of the code can likely be applied to your project.


Arduino can not provide enough current for ESP8266 operations. Use external 3.3V power supply, I would recommend 500ma. Also don't forget to put a small cap between vcc and ground. 100uf should do it.


What Version of the Sketch did I leave on there?

First, you have to store the desired information in your sketch.

#define VERSION F("0.01 4-Apr-2019")

void setup() {
   Serial.begin(9600);
   Serial.print(F("Test Sketch V"));
   Serial.println(VERSION);
}

void loop() {
}

Of course any other way might work as well:

Only print it, if at reset a test button is pressed
Check for a Serial command and respond the version info.
Don't print it, but use avrdude and a programmer to read the FLASH memory and search it for the version string. (Similar to jot's comment above)


How do I specify a working directory when saving to SD card?

You're creating a directory, and then not writing the file into it.

You need to change the filename to /DCIM/100NIKON/DSCN0000.JPG";

Note that SD.open() takes the full filepath to the file, not just the file*name*.

From the Arduino Docs:

  The file names passed to the SD library functions can include paths
  separated by forward-slashes, /, e.g. "directory/filename.txt".
  Because the working directory is always the root of the SD card, a
  name refers to the same file whether or not it includes a leading
  slash (e.g. "/file.txt" is equivalent to "file.txt"). As of version
  1.0, the library supports opening multiple files.

(emphasis mine)


Is it possible to increase the Arduino's input and output pins?

You could use an MCP23017 port expander to get 16 more pins. It communicates via I2C. The pins can be set as inputs, outputs, or inputs with pullups.

Adafruit has a library for the expander: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library

This is the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf

As an alternate solution, you could just add another Arduino Mega to your project, and have them both communicate via serial. You could set up state machines on each one (like in Mr. Gammon's tutorials: http://www.gammon.com.au/statemachine) for fast communication. That way you could easily add an extra 52 pins to your project.


Are there flexible pressure sensors for Arduino that can measure forces of at least 600 lbs?

Sensors such as you describe are usually called "Load Cell".

At the 600 pound weight, I haven't found any "flexible" load cells. A sensor would have to be quite robust.

Flexible might not be the best answer.

This load cell page has quite a range of load cells, several thousand pounds, also not very inexpensive.

This might be difficult to install in running shoes :


What is actually an IC (Integrated Circuit)?

It's funny that you have a picture of one in your profile pic. :)

The arrow points to the most obvious integrated circuit or chip in you pic, there is another square one to the left of the TX and RX markings.  There are lots of different types of ICs -- most are black and come in different shapes and sizes, different number of legs, but most have some form of writing on the back that Google can use to locate the data sheet, or general help.  Have a quick look on Wikipedia for a more authoritative description.


Mega code not compiling on Wemos Mega board

The Wemos/Mega board and IDE setup is complex and not for the faint hearted. Here is the table for the DIP switch setting:

1=ON  2=ON  3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (ATmega2560<->ESP8266)
1=OFF 2=OFF 3=ON  4=ON  5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)
1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=ON  8=OFF (USB<->ESP8266 (Update firmware or sketch))
1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=OFF 8=OFF (USB<->ESP8266 (communication))
1=OFF 2=OFF 3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (All independent)

Table DIP switch Special Solution:

1=ON 2=ON 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <-> ATmega2560<-> ESP8266)
USB converter CH340G connect to RX0/TX0 of ATmega2560
ESP8266 connect to RX3/TX3 of ATmega25

https://arduino-esp8266.readthedocs.io/en/latest/index.html for ESP8266 documentation.

Set the Additional Boards URL to http://arduino.esp8266.com/stable/package_esp8266com_index.json in preferences

Under Tools select Board then Board Manager, then install the esp8266 by ESP8266 Community

The Arduino IDE setup requires understanding what board setting and communication setting to use to build and upload a sketch.

Under Tools select Board then select the "Arduino/Genuino Mega or Mega 2560"

Set the DIP switches on the actual board to 1=OFF 2=OFF 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)

That was the DIP switch and USB setup.

Ref. https://forum.arduino.cc/index.php?topic=578430.0

The error ESP8266WiFi.h: No such file or directory is easy. The file name should be a string: #include "ESP8266WiFi.h".


Is it possible to have a harddrive or sd card feed data into the Arduino to be executed and then feed more data in and so on. If it is possible how is it done?

A harddrive would be difficult to connect, but an SD card will work just fine.

You can write a sketch that reads data from an SD card. There is library support for both SD and FAT16/32 file systems.

Another interpretation of your question is; is it possible to load a sketch from an SD card. The answer is yes; there are a number of projects that have done that.

Cheers!


How to dynamically switch between between 2 objects?

The problem is that you're declaring multiple pointer variables called CActiveLCD in the _UpdateLCD() function. You do it once at the start of the function like this:

LiquidCrystal* CActiveLCD;

You then declare a new and totally separate pointer inside the if block like this:

LiquidCrystal** CActiveLCD = &_Clcd2;

This is called masking. The original pointer you declared at the start of the function still exists, but you can't access it because it's temporarily replaced by the new one. When the if block finishes, that new pointer is destroyed (it goes out of scope) and the old one is available again.

All of that means you never actually store a value in the original pointer variable. The result is that it contains an arbitrary memory address, so attempting to use it at the end of the function results in undefined behaviour.

When you are assigning to the pointer inside your if block, you need to do it like this:

CActiveLCD = _Clcd2;

Notice that this doesn't declare a new CActiveLCD pointer. It simply copies _Clcd2 into the existing one. Additionally, it's important not to use the address-of operator here (&). Adding that in this context gives you a pointer-to-a-pointer. It is technically legitimate in C++, and sometimes does serve a useful purpose, but it's not what you want to do here.

As a side note, when declaring a pointer variable it's usually a good idea to initialise it to something. If you're not assigning an actual address to it right away then initialise it to 0, like this:

LiquidCrystal* CActiveLCD = 0;

This means you can check the pointer later on before using it. If it's 0 then you know it's not got a valid address yet so it's not safe to use. This isn't always strictly necessary, but it can help avoid some frustrating bugs.


Accessing struct's variable parametrically on ESP8266

You can do it but it can be awkward. You'll need an array of structs, each member of which describes one member of your 'struct parameters' - essentially, an expansion of your present 'keys[]'.
Then you can consult this array randomly or in order to find the name, data-type, and memory offset of a given parameter (indexed by parameter order), or search it, to access the same information by parameter name.
Here's your parameter struct with some (incomplete but runnable) code to list the descriptor array, and incidentally, show how to build and use the array. Note that the code compiles but with a warning that a member of your 'parameters' was not initialized. I chose not to fix that; it isn't used here and doesn't prevent compilation.
struct parameters
{
  bool ext_inputs;
  bool auto_relay_off;
  bool useSerial;
  bool useWDT;
  bool useOTA;
  bool useResetKeeper;
  bool useFailNTP;
  bool useDebugLog;
  char deviceTopic[20];
  char groupTopic[20];
  char prefixTopic[20];
  int inputUpPin;
  int inputDownPin;
  int outputUpPin;
  int outputDownPin;
  int inputUpExtPin;
  int inputDownExtPin;
  int auto_relay_off_timeout;
};
//char *keys[] = {"ext_inputs", "auto_relay_off", "useSerial", "useWDT", "useOTA", "useResetKeeper",
//                "useFailNTP", "useDebugLog", "deviceTopic", "groupTopic", "prefixTopic", "inputUpPin",
//                "inputDownPin", "outputUpPin", "outputDownPin", "inputUpExtPin", "inputDownExtPin",
//                "auto_relay_off_timeout"};

parameters def_par{false, false, false, true, true, false, true, "devTopic", "noGroup", "myHome", 2, 1, 14, 12, 0, 2, 60};

parameters final_par;

// A couple of functions to extract data from an array or struct:
#define countof(a) (sizeof(a)/sizeof(a[0]))                             // ret # of array elements (not bytes)
#define offsetof(struc, member) ((int)(&(((struc*)(0))->member)))   // ret byte-offset from start of struct to the given member

// Enumerate possible parameter types
typedef enum {
   t_bool,
   t_char,
   t_int
} parType;

// Descriptor table - contains name, type, and offset of each parameter
// Could go in flash to save a bunch of RAM
struct descriptor {
   const char *name;
   parType pType;
   uint8_t offset;
} Descriptors[] = {
   { "ext_inputs", t_bool, offsetof(parameters, ext_inputs) },
   { "auto_relay_off", t_bool, offsetof(parameters, auto_relay_off) },
   // ...
   { "inputUpPin", t_int, offsetof(parameters, inputUpPin) },
   // ...
   { "auto_relay_off_timeout", t_int, offsetof(parameters, auto_relay_off_timeout) }
};

void setup() {
    Serial.begin(115200);
    Serial.println("parameter        type          offset\n");
    // List the parameters' names, types, and offsets within 'struct parameters'
    for( uint8_t i = 0;  i < countof(Descriptors);  ++i ){
        Serial.print(Descriptors[i].name);    Serial.print(", ");
        Serial.print(Descriptors[i].pType);   Serial.print(", ");
        Serial.println(Descriptors[i].offset);
    }
}

void loop(){
    ;
}


Computer to Arduino to hardware, controlling on / off state of hardware via user input on computer

This seems way too complex for your purpose:

you really do not need to do anything to stay in the same state
if you want to switch the valve ON, no need to check whether it's OFF:
there is no harm in switching ON a valve that is already ON.

Here is a simplified version of the program:

void setup()
{
    Serial.begin(9600);
    Serial.println("Type '0' to turn OFF, '1' to turn ON");
}

void loop()
{
    int command = Serial.read();
    if (command == '0') digitalWrite(53, LOW);
    if (command == '1') digitalWrite(53, HIGH);
}

Notice that Serial.read() returns -1 if there is nothing in the input
buffer, and since -1 is neither '0' nor '1', this will not change the
output.

If you want to use more elaborate commands (not single characters), you
may want to take a look at this simple command-line
interpreter. It is intended to be easy to adapt to
different purposes.


AVR - How to know that there is collision between stack and heap or the memory has filled?

I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

The first thing that happens is that malloc() will return NULL saying that memory could not be allocated. The AVR heap implementation has a few safety measures. One is to check that there is a minimum margin (__malloc_margin) between end of the heap and the top of the stack. This can be adjusted by the application.

Typically the minimum margin should be able to hold the largest stack usage (typically deepest function call tree with the largest local variables usage) plus largest ISR stack usage.

If the stack runs into the heap the memory block/s at the end of the heap is/are corrupted. What happens depends on the type of data structure.

Not checking NULL return from malloc() gives some interesting errors on the AVR as the processors registers are memory mapped. NULL points to R0.

A good rule of thumb when using malloc() in small scale embedded systems is 1) avoid it, 2) allocate memory with malloc() during the setup(). All other dynamic memory need be allocated temporary on stack and only for the processing.


Fail to return int value from a function

the parameters of a function call are copied into parameters in the function. if the pointer is copied it still points to a memory where you write the data. if int is copied then changing the value changes the copy, not the variable used as parameter. reference is kind of pointer

how to make an in-out parameter by passing a parameter by reference

void setup() {

  Serial.begin(115200);
  int x = 3;
  fnc(x);
  Serial.println(x);
}

void loop() {

}

void fnc(int &x) {
  x = 5;
}

prints 5

example with a complex type

#include <IPAddress.h>

void setup() {

  Serial.begin(115200);
  IPAddress ip(192, 168, 1, 5);
  fnc(ip);
  Serial.println(ip);
}

void loop() {

}

void fnc(IPAddress& ip) {
  ip = IPAddress(192, 168, 1, 3);
}

with &ip it prints 192.168.1.3. without & it prints 192.168.1.5


As far as I know, the Serial.print (or println) does rounding up and down. All you have to do is take a float variable and do Serial.print( value, 1);

Without extra parameter, the default is choosen, which is 2 decimal digits: Serial.print( value, 2);

Why do you want to shorten the bytes over the Serial ? You can just as well send two decimal digits and process the value in Python.


8Ω speaker, what resistor values to use?

The speaker rating of 8 Ω is AC resistance, speaker impedance. Impedance (AC-Resistance) changes based on the frequency of the signal fed into it.

If you are worried about hurting the speaker and need to calculate power driving that particular "load", look at the speaker Wattage rating.
Say it is 1 W for example, and you are providing 5 V d.c., the amperage required will be: 0.2 A.

V * A = W
0.2 * 5 = 1

So the DC resistance is actually:

V = I * R (0.2 / 5 = 0.04 Ω).

Give it a higher amplitude... say 5.7 V to account for a transistor no resistor, and you get about 0.175 A. and a change in DC resistance again to 0.0301 Ω.

If the power supply is AC, the impedance needs to be matched to the speaker impedance to get best energy efficiency, otherwise the amplifier can be damaged.

For that circuit I suggest you place a variable resistor where the resistor is in your circuit to allow for a volume change. Also a flyback diode maybe a good idea, that will protect the speaker but take down voltage 0.7 V d.c. keep in mind you have that transistor there adding 0.7 V d.c.! so it evens things out too using that diode.

That diode placed on the high (+) side of the circuit, before the speaker and after the variable resistor.


How to mimic soft-power button in inexpensive toys & flashlights?

I have a lengthy write-up about saving power at Power saving techniques for microprocessors.

One of the sample sketches on that page (Sketch J) does what you ask:

#include <avr/sleep.h>

const byte LED = 9;

void wake ()
{
  // cancel sleep as a precaution
  sleep_disable();
  // precaution while we are doing other things
  detachInterrupt (0);
}  // end of wake

void setup ()
  {
  digitalWrite (2, HIGH);  // enable pull-up
  }  // end of setup

void loop ()
{

  pinMode (LED, OUTPUT);
  digitalWrite (LED, HIGH);
  delay (50);
  digitalWrite (LED, LOW);
  delay (50);
  pinMode (LED, INPUT);

  // disable ADC
  ADCSRA = 0;

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // Do not interrupt before we go to sleep, or the
  // ISR will detach interrupts and we won't wake.
  noInterrupts ();

  // will be called when pin D2 goes low
  attachInterrupt (0, wake, FALLING);

  // turn off brown-out enable in software
  // BODS must be set to one and BODSE must be set to zero within four clock cycles
  MCUCR = bit (BODS) | bit (BODSE);
  // The BODS bit is automatically cleared after three clock cycles
  MCUCR = bit (BODS);

  // We are guaranteed that the sleep_cpu call will be done
  // as the processor executes the next instruction after
  // interrupts are turned on.
  interrupts ();  // one cycle
  sleep_cpu ();   // one cycle

  } // end of loop

According to when I tested that, it used 0.116 µA when asleep (116 nA). That is well below the rate at which batteries self-discharge.

Basically that code does what you described. It sleeps, when pin D2 goes low it wakes and flashes an LED.

I should point out though that any "development board" Arduino with a voltage regulator, USB interface, and power LED on it will consume considerably more power because of the current drain they consume.

For low-power applications you need the bare chip (with appropriate supporting circuitry, like decoupling capacitors).


Arduino Yun receives UDP packets but prints them with gibberish

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


Using a N-type transistor as a high-side switch is inefficient unless you have some way of driving the gate above the positive rail. The most you can reasonably expect at the source is the gate voltage minus the gate threshold voltage, VGS(th). The typical threshold voltage of the 2N7000 as given in the datasheet is 2.1V, which means that it is a bit remarkable that you are able to get a voltage as high as you have (5V - 2.1V = 2.9V).

The way to fix this is to switch to a P-type transistor (and flip it around) since its threshold voltage is negative.


If I understand correctly, you signal has a period of 8 FDCS pulses:
4 with CI high and 4 with CI low. Since the rising and falling edges of
CI do not happen at the same place relative to the FDCS pulses, you
should handle these separately.
I suggest something like the following. Note that, as I do not know what
signal(s) your setup inverted, I just try to reproduce what you show on
the scope, with non inversion:
uint8_t portState = 0;
for (int totalCnt = 0; totalCnt < 16000; totalCnt++)
{
    // On pulse 0, CI rises with FDCS.
    portState |= _BV(FDCSPIN);
    if (totalCnt % 8 == 0)
        portState |= _BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(FDCSoffset);  // pulse width

    // On pulse 4, CI falls with FDCS.
    portState &= ~_BV(FDCSPIN);
    if (totalCnt % 8 == 4)
        portState &= ~_BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(PWus);  // inter-pulse delay
}


Change one specific byte of an IP address

You can do it all with the IPAddress class.

For instance: create an IP address from a string:

IPAddress myAddr(myString);

Create a new IP address with one byte changed:

IPAddress myNewAddr(myAddr[0], myAddr[1], myAddr[2] + 1, myAddr[3]);


@Paul, thanks for your suggestion.

I want to go forward with TCP/IP.
I have now setup a ESP8266 Modul.
The ESP Modul is setup as a Server.
The Server on the ESP Modul is up and running.
I'm also able to connect to the ESP-server with "Hercules", a Terminal Tool.

All the example I found were establishing communicating with Browser and HTML.
I have also checked this, but this is not what i want.

This is the current code communicationg with the web page to toggle a LED.

    void loop() {
    if (esp8266.available()) // check if the esp is sending a message
    {
    debug("available and waiting for command");
    if (esp8266.find("+IPD,"))
    {
      debug("Incomming Request");
      int connectionId = esp8266.parseInt();

      if (esp8266.findUntil("LED","\n")) digitalWrite(LED, !digitalRead(LED));

      String webpage = "
Hello World!
Open [IP]/LED to Toggle LED on D9";

      if (sendCom("AT+CIPSEND=" + String(connectionId) + "," +          String(webpage.length()), ">"))
      {
        sendCom(webpage,"SEND OK");
        sendCom("AT+CIPCLOSE=" + String(connectionId),"OK");
        debug("Send and Close");
      }
    }
  }
}

But the PLC has no web server. So now I would like to do the same thing as client through a terminal.

How can i check what really had beed sent and what the ESP really received?
At this point sending the /LED command has no effect.

Terminal & ESP

Thank you in advance for your advise


Password protection of the REST API is done with Basic Authentication. This, coupled with HTTPS, makes API calls more secure. Since the SSL certificate is self-generated, you'll need to run curl with -k parameter.

As Annonomus Penguin suggested, before going into securing the Yuns, you should secure the network they are using (e.g.: home WiFi should use a strong password).


This is a “feature” introduced in the revision 3 of the Uno board. Up to
Rev 2, the “L” LED was connected to pin 13, through a 1 kΩ
resistor. On Rev 3, the same LED+resistor combination is driven by pin
13 through an op-amp. Thus, when pin 13 is in high impedance mode (i.e.
INPUT mode, the default mode when the program starts), the input of
the op-amp is floating. The voltage at this input (and thus at the
output) is not controlled and depends only on the parasitic conductances
and on leakage currents.

If you want to turn the LED off, you not only need to write LOW to it,
you also (and most importantly) should set the pin to OUTPUT.


Voltmeter using Arduino mega 2560 giving unexpected result after some time

With that circuit you can expect a roughly 10% variance in the output voltage depending on the exact moment at which you sample the voltage.

The basic circuit you have, and the waveforms generated, are like this:

That green waveform is the one you are reading. As you can see, exactly where you sample defines what the result will be.

Since you're trying to average over an undefined period (20,000 samples of how long per sample exactly?) you're not going to get a particularly well defined output.

You should change your sampling strategy to perform multiple samples over a well defined period to find the maximum value. That is the value you should then use in your calculations.

Ideally, you want to repeatedly sample for at least one entire waveform cycle. At 50Hz that's a period of 20ms (17ms for 60Hz).

For example:

uint16_t maxval = 0;
uint32_t ts = millis();
while (millis() - ts < 20) {
    uint16_t val = analogRead(0);
    if (val > maxval) {
       maxval = val;
    }
}

// Use "maxval" in your calculations.

With this strategy, because you're looking for the peak value, you don't care about the impact that the capacitor has on the circuit (except that it will remain artificially high for a period if the voltage drops), so you could actually simplify the circuit and remove that capacitor completely.


Arduino clone CH340G (ATmega328P), MIDI over USB

V-USB bit bangs some GPIO pins so that they speak the low-speed USB protocol.
This does not use the 'normal' USB connection through the CH340; you would have to solder a separate USB cable to those GPIO pins.

Programming would be no problem; the V-USB code is just normal code that runs on the MCU. (Programming through ISP pins would be required on hardware where USB communication and programming is handled with a second AVR MCU; in that case, the USB/MIDI code would run on that second MCU.)

Low-speed USB is not supposed to be used for MIDI, and as a software emulation, V-USB does not work very well, or efficiently.
If you want to create a USB device, you should use an MCU that actually supports USB in hardware, such as the ATmega32U4 or AT90USB646 used on some Teensies.


Arduino, lcd 16x2 and UTP cable shows gibberish text?

Is the cable shielded?
Have to performed continuity test on all leads of the cable to ensure there no break internally that could be causing an issue, or a short?

What is the impedance of your total length of cable?

These sorts of checks will help you further narrow down the issue. If you are certain your wiring is correct, then the most probable issue is either a hardware failure (continuity test)
a hardware limitation (Too much resistance for accurate data travel)
Improper Hardware, unshielded wires can be subject to crosstalk, or signal corruption/distortion due to external signals interfering.


Reading input from digital pins 36, 37, 38 in Arduino Mega 2560 is giving a problem

I expect the problem is in the circuit. To be sure, put a serial print statement directly after reading the inputs, to be sure the input values are read correctly.

See the remark of using INPUT or INPUT_PULLUP from Jot below.

The following is just a more compact way of writing your loop (and does not fix your problem):

void process(int pin, char* text)
{
    if (digitalRead(pin) == HIGH) // Use HIGH instead of 1
    {
       lcd.write(text);
       digitalWrite(35, HIGH);
       delay(2000);
    }
}

void loop()
{
    lcd.begin(16,2);
    // set cursor position to start of first line on the LCD
    lcd.setCursor(0,0);

    process(36, "vswr");
    process(37, "thermal");
    process(38, "overdrive");
}

Also, I would add the delay at the end (after the three calls of process).
And instead of hard coded values 36, 37 and 38 use 3 constants/defines.


You must use a resistor. See The care and feeding of LEDs

  How Do I fix it?

Use a current-limiting resistor.


USB Host Shield plus 2 identical joysticks

Not quite the question that was asked but part of the problem.

This is a simple introduction to pointers.

int variable = 42;                              // Create a variable
int* pointer = &variable;                       // Create a pointer to the variable (by getting its address)
*pointer = 99;                                  // Set the address to a new value
printf ("variable has the value %d", variable); // Print 99.

&x get the address of x

*y dereferences the pointer y, which means it 'turns it back to a variable' (this is simplistic view which isn't really true, but will do for now).
So you could, if you wanted (which you wouldn't) do this *&z which would be the same as doing z.

Basically think of & and * as a pair of complimentary operators like - and + or * and /.  (They aren't operators, but to start with it might help).

The next problem is when you do this

SomeFunction(&variable);

All function parameters in C/C++ are passed by value by default.  This means the function gets a copy of them not the actual value.  So if you had:

void FunctionOne (int val)
{
    val = 99;
}
int val = 4;
FunctionOne(val);
printf("val = %d", val);   // You will see 4 printed.

If you pass by reference then you will see 99 printed, to pass by reference you can do it one of two ways.

void FunctionTwo (int& valByRef);
void FunctionThree (int* valPointer);

FunctionTwo only works with C++ (It will work with an Arduino).

FunctionThree might cause a segmentation error if NULL is passed in and the function writes to it.

If it helps in my opinion pointers was one of the hardest concepts to grasp in classic C/C++ so don't worry if you don't understand it just have a play with it and see what you can do.

Calling Methods

object.method() - Call the function method on the instance called
object which is of type X.
object->method() - Call the function method on the instance called
object which is a pointer of type X.
object::method() - call the function method
which is a static member of class object (static means it doesn't
change any data within an instance of a class)
*object->method() - Avoid this like the plague.  It either means *(object->method()) or (*object)->method() to know you would need to look at the type of object and the return type of the function.  Its easier just to bracket it to remove ambiguity.

As for *object.&method() I've never come across that one, but that doesn't mean it doesn't exist. :)


Is there some kind of timer function that returns the amount of time passed?

Just adding a few notes to the perfectly valid answers you already got:

On your typical AVR-based Arduino, micros() has a resolution of
4 µs and millis() is updated every 1024 µs. This last point
implies that millis() increments most times by 1 ms, but
occasionally by 2 ms. Keep this in mind if time resolution is an
issue.

Both millis() and micros() return 32-bit unsigned numbers. This
implies that millis() overflows (it rolls-over to zero) roughly every
49.7 days and micros() every 71.6 min. This limits the
maximum interval length you can measure with each of those functions. It
does not limit the maximum run time of your program, since
subtracting two timestamps does work fine across a rollover
event.


A pointer to a member function is not allowed in C++. GCC can allow it, but moans at you because it's non-standard.

In C++ the normal way of dealing with the kind of thing you want is through class inheritance.

Typically you would create your base Fsm class that implements the basic functionality of your state machine control, then overlay over the top of that (create a new class that inherits the Fsm class) another class that implements your specific machine functionality.  You can declare functions in your base Fsm class that are pure virtual - that is, they exist, but have no body. It's then the job of the child class to actually implement that functionality.  The parent Fsm class then knows about those functions and can call them.

So you would have something like:

class Fsm {
    public:
        void dispatch();
    protected:
        virtual void initial() = 0;
};

void Fsm::dispatch() {
    initial() ;
}

class Machine : public Fsm {
    protected:
        void initial() {
             Serial.println("Here");
        }
};

Machine mach;

mach.dispatch(); // --> "Here"

Fsm knows about initial(), but the function hasn't been further defined.  Machine implements initial().  You then create an instance of Machine which contains everything needed.  Calling dispatch() runs the function in the Fsm parent class which then calls initial() in the child Machine class.


Nodemcu 1.0 and boot mode (1,6) after soft reset

The esp8266 has a bug (documented). After Serial upload the program is started without reset and then at soft reset the state of "start bootloader" is still active.


You can't - not directly. Instead you do a job at a higher frequency which just counts. When it has counted enough you do your other job.

For instance, you might trigger your interrupt once a second. That interrupt just adds 1 to a count and returns. Unless that count just hit 8, when you reset the count to 0 and run your 8 second routine.


How to power Nodemcu using 12 volt AC to DC adapter?

You connect the + side of the adapter to VIN pin and the - side to GND.
You have to check the maximum voltage when using the VIN pin. Probably it means you 'waste' some power (but it's from a wall wart, so it should be ok). See the remark of Flyingfenix below for heating consequences.
See this link: Power Related ESP-12E Development Board Pins, fragment 'Using a Wall Wart':

The current (1.5A) should be more than enough; the adapter's current should be higher than what is needed by the NodeMCU + circuit. So this is ok.


it's working with u8glib.  but i am using  4-wire SPI.

constructor for U8GLIB

U8GLIB_SSD1306_128X64 u8g(13, 11, 10, 9,8);

Pin configuration was

Arduino -   Oled Display
13 -    CLK
11 -    DIN (SI)
10 -    CS
9 - D/C (A0)
8 - RES

the reset pin is required. i used 3.3v  arduino pin for vcc .


nRF24L01+ RF24 library - can send but can't receive

The pins could be wrong for ATMega328.

It should be.

NRF24L01 - Arduino UNO
GND - GND
VCC - 3.3V
CE - 7
CSN - 8
SCK - 13
MOSI - 11
MISO - 12

or B. You need to connect a 500uF electrolytic capacitor to your NRF24L01+ VCC and GND pins directly. To reduce noise related issues. With clone arduinos/cheap regulators/clone NRFs then noise might start creating issues especially with receiving.


Arduino Mega - I2C pins (20/21) unreliable

The I2C pins on the Arduino Mega 2560 board are 100% reliable, but you have to use them correctly.

The Wire library could halt when something is wrong with the hardware I2C bus. In that case the sketch stops. The Wire library should have timeouts programmed in case something is wrong with the hardware, but sadly it doesn't have timeouts.

Hardware
The hardware I2C bus on the Arduino Mega 2560 board is a 5V I2C bus, because the Arduino Mega 2560 has 10k pullup resistors to 5V for SDA and SCL.
The wires for I2C can only be short. Long wires will not work.
The worst thing is when SDA and SCL are in a flat ribbon cable next to each other. The crosstalk between SDA and SCL will make the I2C very unreliable.
Because it is a 5V I2C bus, you may not connect 3.3V sensors to that 5V I2C bus. In that case you need a level converter.
The total value of all pullup resistors in parallel should not be too high (more sensitive for electrical noise, longer wires are not possible) and not be too low. The I2C specificiation is maximum 3 mA pulling of down current to get the signal low.
Everything that is connected to the I2C bus must have proper power supply. If one sensor has a power supply that fails, then that sensor will probably pull down the SCL and SDA signals.
A test with a breadboard might fail, due to bad contacts of the breadboard.

Software
The Arduino Wire library is often used in a wrong way.
If one of the sensors is an Arduino board as a I2C slave, then the code for the slave must be done right, because there are many ways to do it wrong.
You could check the return value of every Wire.endTransmissions for an error, and check every return value of Wire.requestFrom for the amount of data that is received.

If you tell us everything about the sensors, the wires (with photos), the logic level converters, the sketch, and so on, then we can tell you what the problem is.