How can i connect the Mics-5132 to Arduino Uno (Carbon Monoxide Sensor)

That is a very skimpy data sheet for the MiCS-5132 .  (Shame on manufacturer for not including isolation information between heater and resistor output).

Connect 3.2 volts (3.3 volts is ok) to pins 1 and 3 (heater). Keep in mind the heater will draw about 32 mA.

Pins 2 and 4 are the output.  The output is a resistor, whose value changes with the degree of detected gases. And the resistance is about 160 k ohms.

Wire a resistor (call it R1) from VCC (positive power) to your input. Start out with R1 = 150k  (anything from 120K to 180K). .

Wire the sensor (pin2) to your input (use an input that can do A/D conversion).  Wire the other side of the sensor (pin 4) to your board ground.

This makes a resistor voltage divider to your input pin. Your input pin should be an A/D converter.  The A/D converter input should return a value dependent upon the sensor resistance.

Experiment with different values for R1, to get the input range that you desire.


compare char receive from Slave writer to Master reader with I2C

Improve you indentation.
If you want to compare two strings use strcmp function for that.
Your master part has some brackets left in your void loop() function, correct them.
In I2C you are receiving one byte at time. You should receive data till the last byte in received.
You should have some identification in your message, which is you are sending from slave to master indicating that this is last character. It helps you come out of Data reception loop in Master side.


I have the feeling you need only one state which can have 4 values: L1, L2, R1 or R2.

For this, use an enum:

enum EState { L1, L2, R1, R2 };

Now create one state variable of that type and give it an initial value.

EState state = L1;

Some other problems I see at first sight:

case L1:
  if (state == L1){
  if (button1State == HIGH){
      state == L2;
  }
}
break;

In this statement, when there is case L1, it means the code following ( until the break) is only handled when the state (because of switch(state) is L1, so you can remove the check if (state == L1). What is left is:

case L1:
  if (button1State == HIGH)
  {
    state == L2;
  }
  break;

Than you use state == L2 to set a new state. However, the == only compares two values, if you want to assign it, you have to use a single =, thus the code should be:

case L1:
  if (button1State == HIGH)
  {
    state = L2;
  }
  break;

Of course you have to do this also for the other case statements.

Tip: align your code (make the { and } aligned under each other; this will make your code readability much better.


Arduino Leonardo Pro Mini will not begin sketch when connected to BIOS not an OS

Because the computer doesn't have a full OS at POST time any USB keyboards attached to the system have to operate in a special "Boot Keyboard" mode.

  Keyboards that implement the USB Boot Keyboard profile specified in the USB Device Class Definition for Human Interface Devices (HID) v1.11 and are explicitly configured to use the boot protocol will interrupt the CPU every time the keyboard is polled even if there is no change in state unless the USB controller overrides this behavior, and are limited to 6-key rollover (6KRO). This profile is intended to allow the BIOS to handle a USB keyboard in the absence of a USB-aware operating system. The recommended profile for keyboards that are not in boot mode in this specification limits keyboards to 6KRO and causes them to respond to an interrupt with a status report at least every half second even if there is no state change in the keyboard unless the USB controller overrides this behavior in order to implement typematic (the function that causes keys to repeat when they are held long enough). However, keyboards in non-boot mode are free to implement an alternative HID profile.

  -- Wikipedia

Since it was not expected that anyone would be using the Leonardo to operate in the BIOS that functionality has never been implemented. The choice was to implement the entire system, which would have left less room for your sketch, or to just implement the parts that the majority of people would find useful (that is keyboard, mouse, joystick, etc) and leave out the extra stuff, leaving as much room for sketches as possible.

They chose the latter, since as I am sure you are well aware: "The needs of the many outweigh the needs of the one".

For your rather specific case it may be easiest to butcher an old USB keyboard and work out which pair of inputs to the matrix, when connected together, perform the function you require and design some small interface circuit to allow the Arduino to trigger that function.


Does the arduino board have to be always physically connected to the electronic device you are running?

If the "basic electronic board" is programmable, then yes, you can upload a program to it.

In general, though, "some LEDs" and similar devices are not programmable, and without something to drive them (i.e., the Arduino) they won't do anything at all.  The Arduino is what has the program and it tells the "basic electronic board", moment by moment, what it should be doing.  It is the brain of the operation.  Remove the brain from someone and you'll find their body no longer functions.


Problem Uploading to the Arduino Nano board

A common solution is to actually switch the board type to the Arduino Uno. It is a known problem but I have yet to see any other viable fix.


Can the Sparkfun AVR pocket programmer bootload/program a 3.3 V ATmega328p

With that combination of programmer and Arduino you have two possible options:

Cut JP1 on the programmer and power the programmer from the Arduino. With this you will have to make sure that the Arduino is connected and powered up before you connect the programmer to USB.
Cut SJ1 on the Arduino and allow it to be powered by the programmer at 5V. The Arduino itself isn't required to be powered at 3.3V, that's simply what the on-board regulator provides, so we cut SJ1 in order to isolate the regulator from the MCU. Note that any devices connected to the Arduino will need to support 5V operation in order to this to be safe.

It is not safe to put 5V at the output of the regulator, so you must make sure that does not happen.


PWM output while using I2C with the ATTiny library

This is normal.

Timer0 is used as the clock source for the USI. It's the only internal clock source that can be used. The only other option is to use "software polled" mode where it's up to the sketch (or support library) to manually create the clock signal (less than desirable) by setting a bit in a register at the right time.

So you can only use Timer1 for your own (PWM) purposes while using the USI.


What are exactly XTAL1 and XTAL2 pins in Arduino Uno/Nano?

The Crystal in Red is for the Atmega16U2 that manages the USB interface with its high speed connection to the PC (12 MHz for USB2 I think).

The Resonator in Yellow is for the Atmega328P.  It is less precise than the crystal oscillator.

PB6 and PB7 are dedicated to the external crystal or resonator by the fuse settings used for Arduino.

You can read more about the XTAL1, XTAL2 pins and the fuses from the device datasheet

https://www.microchip.com/wwwproducts/en/ATMEGA328P

You can connect a crystal to the pins, but you will also need 22pF caps to connect from the pins to Gnd. And remove the resonator.  Current Uno layout does not really support making those connections.


Can i supply the AREF pin with an Analog pin from the same board?

With an input voltage between 0 and 2.2 V, you can use a 2:1 voltage divider to cut the voltage in half.  In your code, use analogReference(INTERNAL) to set the analog reference voltage to 1.1 V.  The 1.1 V internal reference voltage is created by a bandgap circuit so is reasonably accurate.

To make the voltage divider, put two equal resistors (eg 10KΩ each) in series; connect one end of the series to your input voltage, the other end to ground, and the mid-point to an analog input pin.


compilation terminated. exit status 1 error compiling for board arduino/genuino uno

Two errors I see is a typo and missing semicolons.

const int ledPin=13
int piesoPin=9

Should be

const int ledPin=13;
int piezoPin=9;

Also I see a unnecessary { and } but this cannot cause a compilation error.

Check the delays, when the temperature is higher than 26 degrees you have more delay than when not, maybe this is intended, maybe not.

However, you probably typed over the code, so maybe there are more errors, please add the exact error text and line in your question.


Arduino controlled light dimmer software

-10uS because of the 10uS delay at the end of the loop, and /128 because he has decided there will be 128 possible dimming levels.


Which platform is better to debug Arduino memory problems? Linux or Windows?

The operating system is irrelevant. If you want to debug the target you need a debugger and a debugging environment. That means a proper hardware debugger interface, not an Arduino's USB serial port, and a proper IDE like Atmel Studio not the Arduino IDE.  All are available for both Linux and Windows.


You need to specify the font, style and size.  I think you want

editor.font=Ubuntu Mono,plain,12

I don't know the exact name you should use for the font but you must have all three fields separated by commas.

The second field can be "plain", "bold" or "italic".

The third field is the font size, I'm not sure the units.


It's really easy to take an ATmega328 chip and wire it up on it's own.  There are even instructions on the Arduino site on how to do it.  Take a look at http://www.arduino.cc/en/Main/Standalone .

You could even pull the 328 out of the Uno, add the crystal and a few caps and then program it with the Uno board.  I've done this a few times myself and it worked just fine for my needs.


Multiple RGB led strips with Uno - options?

I know what you mean - LED strips with all the same colour at the same time. I've used these and I assume you can wire up the MOSFETs ok. If you don't need individually-addressable LEDs they can still produce some effects.

To control 30 PWM lines, at first I thought using the Mega would solve it, but as someone else reminded us, only 15 are full (hardware) PWM and some would have to be software PWM. This may be good enough, I don't know. More expensively, you could use two MEGAs with one acting as a slave to get 30 full PWM pins.

Another idea would be to use a PCA9685 chip module. I got a couple of these on ebay some while ago (dirt cheap, under £2/$2 ) and each board provides 16 PWM outputs, all controlled from I2C input. They aren't hard to use and have library code for Arduino. Two of these and an UNO would do it or one and a MEGA.


Serial Communication between ESP8266 and Arduino Uno

Since you are  Arduino Uno, it has only one Serial. This Serial can be used to transmit data in USART mode to another Serial Device as well as see any Debug data in the Serial terminal.

However, both the functionality can not be used simultaneously. The Tx Rx pair of Arduino can be connected to one pair of other device i.e. either to the computer via the cable or to the Tx Rx of ESP8266.

But if you really need to plug in the Uno to the computer and send data to ESP8266 simultaneously, then you have to use SoftwareSerial library to convert any digital pin to Tx Rx pin, and connect them to ESP8266 for transmitting data.


Can increasing the size of the software RX buffer cause problem in Arduino Uno

The buffer is in the UNO's limited (2K) RAM; you'd be using 1/4 of it for the input buffer. If your app is small enough and simple enough (limited call depth, specifcally), there may still be enough RAM for your app to run successfully. If you have lots of globals (remember to include libraries when you're considering RAM use), allocate much memory from the heap (with new or malloc()) or have a complex call structure such that funcA() calls funcB() calls funcC() calls ... (etc) so that many functions' stack-frames remain allocated at once - at any point in your program - your program could suffer a stack-collision: the call-stack descends low enough that it can overwrite, or get over-written by, your heap or global data.

Why do you want so large an input buffer? Will data be coming in a high rate or in large bursts, while processing of the data will be infrequent or occur at irregular times? Given the limited RAM in the UNO, running complex programs on one can require something of a balancing act in how you use resources.

Update:

  i was performing some AT commands with software serial and buffer limitation generated junk value

Other reasons why SoftwareSerial might return bad data are:

Using too high a baud rate (9600 baud seems to be about the max);
Code that turns the interrupts off too often or for too long;
Other devices creating too many interupts (perhaps a built-in timer running at a high rate).

The replies to most devices' AT commands that I know of are short enough to not require a huge receive buffer. Asking for list of WiFi SSIDs from an ESP8266 could generate a large reply but most responses should not overflow a more modest buffer.


I see 2 problems with your code:

Returning a value from a function: If you want to return a value from a function, you will have to make sure, that in any case the return x statement is executed inside the function in the temperature() function you currently have this if statement:

if(currenttime - checkTempinterval >= checkTemp){

Inside of it is the only return statement. That means, if the function is called before the next measurement time, the function will not return anything. Normally the compiler gives you at least a warning about that (maybe you have to turn the warnings on in the settings of the Arduino IDE).

Here you also have to think about, what you want to return, if no measurement was actually executed. Do you want to return an error value (for example -300; the error value should not be found inside valid data)? Then do so after the if statement. Or do you want it to simply return the last measured value? Then declare a variable (either at global scope, meaning outside of any function, or at local scope, meaning inside the function, but static, which means that the value will be retained between the functions executions). Save the measured temperatures to this variable and return it after the if statement.

If you do this, also consider what that means for the rest of your code. For example, if you return an error value, currently it will also be displayed by your code.
Doing the millis() code correctly: What you are doing wrong here, it that you update the wrong variable inside the if statement. Currently you write the value of checkTempinterval (which is the time of the last measurement) to the variable currenttime. The variable currenttime was declared locally (meaning inside the function) by using

unsigned long currenttime = millis();

Local variables are only present during the execution of the function, that they are declared in. When the microcontroller has executed the return statement, it will throw all local variables away, making the RAM free for other variables. That means currently you are saving a value inside a variable, that get's thrown away directly after it.

What you actually meant to do, was to do it vice versa:

checkTempinterval = currenttime;

checkTempinterval is a global variable. It will stay in RAM during the whole program execution. Since it holds the last measurement time, you write the currenttime to it, when you measure.

Very important: Currently checkTempinterval is defined as const int meaning constant integer. This variable must not be constant, since we want to change the value (update the time of the last measurement). Also you should not use int here, because it's value range goes only up to 32767, which is 32 seconds when used with millis(). After that, it will overflow to negative values. Better use the type of millis() return value: unsigned long. It has 4 byte (instead of ints 2 byte) and will only overflow after 49 days. If you only use this variable type for things with millis(), even this overflow will not be a problem.


Is it possible to program a few Arduinos at the same time?

Arduino Pro Mini is programmed through serial, using a bootloader. It uses STK500 protocol, which is described by Atmel.

In theory, it can be possible to program multiple boards if only one TX Arduino pin is connected to USB-Serial converter, and all RX are in parralel, but this is an unreliable method. Only the board with TX pin connected can send its status back to programmer.

Arduino Mini also requires a physical reset before uploading. Make sure that all Reset pins are connected together when reset button is pressed.


How to use Serial Monitor without Arduino board?

Yes that is possible. Connect to the RX/TX pins on the breadboard chip. Remember these are 5V. You will need an Serial-USB or RS232 adapter to connect your development machine. Please see this blog post for some inspiration.

Cheers!


Reconstruct uint32_t from char array to RTC.set

There are several possible issues here:

can you send the number, as a string, from the PC to the ATtiny?
can you convert the string to an actual number?
can you give this number to the RTC?

The phrasing of your question sounds like your issue is with the
conversion. However that is easily handled with atol(). Here is a test
program I tried on my Uno:

void setup() {
    char time_string[] = "1532341020";
    uint32_t time_number = atol(time_string);

    Serial.begin(9600);
    Serial.print("string: \"");
    Serial.print(time_string);
    Serial.print("\", number = ");
    Serial.println(time_number);
}

The output is:

string: "1532341020", number = 1532341020


library mixing log4Esp & Syslog for esp8266

I did a rather dirty (but efficient for my purpose) job : While creating a new logger I declared and attached to it a log4esp formatter in which I sent ... syslog messages

dirty dirty dirty

my config constants are : SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME

My logger.h:

#ifndef Logging_H
#define Logging_H
#include <Log4Esp.h>
namespace Logging
{
void setup() ;
log4Esp::Logger Logger(const char *name);
}
#endif

my logger.cpp:

#include <Log4Esp.h>
#include <Syslog.h>
#include <WiFiUdp.h>
#include <ESP8266WiFi.h>
#include "Logger.h"
#include "config.h"
namespace Logging
{
// A UDP instance to let us send and receive packets over UDP
WiFiUDP udpClient;
// Create a new syslog instance with LOG_KERN facility
Syslog syslog(udpClient, SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME, LOG_KERN);
//new logger
log4Esp::Logger Logger(const char *name)
{
  //new instance
  log4Esp::Logger logger = log4Esp::Logger(name);
  //minimal level
  logger.addLevelToAll(log4Esp::Appender::LOG_LEVEL);
  // formatting for serial logging
  logger.addFormatterToAll([name](Print & output, log4Esp::Appender::Level level, const char *msg, va_list * args) {
    ////////////////////////////////////////
    // serial log format
    // output uptime of this program in milliseconds
    output.printf("%10d", millis());
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output free heap space
    output.printf("(%d)", ESP.getFreeHeap());
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output logger name
    output.printf("%-4s", name);
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output log level
    output.print(log4Esp::Appender::toString(level, true));
    if (level <= log4Esp::Appender::Level::ERROR) {
      output.print("***");
    } else {
      output.print("   ");
    }
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // determine buffer length for formatted data
    size_t length = vsnprintf(NULL, 0, msg, *args) + 1;
    char buffer[length];
    // output formatted data
    vsnprintf(buffer, length, msg, *args);
    output.print(buffer);
    ////////////////////////////////////////
    // Stop here if wifi is down
    if (WiFi.status() != WL_CONNECTED)
      return;
    ////////////////////////////////////////
    // format for syslog
    uint16_t slevel;
    switch (level) {
      case log4Esp::Appender::Level::FATAL    :
        slevel = LOG_CRIT;
        break;
      case log4Esp::Appender::Level::ERROR    :
        slevel = LOG_ERR;
        break;
      case log4Esp::Appender::Level::WARNING  :
        slevel = LOG_WARNING;
        break;
      case log4Esp::Appender::Level::VERBOSE  :
        slevel = LOG_INFO;
        break;
      case log4Esp::Appender::Level::TRACE    :
      default:
        slevel = LOG_DEBUG;
        break;
    }
    syslog.logf(slevel, "%10d|(%d)|%-4s|%s", millis(), ESP.getFreeHeap(), name, buffer);
  });
  return logger;
}
void setup() {

}
}


The answer for this actually goes to Juraj.  It was the fact that I was missing a delay.  In hindsight it makes sense, as even though I am competing tasks in order, the system is shutting down, before the actual message is sent.  I added a delay(1000) between the "sendMQTTMessage()" and "ESP.deepsleep()" and it worked.


Can two LEDs attached to different pins share their resistor?

Your circuit is safe from the electronic viewpoint, so long as the LEDs used can withstand a back-emf of 4v or so.

If only one LED is on at a time, all will be sweet. But if two or more are on, the brightness will drop and the brightness between LEDS will probably be inconsistent. The forward voltage drop of individual LEDS tend to vary a little, so one is likely to hog most of the available current.

A separate resistor per LED is probably best.


The ESP8266WebServer uses callback functions to handle HTTP request by your code. This callback functions can't be members of a class. But you can use anonymous functions to implement this callbacks. And if you like you can implement them as 'redirects' to functions of your objects.

server.on("/leftbutton", []() {
  currentgui.leftbutton(server);
}

Note: this anonymous functions are called lambda functions and they can do some tricks with parameters too


If I understand you well, it's very easy.

Assuming the 4 outputs of the switch will be connected to 4 GPIO's you just can check for the state of each GPIO and act on it

// Pin numbers where switch 1 to 4 are attached to.
#define PIN_SWITCH_1  8
#define PIN_SWITCH_2  9
#define PIN_SWITCH_3 10
#define PIN_SWITCH_4 11

unsigned long timer_value = 1000; // No switch selected

void setup()
{
     // Set switch pins to input mode.
     pinMode(PIN_SWITCH_1, INPUT);
     pinMode(PIN_SWITCH_2, INPUT);
     pinMode(PIN_SWITCH_3, INPUT);
     pinMode(PIN_SWITCH_4, INPUT);

     // Check switches
     if (digitalRead(PIN_SWITCH_1) == HIGH)
     {
         timer_value = 30000;
     }
     else if (digitalRead(PIN_SWITCH_2) == HIGH)
     {
         timer_value = 60000;
     }
     else if (digitalRead(PIN_SWITCH_3) == HIGH)
     {
         timer_value = 90000;
     }
     else if (digitalRead(PIN_SWITCH_4) == HIGH)
     {
         timer_value = 120000;
     }
     else
     {
         // Keep default value
     }
 }

 void loop()
 {
     // Here you can use timer_value to check for the end of the game.
 }


with readBytesUntil and C string

if (Serial.available()) {
  char buff[32];
  int l = Serial.readBytesUntil('\n', buff, sizeof(buff));
  if (l > 0 && buff[l - 1] == '\r') {
    l--; // to remove \r if it is there
  }
  buff[l] = 0; // terminate the string
  char* p = strchr(buff,'T'); // returns pointer in string
  if (p != NULL) {
    *p = 0; // write 0 as char at pointer to terminate the first part
    p++; // move the pointer to next char
    Serial.println(buff);
    Serial.println(p);
  } else {
    Serial.println(buff);
  }
}


RePaper 2.7" eInk Display with Arduino Due

You're trying to port the library from the Due to the Mega? If the library is large a "port" just isn't going to happen because relatively minor modifications to the code are very unlikely to shrink the size significantly; you'll need a complete rewrite.

My suggestion is to start by studying the data sheet for the device and the code for the existing Due driver to get an idea of how it works. Then sit down and write some sketches for your Mega that make something happen on the display (perhaps just clearing it, turning on and off a few specific pixels, the like) to verify your understanding. Once you've done that, you can start to consider the design of your driver.

Because of the vastly different memory limitations it's likely that your driver will look and work very differently from the Due driver. For example, a 264 x 176 x 1 bit frame buffer would use almost 6K of RAM (most of the RAM in a Mega 2560 and far more than in an Uno), so you're not going to want to have one. I don't know if the Due driver has a frame buffer (I'm just using this as an example of a typical difference you might encounter), but if it does, and that's used for doing certain kinds of things, you'll need to do them in a different way or not do them at all.

This is not a simple project, but it's a great one and will teach you a lot about microcontroller programming!


esp8266-01 and arduino UNO communicating over i2c

Perhaps the Serial.print()s in the slave's request event function are causing too much delay (clock stretching?). You should make the Wire.write() the second statement in that function right after the getTime call. Or you could use Wire.write("Hello") as the only statement in the function, so you can narrow down the problem.


C# Arduino: How to detect if the needed software is present on the computer

How would i go about finding out if there is the needed driver on that computer where the digispark is plugged in

I can't think of any way to do that. That's like asking if a keyboard you plug into a USB port can tell if you have Photoshop installed or not.

  Is there any way to add my program made in c# to the digispark ...

No. The Digispark is a tiny computer based on the Attiny85 which has 8k of program memory, some of which is dedicated to a bootloader which lets you upload new code.

Your project is far too ambitious for the level of hardware you are proposing to use. In fact this video which I watched the other day comes to mind:

https://www.youtube.com/watch?v=s7AXskSxxMk

From a comment:

  the it refers to the digispark, when connected the digispark checks if the f17 key is pressed down and if it is that means my program is running in the background so use the functions that are compatible with the program

OK, so you want the host computer (not the Digispark) to pretend it is holding down F17, and then when the Digispark is plugged in it checks if F17 is down, and if so it knows that the desired program is running on the PC. Is that your idea?

The problem here is that the Digispark is a USB device (not a USB host). I suppose it would be possible to write a special device driver on the PC that, once the Digispark connects, would send some special code to say whether or not the program is running. However with the Digispark only having 8 KB of program memory, this extra code (on the Digispark) might be hard to fit in. Plus you would need to write your USB device driver. Plus the device driver would need to be able to query what programs are running.

I think a far simpler solution would be to have an On/Off button on the Digispark. If you plug it into a PC which has this special program running you press the button, then the Digispark sends the alternative commands to your C# program.


It has nothing to do with the retun statements. You have to close each { with a }. you are missing one.

   {
int index;

pinMode(10, INPUT); //button input

int checkInput();

if (digitalRead(10) == 0) {

return 1;}
else{

return 0;
 }
}


You can interface with the fog machine's button by:

Use a Relay (this will isolate the fog machine's circuit from your Arduino's)
Use a Servo to physically press the button on the fog machine

I believe those would be the simplest and most generic.


I didn't try myself, but in the documentation it shows the MAX value is  2,147,483,647, which is 2^31-1. The MIN value I expect is -2^31, thus -2,148.483.648. Wondering what you mean by 'without success'.
Yes this is a valid approach. A 'perfect' random generator should be able to generate all values with an equal distribution. Since the values are within [-2^31, 2^31-1] this means all values within a 32 bit value is used, which automatically means all bits are also evenly distributed. So you can pick individual bits (as long as you use the entire MIN/MAX range).
In principle all seeds are good, as long as they are random. In the documentation it is advised to take an unconnected analog pin value. If you don't have one unconnected, you can use e.g. the millis function.


2,5m cable too long for LCD connected to Arduino UNO?

If the interface you're using is I2C(only two cables from arduino to lcd, vice versa)you have a problem,you need to pull up the sda-scl channel with appropriate resistors, you could (maybe) boost the I2C signal using ti-p82b715 bus extender, I just assume you use I2C (2,5m length?), what interface do you use? SPI? I2C?


How can I add some additional 5 volt power

At this point, can I also connect the regulator's VOUT to the Arduino's 5volt out?

Absolutely. But don't daisy-chain the regulator to each supply input in turn, connect each one separately directly from the regulator.

  Also, is it possible (or advisable) to add second voltage regulator to the first in a parallel configuration?

It is not advisable. Small manufacturing differences between regulators can result in them outputting slightly different voltages, which will lead to destruction of hardware.


The BMA421 was not locked. An erroneous write to the wrong register had switched it to the (non-existant) SPI interface. The solution was to power cycle the sensor.


need help in code to send sms to multiple contacts using arduino, gsm800, push button

You need to refactor you code, It has become just too complicated for this kind of straight linear code! Your code must be organized better, Don't Repeat Yourself (DRY); just by doing this you may find your error(s).

First lets fix your variables:

#include <LiquidCrystal.h>
#define NUMBUTTS 4
int ButtonValues[NUMBUTTS]= {0,0,0,0};
int Buttons[NUMBUTTS]= {8,9,10,11};
int buz=12;
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

and add some new ones

String numbers[NUMBUTTS] =
{
    "+91234567890",
    "+91234567890",
    "+91234567890",
    "+91234567890",
}

String msgs[NUMBUTTS-1] =
{
   "GUD MNG.. BUS STARTED FROM STARTING POINT\r",
   "BUS IS @ 1st stage\r",
   "BUS IS @ 2nd stage\r",
}

next lets clean up your function:

void okcheck()
{
    unsigned char rcr = 0;
    while(rcr != 'K') // rcr can't be 'K' when it starts as 0
        rcr = Serial.read();
}

Setup needs to be changed now that we changed your vars:

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

    pinMode(buz,OUTPUT);
    digitalWrite(buz, HIGH);

    for(int i=0; i<NUMBUTTS; i++)
        pinMode(Buttons[i],INPUT);

    lcd.begin(16, 2);
    lcd.clear();
    lcd.print("INNOVATIVE CLG");
    lcd.setCursor(0, 1);
    lcd.print("BUS INFO SYSTEM");

    delay(1000);
}

now we need to extract duplicated code and put it in a function:

// common starting code.
void preamble()
{
    Serial.write("AT\r\n");
    okcheck();

    Serial.write("ATE0\r\n");
    okcheck();

    Serial.write("AT+CMGF=1\r\n");
    okcheck();

    Serial.write("AT+CNMI=1,2,0,0\r\n");
    okcheck();

    Serial.write("AT+CSMP=17,167,0,0\r\n");
    okcheck();
}

// common message code
void send_sms(String& msg)
{
    String prefix = "AT+CMGS=\"";
    preamble();

    for(int i=0;i<NUMBUTTS;i++)
    {
        Serial.write(prefix+numbers[i]+"\"\r");
        delay(100);

        Serial.write(msg);
        delay(100);

        Serial.write(0x1A);
        delay(2000)
    }
}

now we need to fix up loop():

void loop()
{
    for(int i=0; i<NUMBUTTS; i++)
    {
        ButtonValues[i]=digitalRead(Buttons[i]);
    }

    for(int i=0; i<NUMBUTTS-1; i++)
    {
        if(ButtonValues[i]!=0)
        {
            lcd.clear();
            lcd.print(msgs[i]);
            send_sms(msgs[i]);
        }
    }

    //special case for button4
    if(ButtonValue[3]!=0)
    {
         lcd.clear();
         lcd.print("BUS IS @ COLLEGE");
         digitalWrite(buz,LOW);
         delay(1000);
         digitalWrite(buz,HIGH);
    }
}

Now your program logic is separate from the code that sends the messages, and you can test each in isolation from each other. You can test that send_sms() actually sends SMSs. Then you can see if your logic does what you think it does; by either replacing send_sms() with a test stub, or just by inspection.

With clean code it should be easier to spot your problem. The code looks like it should work, so I would guess that the modem itself may be causing the delays, maybe it takes a while to send a message and you are queuing them up and it takes a few seconds to get through each one, its possible that not all get send because one or more gets dropped while it is busy sending another. Hard to know without looking at the documentation for your module.

Your diagram looks like it is hooked up wrong, you have TX-> RX, but MOSI -> TX; Serial.read() reads from RX not MOSI, so i don't know how checkok() doesn't just loop forever, since you left the arduino RX floating.


The driver chip was identified by https://www.waveshare.com/wiki/2.8inch_TFT_Touch_Shield and https://www.waveshare.com/w/upload/8/84/2.8inch-TFT-Touch-Shield-UserManual-EN.pdf as being the HX8347D.

At https://github.com/jshnaidman/UTFT_ESP8266_HX8347D there seems to be a library, with which you can use the HX8347D display type to instantiate a UTFT object, with which you can draw. You can build upon this demo code.

The connections for the SPI interface are detailed here. BL (backlight) pin is detailed here. The pin number for the D/C pin must be given in the code in the constructor and can be chosen freely.

Other reference code (which you might have to port) are:

HX8347D by Majenko
Code from Watterott


You would either have to replace the bootloader on your chip (software) with one that knows about your GPRS shield (I don't know if there is one, so you would most likely have to write your own and that is not a trivial task), or use a second microcontroller to act as a programming interface between the GPRS shield and the main Arduino.  That could be another Arduino.

The second option is probably the simplest to create:

The GPRS is connected to Arduino A.
Your main software runs on Ardiuno B.
Both Arduinos are connected by serial
Normal operation Arduino A passes all serial verbatim through to Arduno B
Arduino A receives programming instructions and downloads the new code - maybe storing it on an SD card temporarily (not enough RAM in an Arduino) then resets Arduino B into the bootloader.
Arduino A then sends the serial instructions in the same way that avrdude does to program the downloaded HEX file.

Arduino A is then a proxy between the GPRS and Arduino B.  Arduino A does all the control of the GPRS and sends data between Arduino A and the internet and vice versa - it's up to you to decide how best to achieve that, depending on what information you have going backwards and forwards.

Both solutions require a certain level of programming knowledge and skill and aren't trivial, but are perfectly possible if you set your mind to it.


Where are these capacitors on the arduino schematic?

What: Looking at the schematic that you provided, it seems likely that they serve as C6 & C7.

Why: These are shown as 100 uF each and act as "filter" capacitors for IC4, the 5V regulator.
Within certain limits, such capacitors are not critical in value, and the manufacturer has probably decided that a factor of in the capacitance is probably acceptable.
They are probably correct :-).

How to check: You can check this yourself with an Ohm-meter set to the lowest Ohm range available - often = 200 Ohms max.

Turn off power to the board and leave it off for say 5 minutes to allow capacitors to discharge.
Locate I4 and find its input and output pins or tracks leading to them. You can often get ohmic connections at vias as the tracks change board layers.
IC4 pin1 will be grounded.
One lead of C6 & C7 are also grounded.
The pad you can see in your photo on the board edge side of the caaps is probably the -ve terminals (about 99%+ likely) (and they match the can markings)
and the "stippled" surface is almost certainly system ground.

If you can confirm that the two caps are connected to ground as and where described above, then:

Apply Ohm meter probes between the non ground lead of a capacitor and each non-ground pin in turn of IC4. One of them will be a low resistance connection if they are C6 & C7. Check the other capacitor - it should connect to the other side of IC4.
Reversing the meter leads in each case may give somewhat different readings for non-hard-connected points but should be low and consistent for hard-connected by a track points.


setup() resets from loop, when I add parameters to http get `?identity=%2B0123456789&identityType=1`

"Something crazy while sending parameters ??"

Possibly your power supply is to weak so 5V drops low and the processor resets when the transmitter sends a message.


there are varius calculation.

At the end of the day, if take a point in every position (under no acceleration), you should end up with a sphere, or matematically speacking, wthe lenght of the vector should be equal to gravity, so sqrt(x*x+y*y+z*z) = G or, to do less computing x*x+y*y+z*z = G*G (same apply for magnetometer, but using local magnetic force, or gyroscope, using a know-speed rotation like a LP player)

To create that spere you have to take many point, and find a multiplicator (or function) for each axes. That is particualary important when one axes has differnet precision of others, you are linearizing the axis output, and then normalizig its value relative to others axes.

Once you have corrected the vector lenght to have a spere, you should look at the offset of the sphere; if its center point is not on the origin point 0,0,0 then the differece between center and origin is the correction you talk about. This is offset correction.

Also many (well, all) sensor are affected on their temperature; many claim to be "thermocompensated", that means this difference is less evident due to some some sort of hardware and/or software filtering.


If you scroll down on that page you link to you can see the power circuit. It uses an XC6206 voltage regulator which has a maximum input voltage of 7V and a dropout voltage that could be as high as 680mV.
So you can feed between about 4V and 7V in to the VIN pad and it will step it down to 3.3V. Anything below 4V and you will go "out of regulation" though the system may still run down to lower voltages. If you go above 7V you will blow it up.


Seeking help - Using CJMCU 8*8 LED matrix with arduino

I just received 2 of these from 2 different suppliers on EBAY.
None work using the pins called [GND +5V DIN]. As it turns out the DIN is actually NOT DIN. The other connector area [GND +5V DOUT] is the DIN. Ugh!

These boards are marked CJMCU-8*8 on the back side and on the front they say "WS2812B-64 RGB LEDS". Which is another issue. They are using the 6 pin WS2812, not the 4 pin WS2812B.

So if this is what your board looks like then perhaps try the pin marked DOUT for your DIN. Or try to psych out the traces to make sure first.


How to program a CAN-BUS Arduino shield to control car windows?

What model car do you have?  Most cars do not have the ability to control power windows from the car computer.  Late model cars will have the ability to control the window motors using bidirectional functions on a scan tool.  On any car, the window motors have two wires, if one wire is given power and one ground it will spin if you switch the wire that gets power with the wire that gets ground it spin in the opposite direction.  In my experience the way power windows work are both wires are ground while the switch is in the neutral position and by flipping the switch the switch will disconnect one of the grounds and replace it with a power.  Find a wiring diagram for your car, and look at how the windows are controlled.

Get a 2 relay breakout board such as this one (make sure you check the current ratings):
http://www.amazon.com/SainSmart-2-CH-2-Channel-Relay-Module/dp/B0057OC6D8/ref=sr_1_1?ie=UTF8&qid=1400730995&sr=8-1&keywords=arduino+relay+12v

Connect the ground wire to the normally closed (when no power is applied to the relay this is connected to the output wire) side of both relays and the 12v power to the normally open (when power is applied to the relay this is connected to the output wire)side of both relays.

In order to control the relay breakout board you choose one io pin per relay and set it as an output, then connect those pins to the corresponding pin on the breakout board. Set one of the pins to high (you apply power to one relay) the motor now has a power and a ground connection, set the opposite pin high to spin the other way.

I would place this in the driver side door underneath the window master switches because you can have access to every windows wires as they come out of the master switch.

Some late model cars will have a different set up than the one described, but the window motor will only have two wires (it is just a brushed DC motor) just find the window motor and hookup there.

I hope this helps.


What is the sizeof() Arduino's built in HIGH and LOW?

In Arduino AVR Boards, HIGH and LOW are currently macros:

https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/Arduino.h#L40-L41

#define HIGH 0x1
#define LOW  0x0

This means that sizeof(HIGH) is equivalent to sizeof(0x1). 0x1 is an integer constant. The default type of integer constants is int. On an 8 bit microcontroller like the ATmega2560 used by your Arduino Mega, an int is 16 bits.

That is why sizeof(HIGH) returns 2 (16 bits / 8 bits/byte = 2 bytes).


Why doesn't my 7 segment update every second like in the program?

This is the code that fixed the issue:

  #include <SevSeg.h>
  SevSeg sevseg;

  void setup() {
    byte numDigits = 4;
    byte digitPins[] = {5, 4, 3, 2};
    byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(50);
    sevseg.setNumber(0000, -1);
  }

  void loop() {
    unsigned long timerGlobal = millis();
    sevseg.setNumber(timerGlobal/1000, -1);
    sevseg.refreshDisplay();
  }

In this, no delays are needed. millis is divided by 1000 and the integer second is drawn on the display. Proved to be much easier than I previously thought.


If you are thinking of using OpenCV with a "normal" Arduino, such as the Uno or Mega, then think again. OpenCV runs on a computer - be that a desktop computer or an embedded computer. Basically you need an operating system; "normal" Arduinos don't have an operating system.

It may be possible to run OpenCV on an Arduino that runs Linux (some of the strange Intel things that are being marketed as Arduino do, as does the Yún), but in that case you will be writing a Linux application, not working in the Arduino IDE. You would need to treat it as a normal Linux computer and use the normal Linux tools for developing on it (note that OpenWRT that the Yún runs is tricky to develop for - the best way is to cross-compile on a real computer running Linux using the OpenWRT "Buildroot" system).


How to connect a 12V power supply to an RGB LED strip receiving RGB values via Arduino Uno PWM pins?

01) Is the above diagram safe and sound?

It looks to be OK, except one thing:

The current you can draw from the Arduino's VIN pin is limited to about 1A. That is a sixth of what your power supply can provide, and the LED strip when everything is on needs more than that (1.2A), so you could run into problems.  The limit is threefold:

The barrel jack itself is rated at up to 1A
There is a protection diode with a limit of 1A
The header pins are rated at up to 1A

And of course the Arduino itself needs to use some of that available 1A.  So you might be better off splicing your LED circuit into the power supply's wire before it enters the Arduino.

  02) How do I connect the power supply to the RGB LED strip?

Power goes in (+) to the common pin of the LED strip and then out of any of the three colour pins that happen to be connected to the ground of the power supply. That is, the ground of the Arduino in your schematic since they are (as they should be) all shared.

  03) Is it ok to keep the Arduino 'powered' by the USB whilst plugged in to the 12V power (so that it can keep sending the RGB values to the LED strip via the PWM pins)?

Yes. There is circuitry on the Arduino that allows both the USB and barrel jack to be plugged in together.

  04) I've seen references to grounding the power source, how do I do that?

That refers to connecting the external power supply's ground and the Arduino's ground together. By using the barrel jack that is all taken care of for you.

  05) Are the MOSFETS I have from the Arduino Uno starter kit sufficient for this task?

Not really.  They are designed to be switched with a higher voltage than the Arduino's IO pins provide.  While they will work, they may cause the LEDs to be dimmer than they should be, or the MOSFETs might get hot.  Basically a MOSFET has a "threshold" voltage range which is the voltage range at which the MOSFET transitions from off to on. That is 2V - 4V for that MOSFET, which while within the range of an IO pin isn't really that great. At 4V the MOSFET still isn't completely on. You may notice from the datasheet that the "R_DS(ON)" value - that is the resistance of the MOSFET when it is on, is measured with the gate voltage at 10V. That is a voltage where the MOSFET is guaranteed to be fully on. Anything less than that and the resistance will be higher causing more losses across the MOSFET.  I could see that instantly from the model number - it starts with "IRF".  There is a specific range from International Rectifier which is designed to be directly driven by an IO pin - these are the "IRL" (for International Rectifier Logic-level) series.  These have their R_DS(ON) values measured typically at a gate voltage of 4.5V and a threshold voltage in the region of 500mV to 1.5V. When directly driving from an Arduino these IRL (or equivalent from other manufacturers) are preferred.


I'm trying to use a E18-D80NK but the output is always 1

There are a few possibilities for what is wrong:

1) The wiring may be wrong: the datasheet you reference lists two types (red,black,yellow) and (blue,brown,black) but in your pic it looks like you have (blue, grey, black).  I wouldn't assume the color coding of the sensor wires are correct.

2) The "pull-up" resister mentioned in the data sheet referenced (and included schematic) is not functioning as a pull-up resistor.  I would get rid of the resistor and plug the digital-output wire of the sensor directly into the arduino input.   Also, try configuring the input with pull-up like:  pinMode(irPin2, INPUT_PULLUP);
The Arduino inputs are high impedance and typically do not need a series resistor.


How do I upload sketch (and parameters) through a user interface

1) Why not just

system("avrdude ...");

That's more or less what the Arduino IDE does.

2) If you really want to embed the data in the executable, see
Embedding Blobs in
Binaries.
You would need to re-link and re-upload the program each time you change
that data. You won't need the Arduino IDE, as it's only job is basically
to call avr-g++ and avrdude. You can use the IDE if you find it's CLI
easier than those of the standard tools.

If you put the data in EPPROM instead, the avrdude can upload it without
re-uploading the program.


How to use same sketch on two different computers in two different directories

Open preferences.txt in C:\Users\YourUserName\AppData\Roaming\Arduino and change the path of sketchbook.path=C:\Users\YourUserName\Documents\Arduino to sketchbook.path=YourDesiredPath.


How to drive N channel gate correctly from Adafruit Feather pinout?

Your problem is that the GPIO pin is referenced to ground - and the MOSFET is isolating that ground.

You need instead to switch the power not the ground - and for that, you use a P-channel MOSFET.

simulate this circuit – Schematic created using CircuitLab

To hold the power on you now set the GPIO LOW instead of HIGH.

If you need to switch a higher voltage than the operating voltage of the MCU you will need to add another N-channel MOSFET to pull down the P-channel's gate.


Errors when compiling the GSM SMS receive example from the Arduino IDE

Those are warnings, not errors.  The code should have compiled and be able to flash.


GyX=Wire.read()<<8|Wire.read();

This is a bug. It reads two bytes from the I2C bus and builds a 16-bit
number from them. One of the bytes (we don't know which one) will be the
most significant byte of the result. The other byte will be the least
significant byte.

This instruction is likely to work just fine on some particular version
of some particular compiler with some particular compiler options.
Presumably it did work for the author. But you should not expect it to
work consistently across compilers, or even across different versions of
the same compiler.

The proper way to do this is to perform the two reads in different
instructions:

GyX = (uint16_t) Wire.read() << 8;
GyX |= Wire.read();

assuming the bytes come most-significant first.

Edit: added (uint16_t) cast. C.f. this answer.


You've set pinMode(sig,INPUT); and never changed this back to OUTPUT before triggering next measure:

void loop() {
   pinMode(sig, OUTPUT);    // ensure sig is configured as an output
   digitalWrite(sig, LOW);
   delayMicroseconds(2);
   digitalWrite(sig, HIGH);
   delayMicroseconds(10);
   digitalWrite(sig, LOW);
   pinMode(sig, INPUT);
   long duration = pulseIn(sig, HIGH, 38000);
   delay(2500);
}

And for example PING))) (which is basically the same module) has power consumption about 30mA-35mA in datasheet. Output pin might be strong enough to power it, but I'd recommend at least GND connect directly to arduino GND. And using transistor for powering it up would be even better


How to check if a GSM module is working or not?

Power it up and check the 'status' light.  If it blinks with a 1 blink per second cycle, it is attempting to connect to the network.  If it connects, it does a slow blink at 1 blink/3s, it made the network connection.

I don't know if your board does an auto-power-on, but you might need to push the power button or reset button.


Arduino servo seems to time out after code runs for some amount of time

int in AVR architecture is signed 16 bits. This means 40000 is actually an overflow if it gets assigned to an integer. It would work in most cases, but when the resultant number is > 32767, you would get a minus value, which may cause delay not to work properly.

In order to solve the issue, you may either use long int for randnum or use a random interval smaller than 32768.

Edit: I did some calculation, if you hit exactly 40000 you would delay for 4294974529 milliseconds (+/-1). Any value over 32767 will cause delays that are extremely long.


With the help of the comments, I decided to use variable PWM max values to match absolutely with the frequency. This resulted in a crispier sound that actually doesn't need the Sallen Key anymore.
For example, a low C natural, or 261.6Hz, updated 32 times for 8 full cycles of PWM give us, for a 16MHz chip, an period and amplitude of 238.
This means that having a prescaler of 8 (CS01), a period (OCR0A) AND a max potential duty cycle (ICR1) of 238, and going through 32 iterations of the sound sought for, I got the sound that I wanted and none of the wave groove that comes with a pulse duty cycle cut short.
Sure, it means less granularity when it comes to a Bb with a max duty cycle of 133, however it worked for me.


Recover from wrong Wi-Fi password on Arduino Yún

The simplest option is to provide a serial console interface which will either give full access to the OS (pipe through Console) or a menu driven interface that sends instructions to the main chip (through Bridge).

The user would then connect to the USB interface and use a terminal program to access the configuration in whatever way you have chosen.  This could either be via options within your installed sketch, or by uploading a special sketch through the USB connection.


Problem controlling a Stepper motor with AccelStepper

Ints on vanilla Arduinos are 16 bits, and signed, which means they hold values from -2^15 to +2^15-1, so of course you cannot assign 10^6 to one of them. Use unsigned long (4 bytes), or, better yet, specify the length explicitly by using uint32_t.


Connecting arduino to an existing circuit

Yes, This can be achieved without a transistor.

As the circuits would be on isolated power supplies: Arduino circuit on one and the clock on another, you can use a Solid State Relay.

Use the relay with your Arduino (5v or 3.3v) and wire the relay contacts parallel to the clock switch. This will isolate any power issues as clock will be powered with its own power and Arduino will be powered with its own.

You can program Arduino with proper delays to actuate the relay accordingly.

Hope this helps.


ESP32 Pins won't fit in solderless breadboard

I understand. These breadboards are pretty difficult to work with. Not only fitting an ESP-32 or similar board is difficult, these breadboards are not broad enough to expose all the GPIOs on both the sides.
I had solved this problem in this video. Do have a look. It might be helpful
https://youtu.be/CQlbE1x2i2g


You asked if anyone else has experienced this behavior, and from the documentation I can find the answer must be yes.

The 505 holds the HIGH output for a certain amount of time.  None of the documentation I can find on it specifies the amount of time.  So it is very possible that you are operating right near that limit.  If their quality control is not perfect, some might work correctly and some might not.

In other words, I believe the problem is that you are not allowing for the built-in time delay in the SR505.

That is the main difference between the 501 and the 505.  On the 501 it is adjustable in both sensitivity and time delay.  With the 505 those values are preset.

As a workaround, you can try increasing your delay upwards from 2000ms until you find the right value that will work consistently with your batch of them.

The sensitivity cannot be adjusted, either, but this can be an advantage if you are trying to cover a smaller area than you would try with the 501.  They both have the same 90-100 degree width of view, but the 505 is made for shorter range like a doorway, as opposed to the 501 which can cover an entire room.


No power from Breadboard Power Supply Module

I'm not surprised you can smell burning. You have the power supply connected backwards.

You see that little + and - symbol next to the ON/OFF jumper? That's the polarity of the two runs of pins. You have the + row connected to the - rail of your breadboard (blue) and the - row connected to the (red) positive rail.

Turn the power supply around 180° and connect it to the other end of the breadboard - the rails will be the other way around then.


First, let me give a couple of suggestions on the programming style.
There is no point in defining your own variables for accessing the
hardware registers: the avr-libc does that for you, you just have to
#include <avr/io.h>. Actually, you don't have to #include anything:
the Arduino IDE automatically #includes Arduino.h, which in turn
#includes avr/io.h.

Next, the same avr-libc also defines macros for the bit names, so you
don't have to explicitly write binary numbers in your own code (which is
error-prone). And a couple of utility macros that you can use to make
the code a little bit more readable. For example:

void adc_init()
{
    ADMUX  = _BV(REFS0);  // ADC reference = AVCC
    ADCSRA = _BV(ADEN)    // enable the ADC
           | _BV(ADPS2)   // set prescaler to 128
           | _BV(ADPS1)   // ditto
           | _BV(ADPS0);  // ditto
}

unsigned int adc_read(unsigned char adc_channel)
{
    ADMUX   = _BV(REFS0) | (adc_channel & 7);  // select channel
    ADCSRA |= _BV(ADSC);  // start conversion

    // Conversion is complete when ADSC goes low.
    loop_until_bit_is_clear(ADCSRA, ADSC);

    return ADC;  // return the adc data register
}

Now, let's answer your actual question. When you set both REFS0 and
REFS1 to 0, the voltage reference is stated to be “AREF, internal V
REF turned off”. The implication is that you are supposed to bring your
own voltage reference and connect it to the AREF pin. Otherwise AREF is
left as a floating input. This is illustrated in the schematic of the
ADC. Here is the relevant part:

As you see here, REFS0 is used to connect AREF to one of the other
possible references: either AVCC or the internal bandgap. If REFS0 is
zero, the transistor depicted above is off, and AREF is left floating.


I would like ... to adjust the transmission power to lower the power requirements.

Is your goal to reduce overall/average power consumption, or peak current draw? If the former, then because of the high-level nature of the wifi API exposed by the ESP system, you may get a greater level of success by optimizing the time you are connected, rather than the power consumption.

That is, make sure WiFi radio is disabled while you are preparing whatever data you may wish to send over WiFi, then turn the radio on, connect+send, go back to sleep.

This blog post gives experimental details, but the gist is

In Setup():

WiFi.mode( WIFI_OFF );
WiFi.forceSleepBegin();
delay( 1 );

Just before you choose to connect:

WiFi.forceSleepWake();
delay( 1 );

// Bring up the WiFi connection
WiFi.mode( WIFI_STA );
WiFi.begin( WLAN_SSID, WLAN_PASSWD );

And, when you go to sleep, tell the system to keep the radio off by default:

WiFi.disconnect( true );
delay( 1 );

// WAKE_RF_DISABLED to keep the WiFi radio disabled when we wake up
ESP.deepSleep( SLEEPTIME, WAKE_RF_DISABLED );

Part 3 of this blog also notes that if you will continually be connecting to the same WiFi network, you can tell the ESP8266 to not spend the time loading the previous connection's details from flash memory, but requiring you to provide them in the connection call:

WiFi.forceSleepWake();
delay( 1 );

// Disable the WiFi persistence.  The ESP8266 will not load and save WiFi settings in the flash memory.
WiFi.persistent( false );

WiFi.mode( WIFI_STA );
WiFi.begin( WLAN_SSID, WLAN_PASSWD );


How about fastening a wire to the post, and then the other end, on the bike, goes into a "jack" (the sort of thing you plug headphones into). With the wire inserted, it makes a connection, and the Arduino knows the wire is there. As the thief steals the bicycle the plug (or loose wire) is pulled from the jack, breaking the connection. i.e.


esptool.py is 'avrdude' for the esp8266. it can read the flash too. but you must know the addresses. tha first copy of the application always start at address 0x1000. the length of the application area depends on the size of the flash and the size of the SPIFFS.

> esptool.py read_flash -h
usage: esptool read_flash [-h] [--spi-connection SPI_CONNECTION]
                          [--no-progress]
                          address size filename

positional arguments:
  address               Start address
  size                  Size of region to dump
  filename              Name of binary dump

optional arguments:
  -h, --help            show this help message and exit
  --spi-connection SPI_CONNECTION, -sc SPI_CONNECTION
                        ESP32-only argument. Override default SPI Flash
                        connection. Value can be SPI, HSPI or a comma-
                        separated list of 5 I/O numbers to use for SPI flash
                        (CLK,Q,D,HD,CS).
  --no-progress, -p     Suppress progress output


Arduinos are for rapidly getting something going without having to know much about the underlying electronics and microcontroller.  As a result, some design tradeoffs were made for you, generally optimized for development simplicity.

You now have a different primary concern, which is low power consumption.  If that is truly important, then you have to design the system with that goal up front.  This means starting with the bare microcontroller, designing the electronics around it carefully to minimize power, and designing the firmware architecture to minimize high-power cycles and maximize sleep time.

You are asking where to strap the big engine on a Honda Civic to make a high performance racing car.  You can make a Civic higher performance, but to get really high performance you have to start with that goal from the beginning.


It sounds like the microcontroller is browning out.

IR sensors are notorious for taking a lot of power when they operate; often they will tax a small power supply and cause the voltage to droop low enough to reset/brownout the microcontroller.

Try either putting a fairly beefy capacitor on the power bus, or getting a larger power supply.

Hope this helps!

(edit: I reverted another user's edit to this answer; "droop" is in fact the correct term for what is going on: http://en.wikipedia.org/wiki/Voltage_droop)


Resistance in Switch (negative vs positive logic)

From a pure electronics viewpoint, there is no real difference between both circuits, the difference will be handled by your code running on the MCU, as a close switch will either be HIGH or LOW depending on the logic you used to wire your switch.

The resistor must be present for 2 reasons:

to avoid producing a shortcut between +5V and GND when the switch is closed, without it the shortcut would probably damage your power supply circuitry (if both pins are directly taken from Arduino, that would mean damaging Arduino supply circuits)
to make the voltage pin attached to the pin the "winner" of both voltage pins when the switch is closed, ie that pin will provide the level to Arduino input pin

The value of the resistor should  be:

high enough to limit the current between +5V and GND when the switch is closed, preventing damage and limiting overall power consumption of your circuit
not too high to allow providing a voltage level to the input pin

Using 10k means that, applying Ohm's law, when closing the switch, a 0.5mA current would flow from +5V to GND, which is generally acceptable in terms of consumption and cwill not damage your power supply.

Note that the input pin is "high impedance" which means it has no voltage level if not connected to anything, and it does not supply or sink any current (or more accurqtely a negligible current only).

Finally, it is good to know that Arduino MCU offers the INPUT_PULLUP mode for digital pins, where an internal resistor pulls up the pin input to 5V.  This enables you to directly connect your switch between the pin and GND. So you just have to code:

pinMode(XXX, INPUT_PULLUP);

instead of:

pinMode(XXX, INPUT);

For information, according to ATmega328P datasheet (the MCU of Arduino UNO), those internal pullup resistors have a value between 20k and 50k.


GPS logging on the intel edison breakout board

Try this:

String GPSLine;

bool checkGPS()
{
  while(serialGPS.available())
  {
    char c = serialGPS.read();
    if(c == '\n') return true;
    if(c == '\r') continue;

    GPSLine += c;
  }
  return false;
}

void loop()
{
  if(checkGPS())
  {
    Serial.println(GPSLine);
    GPSLine = "";
  }
}


If you have a read of section 31 of the Datasheet, available from here, things may come a little clearer for you.

Here's a summary of what I know:

PIO stands for Parallel Input/Output and offers the functionality to read and write multiple register ports at a time.  Where the datasheet mentions a register, for example PIO_OWER, the Arduino library has macros for accessing them in this format REG_PIO?_OWER where ? is either A, B, C or D for the different ports available.

I tend to still use the slow Arduino pinMode() function to set input/output on the pins as it makes the code more readable than the acronym based registers calls such as REG_PIOC_OWER = 0xdeadbeef, but then use the direct registers to set the pins for performance/synchronisation.  As yet, I haven't done anything with input, so my examples are all output based.

For basic usage, you would use REG_PIO?_SODR to set output lines high and REG_PIO?_CODR to set them low.  For example REG_PIOC_SODR = 0x00000002 would set bit 1 (numbered from zero) on PORTC (this is Due digital pin 33) high. All other pins on PORTC remain unchanged.  REG_POIC_CODR = 0x00000002 would set bit 1 on PORTC low.  Again all other pins would be unchanged.

As this is still not optimal, or synchronised if you are working with parallel data, there is a register that allows you to write all 32 bits of a port with a single call.  These are the REG_PIO?_ODSR, so REG_PIOC_ODSR = 0x00000002 would now set bit 1 on PORTC high and all other bits on PORTC would be set low instantly in a single CPU instruction.

Because it is unlikely that you would ever be in a situation where you need to set all 32 bits of a port at the same time, you would need to store the current value of the pins, perform an AND operation to mask out the ones you want to alter, perform an OR operation to set the ones you want set high then perform your write and again, and this is not optimal.  To overcome this, the CPU itself will perform the masking for you.  There is a register called OWSR (output write status register) that will mask out any bits that you write to ODSRs that don't match bits set in the OWSR.

So, now if we call REG_PIOC_OWER = 0x00000002 (this sets bit 1 of the OWSR high) and REG_PIOC_OWDR = 0xfffffffd (this clears all bits except bit 1 of the OWSR) and then call REG_PIOC_ODSR = 0x00000002 again, this time it would only change bit 1 of PORTC and all other bits remain unchanged.  Pay attention to the fact that OWER enables any bits that are set to 1 in the value you write and that OWDR disables any bits that are set to 1 in the value you write.  Even though I understood this when I read it, I still managed to make a code mistake when writing my first test code thinking that OWDR disabled bits that weren't set to 1 in the value I wrote.

I hope this has at least given you a bit of a start in understanding the PIO of the Due CPU.  Have a read and a play and if you have any further questions, I'll try to answer them.

Edit:
One more thing...

How do you know which bits of the PORTs correspond to which digital lines of the Due?  Check this out: Due Pinout


Arduino communicate between 2 different router in different location

It's not the Arduino that has anything to do with this but the routing, port forwarding and/or VPN that you set up between your routers.

I'd have thought, since you're in your final year of IT, you'd at least have some rudimentary knowledge of routing, port forwarding and VPNs...


Can I connect a servo directly to arduino uno without a transistor?

The Arduino's GPIO pins can drive the signal of most model servos directly, without any extra transistors.

Driving a model servo signal input is not the main problem with driving servos from an Arduino.

The main problem is trying to use the Arduino's power supply to power the model servo. With many model servo's, the amount of current the model servo needs to start, or when it is almost stopped is so big that the Arduino's power supply can't maintain 5V. As the Arduino's power supply voltage drops, the Arduino often gets reset, and the program restarts from setup.


String class summation disappears the right operand

Your "disappearing string" has the following cause: Out-of-Memory.

You are constructing lots of String objects in your code and are concatinating to one. That uses memory on the heap for each String (and realloc() when the String memory must be expanded).

Consider the following test sketch which includes your code but also adds a memory leak by 150 bytes in each iteration:

#include <Arduino.h>
#include <ArduinoSTL.h>
using namespace std;

extern unsigned int __heap_start;
extern void *__brkval;

/*
 * The free list structure as maintained by the
 * avr-libc memory allocation routines.
 */
struct __freelist {
    size_t sz;
    struct __freelist *nx;
};

/* The head of the free list structure */
extern struct __freelist *__flp;

/* Calculates the size of the free list */
int freeListSize() {
    struct __freelist* current;
    int total = 0;
    for (current = __flp; current; current = current->nx) {
        total += 2; /* Add two bytes for the memory block's header  */
        total += (int) current->sz;
    }
    return total;
}

int freeMemory() {
    int free_memory;
    if ((int) __brkval == 0) {
        free_memory = ((int) &free_memory) - ((int) &__heap_start);
    } else {
        free_memory = ((int) &free_memory) - ((int) __brkval);
        free_memory += freeListSize();
    }
    return free_memory;
}

String jsonificar(vector<vector<String>> sujeito) {
    String json_txt = String(""), chave, valor;
    String chave_str, valor_str;

    json_txt += String("{");
    for (unsigned int i = 0; i < sujeito.size(); i++) {
        if (sujeito[i].size() != 2) {
            Serial.println("Cada conteudo deve conter 2 textos!");
        } else {
            chave = sujeito[i][0];
            valor = sujeito[i][1];
            Serial.println(chave);
            Serial.println(valor);
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += chave;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += ":";
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += valor;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);

            if (i != sujeito.size() - 1) {
                json_txt += String(",");
            }
        }
    }

    json_txt += "}";
    Serial.println(json_txt);

    return json_txt;
}

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

String myStr = "";

void loop(void) {

    Serial.print(F("Free Memory:"));
    Serial.println(freeMemory());

    //force a memory leak by allocating appending to a global String
    myStr +=
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

    vector<vector<String>> v =
            { { "Chave1", "Valor1" }, { "Chave2", "Valor2" }, };

    jsonificar(v);
    delay(1000);
}

From the output we can see the exact point where we have enough memory and the result is correct, and where we don't have enough memory and the string just "disappears" because there was not enough memory to allocate it:

Free Memory:911
Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"Chave2
{\"Chave1\":\"Valor1\",\"Chave2\"
{\"Chave1\":\"Valor1\",\"Chave2\":
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"}
Free Memory:761
Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"Chave2
{\"Chave1\":\"Valor1\",\"Chave2\"
{\"Chave1\":\"Valor1\",\"Chave2\":
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"


How to send numbers to Arduino UNO via Python 3 and the module serial

Parsing on the Arduino can be slow and time-consuming (which is bad if you use clock prescaling or have time-critical tasks), so let's do it in Python.

The problem is that you're sending the numbers as ASCII whereas you need to be sending them as raw binary. This is where struct comes in.

3>> import struct
3>> print(struct.pack('>B', 0))
b'\x00'
3>> print(struct.pack('>B', 255))
b'\xff'
3>> print(struct.pack('>2B', 255, 0))
b'\xff\x00'
3>> print(struct.pack('>H', 9000))
b'#('

So what you really want is:

data = arduino.write(struct.pack('>B', valueToWrite))

or something to that effect.


Reading out two sensors via Com-Port at the same time

Shouldn't the Com-Ports be independent?

Not in the Arduino IDE, no. Basically the IDE is [expletive deleted] when it comes to using more than one board at a time.

You're better off using a proper serial terminal program, not the "serial monitor" in the IDE. Something like Teraterm or Putty, where you can have multiple instances on different ports at once.


Arduino Leonardo - disabling the debugger port

There is no easy way, no. You have to reprogram the core to break the connection between the USB interface and the CDC/ACM driver. That means working out a new set of descriptors, deleting chunks of code, patching around the newly created holes, etc.


millis() function always returns same value

You never exit the ISR, hence all interrupts are disabled. Do the minimum work possible within an ISR, and have the main loop outside.


Help understanding code to build circuit for plant reader

Pin13 is attached to the onboard LED.

So when you see a reference to it, it means that the program is turning the light ON/OFF. You do not need to do any wiring with it.

But the logic seems strange: it turns the LED off only when the analog reading is out of range (and it resets the stress).

It seems to imply that once the plant is stressed, it will stay stressed :-)

Btw, as side note: posting the code in ASCII form would allow people to quote/comment on it. The screenshot is not very good for that purpose.

What cannot be figured out from the code, is how to instrument your plant.
If your friend has a working setup, you could try to replicate it.
At least post a few pictures.


Can you make Arduino Uno send information through a WiFi module to a server?

Yes, I can.

The simplest way is through an HTTP "GET" request. Every time you request a web page (and there are plenty of examples of that) you are sending data to the server to tell it both what web page to get (/foo/bar.php) and what data to submit to that web page (?baz=4).

It's then up to you to craft that GET request, such as:

GET /foo/bar.php?baz=4 HTTP/1.1
Host: example.com
Content-length: 0

and write the PHP web page (or whatever language you prefer to write web pages in) to do something meaningful with the "baz = 4" parameter.


(Note for the Arduino Uno: you'll need to add a 10 uF capacitor
  between reset and ground.)

From http://arduino.cc/en/Tutorial/ArduinoISP


You could check the connections of the breadboard, using a multimeter (set to continuity check) and wires in the breadboard holes, with the + and - leads, from the meter, at either end of each row/column of connections, following the diagram below:

It might be a bit tedious, but it should only take thirty minutes maximum, and would give you peace of mind as well as saving you four Euros...

If you say that it was working before and now is not, then maybe the breadboard is damaged. However, it is unlikely that the whole breadboard is... try moving your components to a different part of the breadboard.

The breadboard could possibly get warm, as servos can use a fair bit of current, and breadboards aren't really designed for power circuitry. You may be better off using an Arduino Servo shield and connecting the servos directly to that, rather than using the breadboard. Why are you using a breadboard - can you, as Majenko states, provide a schematic diagram?

Answering the last part of your question - Taking the graphics from my answer to Code to control servo with shield, to show the different colours for the four different connector types:

Futaba and Airtronics connectors

Hitec and JR Radio connectors have the same pin out:

.

This means that the red, brown and orange leads go to a JR Radios connector.


What isn't obvious is that with Arduino, you can have normal C and C++ files in the same directory as the .ino file. These can have functions and variables inside them, and Arduino will link them into the main program too. You only need one .ino file - all the rest can be in modules with a .c or .cpp (for C++) extension.

That way, you can group "helper" functions in different files by category - for example, a BrailleServo.c file. These contain the functions and variables for just that category.

If you haven't programmed native C/C++:

Put the functions and variables in the BrailleServo.c file, and then repeat the functions' header in the BrailleServo.h file.
Inside the BrailleServo.c file, at the top, put the following line:

#include "BrailleServo.h"

Note the quotes (" "), not angle brackets (< >)
Inside the .ino file, put the same #include line. That tells the module that "there are other functions elsewhere, and these are their definitions".

The only problem? Getting the silly Arduino environment to let you add .c and .h files to that directory. You could just use Notepad, but there's a trick (if you're using Windows):

Choose File|Open…
Right-click the pane with the files in it, and choose New >|Text Document
Give it a complete name, and make sure you replace the .txt part of the name too with .c or .h. You may get the "If you change the extension, the file may be unusable" warning - just click OK.
Select the new (blank) file in the file pane, and a new tab will appear.

  Note that 3. above assumes that you've told Windows File Explorer to NOT hide the extensions of known file types. I always do that - if you haven't, you'll need to. With:

  Windows 10:
  In any folder's View tab, tick the File name extensions checkbox;
  Windows 7:
  In Control Panel | Appearance and Personalization | Folder Options' View tab, untick Hide extensions for known file types

Here are three examples:

BrailleServo.h

//
// BrailleServo.h
//

// Call this function once in setup()
void BrailleInit();

// This function activates the six servos to form the passed-in pattern.
void BrailleShow(byte pattern);

BrailleServo.c

//
// BrailleServo.c
//

#include "BrailleServo.h"

// The number of servos
const byte NumServos = 6;

// These are the pins for the six servos
const byte servo[NumServos] = { 3, 4, 6, 7, 9, 10 };

// This initialises the six servos
void BrailleInit() {
   for (byte i=0; i<NumServos; ++i) {
      pinMode(servo[i], OUTPUT);
      // Do what else you need to do with servo[i]
   } // for
} // BrailleInit()

// This is how to use the six servos to form the passed-in pattern
void BrailleShow(byte pattern) {
   // … Complicated code here …
} // BrailleShow(pattern)

Main.ino

//
// Main.ino
//

#include "BrailleServo.h"

void setup() {
   BrailleInit();
   // Other stuff
} // setup()

void loop() {
   BrailleShow('A');
   delay(1000);
   BrailleShow('B');
   delay(1000);
} // loop()

Incidentally, for ideas you may want to check out my answer to a more generic Braille question.


The current direction for digital output pins

When you set a pin to HIGH then that pin will provide 5V.  When you set a pin to LOW then that pin will be set to 0 volts.  Which direction the current flows depends on what is at the other end of the wire.  Current always flows from higher voltage to lower voltage.  If you set a pin to HIGH and the thing it is connected to is at ground then current will flow out of the pin towards ground.  If you set a pin to HIGH but the thing it is connected to is already at 5V then no current flows.  If you set a pin to LOW and the thing it is connected to has some positive voltage then current will flow to the pin.  If you set the pin to HIGH (5V) but the thing it is connected to has more voltage than that (say 10V) then current will flow towards the lower voltage and into the pin, probably damaging the Arduino in the process.


Avrdude Verification Error while flashing Arduino Mega code

I have made Jot's comment into an answer in the hope that it helps someone.

First mismatch in byte 0x0000. [This is] the first byte that goes wrong. That means that not even a single byte passes the verification.

Perhaps the cause is one of these:

A cheap clone with a bad bootloader.
An old bootloader.
A bug, perhaps a bug with the size of the code or ram, for example the code at the border of 32k or 64k.
Maybe the voltage of the Arduino board is too low. Measure it. It must be above 4.5V.
Maybe a bad USB cable.
Wrong USB driver.
Board is too cheap and is missing decoupling capacitors.


Arduino Wall Wart and Relay Board Power Supply

You will need the relay board.  The Arduino output 5V and so you can't use it to directly power the 12V half of the circuit.

If you can split the power from the wall wart so it powers the 12V circuit and the barrel connector on the Arduino then that should work.  If you can, then you will need to ensure that the 0v of the Arduino and the 12v circuit are tied together, otherwise the two halves of the circuit will be using different versions of 0V and you will get interesting results.

If you want to use the setup in your second picture then no you don't need the relay board, but that's only because the whole circuit is 5V.

"How do you split the power?" I hear you say, "do I need any extra hardware?"

That depends, how attached are you to your wall wart's cable?  The way I have done it is to UNPLUG the wall wart, cut the cable in "half", strip a cm of each wire and plug both ends of it into two empty rows on you bread board.  Then use jumper wires to take an additional feed off to the 12V circuit.

CAUTION Ensure you get the polarity of the wires the right way around.  You can test this with a volt metre.  I suggest red electrical tape to mark the +ve wire.

IF YOU ARE NOT CONFIDENT DON'T DO IT!


The L298N is a chip, and the link you provided in the comments is to the chip, not to a full H-bridge module with voltage regulator and other components. We don't have any way to answer your question about your particular set-up without more info.

If the module you have uses a voltage regulator to provide clean 5V to its solid state chips, but does not use it to drive the motors, and it provides enough extra current to drive your Arduino then you might be able to get away with using it to feed your Arduino. If the H-bridge module uses the output of it's 5V regulator to drive the motors then I would not recommend using it to power your Arduino, since as the motor is switched on and off it will cause the voltage from the regulator to bobble. At the very least you would need a reservoir capacitor across the 5V rails near the Arduino to smooth out the 5V supply.


A simple approach would be to use bit 0 of serial data to control "button 1", and bit 1 of serial data to control "button 2".  As follows:

char sd = Serial.read();
byte button1 = sd & 1;
byte button2 = sd & 2; // Or (sd & 2)>>1 if you prefer

With the above code, button 1 is true for odd-digit inputs, and button 2 is true when (sd & 2)>>1 is odd.  For example, input 0 to turn off both buttons, 1 to turn on only button 1, 2 for only button 2, and 3 to turn on both.

You might also wish to button1 or button2 only when the input character represents a digit.  For this, you can say:

char sd = Serial.read();
byte button1, button2;
... ;
if ('0' <= sd && sd <= '9') {
    button1 = sd & 1;
    button2 = (sd & 2)>>1;
}


Uno to Mega and where is the error for the interrupt that isn't delared?

Your brackets are all messed up.  If you pass your code through an autoformatter (such as the one included in the IDE) you end up with this:

// Wiring connections for my encoder:
// Brown : VCC = 5 to 24VDC
// Blue: 0V(Common) = GND
// Shield: GND
// Black: outA = Digital pin 2
// White: outB = Digital pin 3
// Orange: outZ = Digital pin 4 (Index)
// With these outA/outB/outZ connections and the interrupt code below
// clockwise rotation gives positive encoder counts

const int outA = 2;
const int outB = 3;
const int outZ = 4;

volatile long encoder = 0; // declare volatile since modified by interrupt routines
float encoder_save = 0;

void setup() { // set encoder pins
    pinMode(outA, INPUT_PULLUP);
    pinMode(outB, INPUT_PULLUP);
    pinMode(outZ, INPUT_PULLUP);  //Index
// attach interrupts to pins
    attachInterrupt(digitalPinToInterrupt(outA), outAChange, CHANGE);
    attachInterrupt(digitalPinToInterrupt(outB), outBChange, CHANGE);
    attachInterrupt(digitalPinToInterrupt(outZ), outZChange, CHANGE);
// initialize serial
    Serial.begin(57600);
}

void loop() {
    if (encoder_save != encoder) { // only print if new value
        encoder_save = encoder;
    }

// If Index(Z) reads low reset encoder to 0
    if (digitalRead(outZ) == LOW) {
        encoder = 0;
    }
}

{                                                << WHAT
    Serial.println((encoder * 360) / 360);       << IS
}                                                << THIS
}                                                << CODE?

// interrupt routines
void outAChange() {
// when outA changes, outA==outB means negative direction
    encoder += digitalRead(outA) == digitalRead(outB) ? -1 : 1;

    if (encoder < 0) {
        encoder = (encoder + 360);
    }
}

void outBChange() {
// when outB changes, outA==outB means positive direction
    encoder += digitalRead(outA) == digitalRead(outB) ? 1 : -1;

    if (encoder >= 360) {
        encoder = (encoder - 360);
    }
}

As you can see, after the end of your loop() function, you have an extraneous block of code with a bunch of random brackets.

You need to decide where in your program that should actually be and move it there, deleting those extra brackets.


You can just cut off the extra pin. Adafruit probably just had a bunch of 6 pin headers in their stock.


Need assistance with program for POV Project

Your third delay is the issue. It means you have up to 10 ms before you notice the need to turn on the light. Try this:

const byte pin = 13;
volatile bool detected;

void setup() {
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, RISING);
}

void loop() {
  if (detected)
    {
    delay(10);
    digitalWrite(pin, LOW);
    detected = false;
    }

}

void blink() {
  digitalWrite(pin, HIGH);
  detected = true;
}

Now that immediately turns on the LED, so it will always happen at the same time. Then in the main loop you notice it is on, wait 10 ms, and then turn it off.


creating object of another class when initializing an object of a class

You don't need to "create" anything. Just have an object in your class:

class Tone {
    public:
        void dosomething() {
            // Whatever is in here
        }
};

class MyMotor {
    public:
        Tone tone;
        void init() {
            // Nothing much else to do in here now.
        }
};

You then:

MyMotor newmotor1;

And you can access:

newmotor1.tone.dosomething();


How to have some code executed at a certain time of day with a DS3231 RTC?

If you are getting 165:165:165 that indicates usually a problem with your I2C bus. But it might also be a power problem in the RTC.

In any case, check your wiring.

Your processor is simply not properly communicating with the RTC. If the RTC's red light is on then check your wiring and make sure you haven't reversed SDA and SCL.

Also, the DS3231 has and most Arduinos have enough pull-up that you won't need external pull-up resistors in order to communicate directly with the DS3231.

Try plugging it straight into the Arduino - go minimalist and make that work before adding other devices to the I2C bus like a LCD display. Set the clock by code and watch it in the serial monitor.

Once you're sure the RTC is not a problem then you can go from there with the I2C bus. It is certainly possible for other devices on the bus to cause the RTC to be unable to respond correctly. For a short-range I2C bus that includes the DS3231 don't add any external pullups.

The most reliable RTC for Arduino is the DS3231, but if you bought it via the slow boat you might try a voltmeter to verify the battery so it keeps time even when powered down.

And of course, it is only as accurate as you program it to be. When I program my DS3231s, I always add a couple of minutes to the current time to allow for the time to fix forgotten semicolons and such before it gets around to actually programming the device.

One last note: The program will run when you open the serial monitor. So that will be when it sets the time then begins to display it.


If you are doing what is in the first picture then you're doing it wrong.

You have to make sure the led is horizontal, not vertical. The signal is going through the led and not making it into ground. And your ground is in the same lane as your signal.

I think you should learn how breadboards work and then move on from there. Its pretty simple and I think you'll learn it quickly.

For your code part, instead of defining the variables, you could just use int.
 Refer to this as a starter tutorial, https://www.arduino.cc/en/Tutorial/.

This is how your wiring should look like if you followed the tutorial,


You can (just about) use any combination of two of:

Serial to PC,
HC-05
ESP-03

You have, basically, a hardware UART (pins 0/1), and a software UART (any pins of your choice).

Only the hardware UART can be used for communication with the PC, and you can only reliably use one instance of SoftwareSerial.

So, you could:

Use Serial to the PC (0/1) and HC-05 (SoftwareSerial, your choice of pins), or
Use Serial to the PC (0/1) and ESP-03 (SoftwareSerial, your choice of pins), or
Hardware Serial for ESP-03 (0/1) and SoftwareSerial for HC-05 (your choice of pins), or
Hardware Serial for HC-05 (0/1) and SoftwareSerial for ESP-03 (your choice of pins)

If you want anything more complex than that then you need to use a board with more than one hardware Serial port (such as a Mega2560).


Arduino Servo won't move when using classes

It looks this problem may be due to bad order of initializers calls for global variables.

In C++, the order of global variable initialization is unpredictable across different compilation units (i.e. C++ source files, not header files). Initialization order is only respected inside one compilation unit.

In your program, there are several global variables that, if initialized in the wrong order, will fail your program:

Leg topLeft; this is your class instance
servo_t servos[MAX_SERVOS];, int8_t Channel[_Nbr_16timers ]; and uint8_t ServoCount = 0; all defined in Servo.cpp

Calling Servo.attach() requires that the 3 variables above have already been initialized, which you cannot be sure of.

How can you fix that?

By not performing the attach() in Leg constructor but delegating it to some kind of init() method that you can call from setup():

class Leg {
    // Actions that can be triggered from outside
    public:
    void init(int hipPin, int kneePin);
    void up();

    // These should be only available for the leg
    private:
    Servo hip;
    Servo knee;
};

Leg::init(int hipPin, int kneePin) {
    hip.attach(hipPin);
    knee.attach(kneePin);
}

// Testing the leg: move it up
void Leg::up() {
    for(int pos = 0; pos < 180; pos += 1) {
        hip.write(pos);
        delay(15);
    }
}

// Declare the leg
Leg topLeft;

void setup() {
    // Initialize the leg
    topLeft.init(9, 10);
}

// Test the function up()
void loop() {
    topLeft.up();
}


Your picture does not give a clear view of the connections between the Arduino Uno and the LCD module.  However, if we are to follow your description of your connections ...

D7 to pin 2
D6 to pin 3
D5 to pin 4
D4 to pin 5
E to pin 11

... and we assume D7, D6, D5 & D4 are pins on the LCD, then we see that the code is incorrect ...
LiquidCrystal lcd(2, 3, 4, 5, 11, 12);      // put your pin numbers here

... given the LiquidCrystal description here of the syntax of the overloaded (means there are more than one pattern to the passed parameters to the identically named constructor) class ...
Syntax

LiquidCrystal(rs, enable, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d4, d5, d6, d7)
LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)

... instead, try:
LiquidCrystal lcd(?, 11, 5, 4, 3, 2);      // put your pin numbers here

... as you didn't tell us how you connected the RS line I have left that value above as a "?".  So this will not compile until you fill in the missing information.
It should be added, based on what can be seen in the picture, that a connection has been made to the LCD's RS & RW pins and no connection has been made to the LCD's E (enable) pin.  But in all the constructor's overloaded versions, there is always an E (enable) pin.  Please take a closer look at your design to determine if this is a problem.


How do I add or subtract to a pre-determined value without having it default back to the original value?

You wrote:

ftin = feet*100 + INCH;

What is this monster? I am not very familiar with imperial units (and I
wonder why anyone would still want to use them), but I believe a foot is
not 100 inches.
Oh, I see. The monster is a kludge to manage the display in feet &
inches. But note that it is computed at every loop iteration as a
function of the measured distance. I doesn't make sense to apply a
correction to the monster as it is going to be recomputed on the next
iteration. That's why the value “returns” to what it is supposed to be.
As to why the down button changes “100” to “99”, I think it is quite
obvious: 100 minus one is 99. It is not a good idea to do arithmetics
with the monster.
If you want the correction to persist, you have to store it in a global
variable (or static local), and add that variable to the measured
distance at every loop iteration. For example:
// In global scope:
int correction = 0;

// In loop():
dist = ...;
inches = dist * 0.3937008 + correction;  // correction added here
ftin = (inches/12) * 100 + (inches%12);  // only used for display

if (Up_lastButtonState == LOW && Up_buttonState == HIGH) {
    correction++;
    delay(500);
}
if (Dn_lastButtonState == LOW && Dn_buttonState == HIGH) {
    correction--;
    delay(500);
}

Note that the monster is used for display only. No arithmetics are
performed on it, as that would not make any sense.


Change/declare a constant in setup and use it in loop

You are not going to get good answers without showing your code, but maybe this is a good guess of what you want:
why not try something roughly like this (untested and incomplete)?
Adafruit_BMP3XX bmp;
float startPressure;
float difference;

void setup() {
  bmp.begin_I2C();
  startPressure = bmp.readPressure();
}

void loop() {
  difference = startPressure - bmp.readPressure();
}

Or, better:
Adafruit_BMP3XX bmp;

void setup() {
  bmp.begin_I2C();
}

void loop() {
  static const float startPressure = bmp.readPressure();
  static float difference;
  difference = startPressure - bmp.readPressure();
}


ESP8266 feather huzzah wiring for MFRC522

use Wemos table from your link. here is the mapping to esp8266 io pins

RST/Reset   D3 = io 0
SPI SS      D8 = io 15
SPI MOSI    D7 = io 13
SPI MISO    D6 = io 12
SPI SCK     D5 = io 14

If you want, you can use any pin for SS and reset. See the examples.

#define SS_PIN 4
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);


Why does per-led current consumption diminishes when more leds are on?

If using a constant voltage source it is advisable to use current limiting resistors in series with LEDs.

If these LEDs are different colors that may explain the different current readings.

Or, if all LEDs are of the same color and you are powering the project from a source with internal resistance (a battery), the more current you draw the lower the supply voltage.  This may show up as a reduced incremental current increase.

Or, if using a poor power source or operating at the current capacity of the power supply - again - this may show up as a reduced incremental current increase.

Note that different generations of LEDs operate at slightly different voltages.  But, in general, RED, GREEN & BLUE LEDs of the same generation operate at slightly increasing voltages respectively.  Details can be found here in this wikipedia.com page:

  Typically, the forward voltage of an LED is between 1.8 and 3.3 volts.
  It varies by the color of the LED. A red LED typically drops 1.8
  volts, but since both voltage drop and light frequency increase with
  band gap, a blue LED may drop from 3 to 3.3 volts.

Use the LED current (Iled) and voltage (Vled) specifications to determine the proper resistor value for a given supply voltage (Vbatt).

The following equation from this article should prove useful for this calculation:


Changing the duty cycle does not change the frequency of the PWM signal.
The tb6000 needs a pulse to trigger a step of the motor. If the frequency does not change the pulses per second do not change too and thus the speed is constant.
If you control just one motor the method of using delays to control the frequency works.
But in the case of two motors with different speed you need counter variables to immetate two frequencies (speeds) you need to control each speed of the motors.
First you caculate the ration of the speeds (you said y=1 and x=n steps. Then, the ratio is n:1, i.e the X Motor is faster then the Y Motor by factor n).
The following is just an incomplete example to explain my idea.
int cntX = 0;
int cntY = 0;

// I don't know you value n
// Let's say n=5
int ratioX = 5;
int ratioY = 1;

// One step per second at max speeed
// choose whatever fits your needs
int delayForMaxSpeed = 1000;

const int stepPinX = 5;
const int dirPinX = 2;
const int stepPinY = 6;
const int dirPinY = 3;
const int enPin = 8;

void setup()
{

  pinMode(stepPinX,OUTPUT);
  pinMode(dirPinX,OUTPUT);
  pinMode( stepPinY, OUTPUT );
  pinMode( dirPinY, OUTPUT );

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

}

void loop()
{
  // Enables the motor to move in a particular direction
  digitalWrite( dirPin, HIGH );

  countx++;
  county++;

  if ( countX >= ratioX )
  {
     countX = 0;
     digitalWrite( stepPinX, HIGH );
  }

  if ( countY >= ratioY )
  {
    countY = 0;
    digitalWrite( stepPinY, HIGH );
  }

  delayMicroseconds( 500 );

  digitalWrite( stepPinX, LOW );
  digitalWrite( stepPinY, LOW );

  delay( delayForMaxSpeed );
}


Try this instead.

#include “TimerOne.h”
bool val=0;
void setup()
{
    pinMode(13, OUTPUT);
    Timer1.initialize(500000); // initialize timer1, and set a 1/2 second period
    Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
}

void callback()
{
    val=!val;
}

void loop()
{
    digitalWrite(13,val);
}