my arduino talks to another device that uses serial communication

What other device? You haven't said which Arduino, but Arduinos are generally "devices" which talk to a "controller" (host) which is generally a PC / Mac.

The host has the job of supplying power (via the USB cable) to the device. Thus your Arduino will be powered by the device it is plugged into.

Disregarding this issue for the moment, you can supply regulated 5V power directly to the 5V pin on the Arduino. On the Uno (and many others) this is labelled "5V".

The power jack is to supply 7V to 12V (eg. from a wall-wart) which then goes through the voltage regulator on the Arduino (depending on the model in question).

There is quite a discussion about this on https://www.arduino.cc/en/main/arduinoBoardUno. On that it mentions:

  Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

This is true. Directly supplying 5V to the 5V pin bypasses the regulator and also bypasses the reverse-voltage protection diode. However it is possible to do it.

  What about the Vin pin?

For a Uno you can see from the reference schematic what happens:

The power jack (on the left) goes into the reverse-voltage protection diode (D1). The other side of that becomes Vin. Then it goes into the 5V voltage regulator (U1). The other side of that becomes the 5V line.

Thus to supply 5V you can provide 5V power to the pin marked 5V. It is probably not ideal, because the voltage regulator may not be designed to have power applied on its "output" side.

There is more circuitry to decide whether to use the USB power or the Vin power (not shown above).


Why was the Atmega16U2 used on the Arduino UNO as a USB to Serial converter?

First reason I'd guess is price:

FT232 on octopart: USD2.65 ~ 3
Atmega16U2 on octopart: USD2.12 ~ 2.2

They can probably get much better deals considering that the Atmega328 is also from Atmel (now Microchip).

About the programming:

There are some projects which make the Atmega16U2 into a MIDI device over USB or HID, for example some repos: 1, 2, 3. I've used the second one I think, and it works fine.

You can program it with an ISP/ICSP programmer such as Atmel ICE(below) or Arduino ISP.

Use the ISP pins by the Atmega16U2:


As jsotola mentioned in his comment, pin 1 and pin 14 on the display are connected to each other (GND). You can connect pin 14 to an input pin with enabled INPUT_PULLUP. If no display is connected, this pin will be pulled high by the pullup, thus the pin will read high. If the display is connected, the pin will read low.


Is there any way to check with Arduino UNO if a sensor is connected and ready to be read?

Basically pull-up resistor pulls up the line, when nobody/nothing is doing otherwise (for example wire unconnected, or connected to INPUT, or to I2C bus, which is not doing something right now ...). If some device (or Arduino) sets the wire to LOW (0V, GND, ground), the it overrules the resistor and the wire is LOW.

So the value of the resistor must be high enought to anable any attached device to draw the wire LOW. So if you know, how much of current can a device sink and what is considered LOW value on input, then you can compute the minimal value of the resistor from Ohm law (and the Vcc, where the resistor is connected). If you do not want calculate anything, just put 10KOhm between the wire and Vcc and it would probabelly work just fine.

About detecting sensor - you have to know, what sensor and where is supposed to be attached (as you construct the robot). So you just send any command to the sensor (probabelly to read a value) and see, if you get answer and the answer make a sense (eg. temperature is like 0-100 Celcius, or so). If it works OK, then the sensor is connected and can be used, otherwise you should stop the robot, light big red light and wait for user to repair what is broken. Thing also about the type of sensor, if it needs some time to "boot up" and it it needs some time to "seatle the value and answer" to provide that time before testing (like with delay()).

The pull-up resistors fits there in the way, that they are connected to Arduino, so if there is no connection to sensor, then the unconnected pin is not "floating" (and possibly return any random or not random value), but is weakly drawn up ti HIGH, so if the connetor is broken/unattached, then all reads are just plain HIGH, no communication from sensor (or any noise to be messing with the detection). So you can detect "no answer" status and after a while (when sensor really, really should answer, but did not) flash that big red light.


program evaluating if clause incorrectly

Do not put a ; after an if:

if(flag != 0xaa);

is the same as

if(flag != 0xaa)
{
}

Meaning that the code after the if statement is always executed.


A band pass filter simply means that it a filter between a certain interval of frequencies thus it can be made from a high pass filter and a low pass filter

e.g. this fact is mentioned here http://www.electronics-tutorials.ws/filter/filter_4.html

as well as lots of other web pages which a search by you can find.
So yes a band pass filter can be implemented on arduino if you can implement the corresponding high pass and low pass filter too.


Atmega328 output pins are rated at 40 mA absolute-maximum current, and the 328's total current through Vcc and ground pins is 200 mA absolute max.  Eg, see table 29.1 in the Atmega328 specs.

Although some sources rate a high-speed 716 coreless dc motor at 40 mA, other sources rate it at 100 mA.  In either case, it exceeds normal I/O pin capability. You should use FETs or other drivers between Arduino output pins and the motors rather than trying to drive the motors directly from digital output pins.

Edit: Regarding the comment, “But most projects i've seen don't use any drivers, Why so ?” I replied:

  Perhaps they are using slightly higher voltage to the Pro Mini, eg 3.7 V up to 5 V, which after accounting for voltage drop in the i/o pin circuits may deliver enough voltage to the motors. Note that a driverless circuit ie direct drive from the i/o pins operates the 328 out of its safe operating area (SOA), but it may be close enough to the safe area to usually work.

For example, some of the 716-based quadcopter pages I looked at say they used 4.2 V LiPo batteries.  Also note, 716 seems to be a fairly generic motor designation; it refers to the motor's 7 mm diameter and 16 mm length.  As a generic designation it has been used for several different motors, some of which produce less power.  For example, in thread #1710948 on rcgroups.com, people refer to different RPMs, less lift, etc. for various motors, and the importance of shaving grams off of the copter's weight to allow it to fly.

Another item that matters when drawing high current from an Atmega328 is which ports are used; and for some devices, it matters whether drive is high-side or low-side, ie whether current is sourced or sunk.  The Atmega328 spec sheet (Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf) says “Each output buffer has symmetrical drive characteristics with both high sink and source capability”, but for several kinds of drivers less voltage is lost with low-side drive than with high-side.  Ie, you could try connecting the motor's V+ lead to Vcc and its V- lead to the i/o pin, and inverting the on-off logic in the sketch. (I don't know if this will make any difference at all in how well things work.)

Regarding which ports are used, the footnotes to Table 30-1, “Common DC characteristics”, spell out various combinations of ports where total current draw must not exceed a limit (100 mA in some cases, 150 mA in others).  On the Uno and Pro-Mini, digital outputs marked 10 through 13 (as used for motor control in the question's sketch) are port B Atmega pins, with a footnoted total-current limit for the group.  If you move two of the motor drives to outputs marked 2...4 or D2...D4, then a different total-current limit will apply.  (Again, I don't know if this will make any difference at all in how well things work.)  Refer to Table 30-1 footnotes for details.

As noted in Gerben's comment, having flyback-diodes for the motor circuits is a good idea. This consists of placing power diodes across the motors, cathode to V+, anode to V-, to prevent energy stored in the motor's inductance from producing extreme i/o pin voltages each time the motor is turned off.

Edit 2: Regarding “which diode, FET to use and where [to] learn about them”, electronics-tutorials.ws is an accurate and helpful presentation about FET digital circuits.  In particular, see the section called “An example of using the MOSFET as a switch”.

Which FETs to consider depends in part on your electronic-circuits fabrication skills.  Note that surface mount devices (SMD parts) usually weigh less than other versions of parts, which is important for a lightweight quadcopter.  However, some people find SMD parts difficult to work with.  In my opinion, the main difficulty is holding parts in their proper places while soldering them, due to small size.  (Eg, a SOT-23 SMD transistor package is on the order of 3mm x 2mm x 1mm, and a diode may be half as big.)  If you have good soldering skills and a way to hold parts in place while soldering, you should be ok, either using a printed circuit board or air-wiring parts using wire-wrap wire (ie, 30 AWG wire, about 0.25mm diameter).

Some typical logic-level-input SMD FETs are shown in mouser.com's online catalog.  Note that in that list, RDS_on decreases a bunch as unit price increases slightly.  For example, the FDN359BN would have under 0.1 ohm resistance when operated with Vcc = 3.7 V and currents < 100 mA.  Voltage drop running a 40 mA motor should be about 4 millivolts.

Some typical SMD Schottky diodes also are shown in mouser.com's online catalog.  I think even the cheapest of these would work ok.  Of course you'll need to adapt all these suggestions to your own skills, sources of parts supply, and budget.


.parseInt() reads incoming text up until either it times out or until it reads something that isn't a number.

You are sending a number, and most likely a line-ending. If that line-ending is a simple \n then that will trigger the "end of number" and will be discarded and the number returned.  However, if you are sending \r\n (i.e., CRLF) then you effectively have two line endings there:

1\r\n

Parsed as:

1\r => return 1
\n => return 0

Relying on the (poorly written) Arduino stream parsing routines is not good. Not only are they blocking, but often they just don't work right.

Instead you should be reading the serial properly, taking account of line endings, and then converting the string you have read into a number using the likes of atoi().

Tutorial on reading serial:

https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/


Attempt stacking 'CAN-BUS' and 'USB Host' Shields on Mega 2560

I think that there is an hardware bug on the USB Master shield:
IC3, the 3-state buffer which converts MISO to 5V, is always active...
The enable pin of this 74LVC1G125 (pin 1) should be connected to the pin ss_3V3.
Then you can stack this shield with another one.


Powering USB cable that powers Arduino with regulated 5V

I solved this problem by using a laptop instead. It is immune to these power fluctuations


How to use the Osepp proximity module with arduino uno

How should I connect it to the Arduino

Refer to the schematic in the page you link to. That shows you which pin is which.  It's I2C, so there's just 2 data pins, power, and ground.

  and what library do I use?

The Osepp board is a GP2Y0D805Z0F connected to a PCA9534 IO expander. There is a library here.


Usually the SPI Master clocks data out while the Slave clocks data back in. So if you were sending and receiving 8 bits per transaction you can clock out 8 bits and at the same time clock in 8 bits for a total of 8 clocks.  This is described in this Wikipedia paragraph. That said, often the first 8 clocks are used to transmit a command and an additional 8 clocks are used to retrieve the result.

If you looped MOSI to MISO you would clock in what you clocked out. You would complete the entire transaction in 8 clocks. At a low level I'm thinking this does not matter. But at a higher level the software would have to be re-written to accommodate this weirdness.


Store button presses in an array and sequince it with the LEDs

Start by writing a sketch that debounces your buttons to get an accurate count of each button press. Install the Bounce2 Library available in the IDE.
Use a byte array to store the sequence of button presses (record the pin numbers).
Once the pre-set limit (sequence length) is reached, play back the sequence.
Playing back the sequence could look something like this:
const byte ledPin1 = 4;
const byte ledPin2 = 5;
const byte sequenceLength = 4;
byte sequence[sequenceLength] = {4, 5, 5, 4};

void setup(){

  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin1, LOW);
  digitalWrite(ledPin2, LOW);

  for(byte i = 0; i < sequenceLength; i++){
    if(sequence[i] == ledPin1){
      digitalWrite(ledPin1, HIGH);
      digitalWrite(ledPin2, LOW);
    }
    else{
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, HIGH);
    }
    delay(500);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    delay(500);
  }

}

void loop(){}

EDIT: Adding a couple of buttons using the Bounce2 library is a trivial task.
// Arduino IDE 1.8.9
// Sketch uses 1696 bytes (5%) of program storage space.
// Global variables use 30 bytes (1%) of dynamic memory,
#include <Bounce2.h>
const byte ledPin1 = 4;
const byte ledPin2 = 5;
const byte buttonPin1 = 8;
const byte buttonPin2 = 9;
const byte sequenceLength = 4;
byte sequence[sequenceLength];
byte counter = 0;

Bounce button1 = Bounce();
Bounce button2 = Bounce();

void setup(){

  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin1, LOW);
  digitalWrite(ledPin2, LOW);

  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);

  button1.attach(buttonPin1);
  button1.interval(50);
  button2.attach(buttonPin2);
  button2.interval(50);

}

void loop(){

  if(button1.update()){
    if(button1.read() == 0){
      addToSequence(ledPin1);
    }
  }

  if(button2.update()){
    if(button2.read() == 0){
      addToSequence(ledPin2);
    }
  }

  if(counter == sequenceLength){
    for(byte i = 0; i < sequenceLength; i++){
      if(sequence[i] == ledPin1){
        digitalWrite(ledPin1, HIGH);
        digitalWrite(ledPin2, LOW);
      }
      else{
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, HIGH);
      }
      delay(500);
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      delay(500);
    }
    counter = 0;
  }
}

void addToSequence(byte pinNumber){
  sequence[counter] = pinNumber;
  counter++;
}


The problem that I see in the photo is that the pads from the PCB are pulled off and attached to the antenna. So now there is nothing to solder the antenna back to.
While it's possible to rework this with some solder rework tools, I suspect you don't have those.  There is really not much else you can do but replace the Nano with a new one.  You should still be able to use this one for an application that doesn't need WiFi.
It looks like the two active leads (the two in the upper right-hand side of the green module may be those) are still intact.  If you have a small tip soldering iron and a steady hand you may be able to put a tiny drop of solder on both of them and then resolder the antenna to them.  You could support the antenna with some silicone caulk or other non-conductive adhesive after you get it attached.
Keep in mind, that this is tricky to solder by hand but there is little to lose since that part of the module is not non-functional anyway.


I just bought a TFT screen is it still possible to use the serial port 1 and 0?

Yes, you can use those pins. Just because there are physical pins on the shield doesn't mean they are actually used. If nothing is written next to them then yes you can use them.

Be warned though that those pins are used for communication with your PC - and that includes uploading sketches - so you may experience problems doing things like that while your Mega is connected to those pins.


Is the SIM900 3G? Or is the SIM900A able to connect to 3G?

First of all if you are in USA you cannot use SIM 900A since it supports only Dual frequency bands.(900,1800 MHz)it supports only Asian region countries.

According to Wikipedia, PTel Mobile supports only GSM 850/1900 frequencies.
so SIM 900 supports( 850,900,1800,1900 MHz ) you must use SIM900

Considering about the speed you cannot obtain 3g, 4g speed since GSM Shield(SIM900) provides maximum of GPRS class 10: max. 85.6 kbps (downlink) so,

It will able to connect but cannot get such speed in 3g and 4g.


The scope of your question is too wide for a simple answer so let us constrain it to slow signals (audio frequencies or less) over short cables (not more than several meters) in a electrically clean environment (such as found in most homes).
That said, it is likely most looking for similar solutions reading your question will have different specific requirements.  So to make this question and answer useful to others let us consider the most generic, economical and Arduino based solution.

Most cables worth automatically testing will have far more individual connections than common Arduino boards, such as the Arduino Uno, have GPIO pins.  Consider using a GPIO expander or multiple Arduinos which communicate with each other to coordinate efforts.
When testing a cable that will be used for low frequencies, short distance and low immunity to noise it is likely the only faults that are of concern are OPENS and SHORTS.
As this design uses GPIO pins we have the following options at any given GPIO pin: Drive High, Drive Low and Input With Pull Ups.
Build a cable test rig where one end (the near end) of the cable under test is connected to GPIO pins designated as the driver side and the other end of the cable under test (the far end) is connected to GPIO pins designated as the sensing side.
For a SHORTS and OPENS test set all the sensing  and driving GPIO pins to Input With Pull Ups.  Verify that all sensing GPIO pins report a 1.  Next change one and only one of the driver GPIO pins to an output and send a 0.  Record that state of all sensing GPIO pins.  Return the driver GPIO pin to Input with NO PULL UPS and repeat these steps for the next GPIO driver pin.
If this is a STRAIGHT THROUGH cable only 1 sensing GPIO pin should report a 0 in each testing pattern recorded.  If more than 1 sensing GPIO pin reports a 0 then there is a short between the 0 reporting pins.  If none of the GPIO pins reports a 0 then there is an open for that GPIO pin.
Use the same test for cables containing intentional SHORTS (perhaps multiple ground pins are shorted together) expecting to see the associated GPIO pins to all change to 0 at the same time.
For even more complex cables containing loop backs at both ends consider only the "GPIO pin set to an output sending 0" as the driver and record the state of ALL OTHER GPIO pins as they are now all possible outputs.


Weird characters in Serial Monitor and not functioning ESP8266 ESP-12e

Check what baud rate is serial window displaying. It should be the same as defined in your code.


My RTC is returning a sporadic date/time

The RTC library does not check for communications success. In particular, here:

DateTime RTC_DS1307::now() {
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.send((byte) 0);
  Wire.endTransmission();

  Wire.requestFrom(DS1307_ADDRESS, 7);
  uint8_t ss = bcd2bin(Wire.read() & 0x7F);
  uint8_t mm = bcd2bin(Wire.read());
  uint8_t hh = bcd2bin(Wire.read());
  Wire.read();
  uint8_t d = bcd2bin(Wire.read());
  uint8_t m = bcd2bin(Wire.read());
  uint16_t y = bcd2bin(Wire.read()) + 2000;

  return DateTime (y, m, d, hh, mm, ss);
}

There should be a check for a zero returned from Wire.endTransmission(). It isn't otherwise possible to detect if the data is invalid (if we got the endTransmission OK) however generally speaking I2C will return 0xFF if the transmission has ceased.

The code in the library for bcd2bin is this:

static uint8_t bcd2bin (uint8_t val) { return val - 6 * (val >> 4); }

You can see that if passed 0xFF (255) it will return:

   255 - (6 * 15) = 165

Thus if any of the minutes, hours, day or month (which are not further affected in the code above) are 165 (or if the year is 2165) you can assume the whole date/time is bad.


Using Rx and Tx pins(0 and 1) on Arduino Uno for GSM

You have a choice.

Always:

GND => GND
+5V => +5V

Then, either:

TX => RX (0)
RX => TX (1)

and use the hardware UART "Serial", but that then means that uploading new code to your Arduino becomes an arduous task since the usage pins 0 and 1 will interfere with that.  So the other option:

TX => Any pin
RX => Any pin

And then use SoftwareSerial to set up a secondary "bit banged" serial port on the two pins you choose.


Thanks for @Majenko.
I solved problem by upgrade firmware to 1137B15SIM900M64_ST.


How to send data to sim900 only once in loop()

You can use a boolean variable to decide if you are going to execute the send command. You can set the variable to true in the setup and to false after the command is executed.

If you introduce the send call inside an if (your boolean variable == true), it will only be executed in one loop iteration.

You can execute it again anytime you like setting the variable to true at any moment.


Creating a timer using a Real Time Clock with start and stop times

I had a similar problem when i tried to control some heating source here at home.This was how I made my steps to get it working.
First I will assume you are using the library time.h and DS1307RTC.h (check here for info: https://www.pjrc.com/teensy/td_libs_Time.html).

Assuming that you will need 3 variables of the type tmElements_t.
tm will store your current time( the one you get from DS1307). The other two are auxiliary for defining time you start and time you stop the pump.
In similar way, you will need 3 variables of type time_t for the same reasons.
time_t variables store a the timestamps since 01/01/1970 (Unix epoch) which are easier to work with but tmElements structures are more human friendly.

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now, t_hour_start, t_hour_end;

Now in your loop you need to get the current time from rtc:

time_t now = RTC.get();

after, use the breaktime funtion to convert the timestamp value to tmElements struture:

breakTime(now, tm);

Next step is to copy contents of tm to the other auxiliary structures, use the memcpy function:

memcpy(&tm_hour_start, &tm, sizeof(tm));
memcpy(&tm_hour_end, &tm, sizeof(tm));

after, change the the auxiliaries vars to meet your correct schedule of start and stop (are seconds important? if so, do similar way):

tm_hour_start.Hour = startHour;
tm_hour_start.Minute = startMinute;
tm_hour_start.Second = 0;
tm_hour_end.Hour = endHour;
tm_hour_end.Minute = endMinute;
tm_hour_end.Second = 0;

Ok, we have the more human friendly start and end structures, lets get the timestamps from them. To do soo we use the makeTime function that converts tmElements_t structures to time_t:

t_hour_start = makeTime(tm_hour_start);
t_hour_end = makeTime(tm_hour_end);

All you need to do now, is check if your current timestamp (now) is between this newly created timestamps:

if ((t_hour_start <= now) && (now <= t_hour_end)){
   //do something is soo...
}else{
   // do something if not...
}

Extra tip: In case your stop hour goes past midnight, add one more day to the timestamp:

if (startHour > endHour) //past midnight correction
   t_hour_end = t_hour_end + SECS_PER_DAY;

clean code:

#include <time.h>
#include <DS1307RTC.h>
#include <stdio.h>
// other includes etc...

byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now, t_hour_start, t_hour_end;

// setup function and other needed things...

void loop(){
  //get current timestamp
  time_t now = RTC.get();
  // make current date and time structure
  breakTime(now, tm);
  // make auxiliary structures to be more human editable and friendly
  memcpy(&tm_hour_start, &tm, sizeof(tm));
  memcpy(&tm_hour_end, &tm, sizeof(tm));
  // change auxiliary structures to meet your start and end schedule
  tm_hour_start.Hour = startHour;
  tm_hour_start.Minute = startMinute;
  tm_hour_start.Second = 0;
  tm_hour_end.Hour = endHour;
  tm_hour_end.Minute = endMinute;
  tm_hour_end.Second = 0;
  // reverse process to get timestamps
  t_hour_start = makeTime(tm_hour_start);
  t_hour_end = makeTime(tm_hour_end);
  // check if end time is past midnight and correct if needed
  if (startHour > endHour) //past midnight correction
       t_hour_end = t_hour_end + SECS_PER_DAY;

  //final part
  if ((t_hour_start <= now) && (now <= t_hour_end)){
          //do something is soo...
  }else{
          // do something if not...
  }

}

EDIT: to correct the thing about midnight checks spotted in comments. New code:

#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>
#include <stdio.h>
// other includes etc...

byte startHour = 8;
byte startMinute = 15;
byte endHour = 14;
byte endMinute = 20;

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now_, t_hour_start, t_hour_end;
boolean update_tm = 1;

// setup function and other needed things...
void setup(){};

void loop(){
  //get current timestamp
  time_t now_ = RTC.get();
  // make current date and time structure
  breakTime(now_, tm);
  // make auxiliary structures to be more human editable and friendly
  if(update_tm){
    memcpy(&tm_hour_start, &tm, sizeof(tm));
    memcpy(&tm_hour_end, &tm, sizeof(tm));
    // change auxiliary structures to meet your start and end schedule
    tm_hour_start.Hour = startHour;
    tm_hour_start.Minute = startMinute;
    tm_hour_start.Second = 0;
    tm_hour_end.Hour = endHour;
    tm_hour_end.Minute = endMinute;
    tm_hour_end.Second = 0;
    // reverse process to get timestamps
    t_hour_start = makeTime(tm_hour_start);
    t_hour_end = makeTime(tm_hour_end);

    // check if end time is past midnight and correct if needed
    if (startHour > endHour) //past midnight correction
      t_hour_end = t_hour_end + SECS_PER_DAY;
  }
  //final part
  if ((t_hour_start <= now_) && (now_ <= t_hour_end)){
    /* if we got a valid schedule, don't change the tm_hour structures and the
    respective t_hour_start and t_hour_end timestamps. They should be updated
    after exiting the valid schedule */
    if(update_tm)
      update_tm = 0;

    //do something is soo...
  }else{
    if(update_tm == 0)
      update_tm = 1;
    // do something if not...
  }

}


4 IR sensors on Arduino pro micro. 2 are working other aren't

Pin 5 is not analog pins.

On the pro-micro only pins A0-5 and D4, D6, D8-10, D12 can convert an analog voltage to a value.

Just use the A0-5 pins instead, as that will work on any Arduino.


Understanding flow of current with pull-up and pull-down circuits

It's very hard to read your circuit, because there are wires everywhere. However this is effectively what a switch and a pull-up resistor looks like:

Due to the pull-up, pin 8 on the Arduino (which the switch is connected to) is normally pulled-up to 5V if the switch is open.

When you close the switch pin 8 becomes 0V, thus your meter reads 0V.

On the other hand, with a pull-down resistor, the circuit looks like this:

Now pin 8 is normally zero volts with the switch open, and when closed pin 8 is connected to 5V to pin 8 becomes 5V.

See my tutorial on switches for more details.

  What happens with the flow of current and the resistor to make one example read high and the other low.

Imagine a door with a spring on it to close it. The spring is like a pull-up (or pull-down) resistor (depending on whether you are trying to keep the door closed or open).

The spring gently pulls the door shut. However if you barge out of it with a handful of pizzas in your hand your override the spring. In the absence of the spring the door would just flap in the breeze, sometimes opening and sometimes closing.

The point is, a person is strong enough to force the door open, despite the spring. Similarly if you close the switch you override the pull-up (or pull-down) resistor.

  Where does the 5V go when the switch is closed.

It flows through the resistor to ground (or 5V depending on which one you are talking about).

  When the switch is open in the pull up example - is voltage going through the resistor? From what I'm reading online, in the pull up case voltage isn't traveling through the resistor until the button is pressed.

Voltage doesn't "go through" a resistor, current does.

With the switch open, effectively a tiny amount of current goes through the resistor to pin 8. It is a "high impedance" input which means it puts a very small load on the input. Thus there is a very small voltage drop over the 10k resistor, and almost the full 5V is presented to the input pin for reading.

To work out the exact amount, we can look at the datasheet which says that the maximum leakage current through an I/O pin at 5V is 1 µA. Now using Ohm's Law we can find the voltage drop over the 10k resistor:

V = I * R
V = 0.000001 * 10000
V = 0.01 V

Thus with 5V at the 5V pin of the processor, and a (maximum of) 1 µA consumed at pin 8, it will therefore have 4.99 V at the pin, which therefore reads HIGH.

With the switch closed, then we use Ohm's Law to calculate the flow through the resistor:

I = V / R
I = 5 / 10000
I = 0.0005 A

Thus 0.5 mA flows through the resistor with the switch closed. This is not enough to damage the resistor, or make a significant load on the 5V line.

I think you are getting confused (as I did when I was young) that a big resistance (like 10k) must "resist" a lot of voltage. It is easy to think that after going through 10k resistance there can't be much "voltage" left.

The fact is, though, that the voltage on the other end of a resistor is proportional to not only the resistance (R) but also the current (I). This is Ohms's Law (V = I * R)

So, if the current is very small (as is the case with an input pin) then the voltage drop over a resistor - even a large one - is very small.

So, the idea of a pull-up resistor is, that with no external influences (like a switch) then after passing through 10k resistance, there is still 5V at the other side.

Let me issue you with a challenge. Find a voltage source (eg. a battery). Measure it with your multimeter. Let's say you have a 5V source which is the Arduino 5V pin. Now get a 10k resistor. Put it in series with the 5V source. Now measure it on the other side of the resistor. Depending on the quality of the meter (and thus how much current it takes to measure a voltage) you will get very close to the same voltage reading. In my case I had 5V on one side of the resistor, and 4.99V on the other side. This is exactly what my calculations above predicted.


Is using malloc() and free() a really bad idea on Arduino?

My general rule for embedded systems is to only malloc() large buffers and only once, at the start of the program, e.g., in setup(). The trouble comes when you allocate and de-allocate memory. Over a long run session, memory becomes fragmented and eventually an allocation fails due to lack of a sufficiently large free area, even though the total free memory is more than adequate for the request.

(Historical perspective, skip if not interested): Depending on the loader implementation, the only advantage of run-time allocation vs. compile-time allocation (intialized globals) is the size of the hex file. When embedded systems were built with off the shelf computers having all volatile memory, the program was often uploaded to the embedded system from a network or an instrumentation computer and the upload time was sometimes an issue. Leaving out buffers full of zeros from the image could shorten the time considerably.)

If I need dynamic memory allocation in an embedded system, I generally malloc(), or preferably, statically allocate, a large pool and divide it into fixed-size buffers (or one pool each of small and large buffers, respectively) and do my own allocation/de-allocation from that pool. Then every request for any amount of memory up to the fixed buffer size is honored with one of those buffers. The calling function doesn't need to know whether it's larger than requested, and by avoiding splitting and re-combining blocks we solve fragmentation. Of course memory leaks can still occur if the program has allocate/de-allocate bugs.


How can i connect 01 ESP8266 to a shift register?

While I do believe you could use GPIO2, TX, and RX for your connections, I don't think the clock is explicitly exposed on the ESP-01. That means your code would have to "emulate" a clock via GPIO2 (most likely) with that pin going to your shift register's clock pin. That said, it's really hackish and I'd recommend other ESP dev board that has a pin for the onboard clock.


I've written a code for NRF24L01+ based on the datasheet.run them on your arduino and test them.CE pin is PIN7 in arduino and CSN is PIN8 in arduino.
NRF_monitorRegisters() shows all Registers of NRF.It's nice to test your NRF
maybe it helps:

for transmitter:

#include <SPI.h>

int sending = 1;
int data = 7;

void IRQ() {
  Serial.println("STATUS register from IRQ ISR :  ");
  digitalWrite(8, 0);
  SPI.transfer(0x07);
  delay(10);
  Serial.println(SPI.transfer(0xff), BIN);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x08);
  delay(10);
  Serial.println(SPI.transfer(0xff), BIN);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);
}

void NRF_transmitterBegin() {

  //reading
  /*digitalWrite(8, 0);
    SPI.transfer(0x00);
    delay(10);
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);*/

  pinMode(7, OUTPUT);  //CE
  pinMode(8, OUTPUT);  //CSN
  delay(100);
  digitalWrite(8, 1);
  digitalWrite(7, 0);

  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV4);
  SPI.begin();
  delay(1000);

  digitalWrite(8, 0);   //flush TX_FIFO
  SPI.transfer(0xe1);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);   //flush RX_FIFO
  SPI.transfer(0xe2);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xf0);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x00 + 0x20);
  delay(10);
  SPI.transfer(0x0e);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  /*digitalWrite(8, 0);
    SPI.transfer(0x11 + 0x20);
    delay(10);
    SPI.transfer(0x3f);
    delay(10);
    digitalWrite(8, 1);*/

  //Down for DYNPL
  digitalWrite(8, 0);
  SPI.transfer(0x1c + 0x20);
  delay(10);
  SPI.transfer(0x01);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x1d + 0x20);
  delay(10);
  SPI.transfer(0x04);
  delay(10);
  digitalWrite(8, 1);
  //Up for DYNPL

  digitalWrite(8, 0);
  SPI.transfer(0x01 + 0x20);
  delay(10);
  SPI.transfer(0x3f);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x02 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x03 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x04 + 0x20);
  delay(10);
  SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x05 + 0x20);
  delay(10);
  SPI.transfer(0x4c);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x06 + 0x20);
  delay(10);
  SPI.transfer(0x06);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x0a + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x10 + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

  attachInterrupt(digitalPinToInterrupt(2), IRQ, FALLING);
  delay(10);

}

void NRF_transmit(int whatIsData , float data , float hum) {    //hum is used just for temp&humidity
  /*
     byte 0 says what is our data:  1 -> data and humidity    2 -> movement   3 -> gas

     1(float) :   byte 1 -> integer part of temp  byte 2 -> fractional part of temp   byte 3 -> integer part of humidity    byte 4 -> fractional part of humidity    byte 5 -> %battery
     2(binary) :  byte 1 -> %battery
     3(float) :   byte 1 -> integer part of gas   byte 2 -> fractional part of gas    byte 3 -> %battery

     %battery feature is in progress ...
  */

  int byte0 = 0 , byte1 = 0 , byte2 = 0 , byte3 = 0 , byte4 = 0 , byte5 = 0;
  float buf = 0;

  byte0 = whatIsData;

  switch (whatIsData) {
    case 1: {

        byte1 = data;
        buf = data - byte1;
        byte2 = buf * 10;

        byte3 = hum;
        buf = hum - byte3;
        byte4 = buf * 10;

        break;
      }
    case 2: {

        break;
      }
    case 3: {

        byte1 = data;
        buf = data - byte1;
        byte2 = buf * 10;

        break;
      }
    default: {
        break;
      }
  }

  digitalWrite(8, 0);
  SPI.transfer(0xe1);   //flush TX_FIFO empty
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0xa0);   //write on TX_FIFO
  delay(10);
  SPI.transfer(byte0);
  delay(10);
  SPI.transfer(byte1);
  delay(10);
  SPI.transfer(byte2);
  delay(10);
  SPI.transfer(byte3);
  delay(10);
  SPI.transfer(byte4);
  delay(10);
  SPI.transfer(byte5);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(7, 1);   //CE High
  delay(1);
  digitalWrite(7, 0);   //CE Low

}

void NRF_monitorRegisters() {

  for (int i = 0; i < 30; i++) {
    digitalWrite(8, 0);
    SPI.transfer(i);
    delay(10);
    Serial.print(i , HEX);
    Serial.print(" -> ");
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);
  }
  Serial.println("");

}

void setup() {

  Serial.begin(115200);

  NRF_transmitterBegin();
  NRF_monitorRegisters();

}

void loop() {

  NRF_transmit(3 , 15.1 , 0);

  delay(1000);
}

for receiver :

#include <SPI.h>

long int lastTime = 0;

void IRQ() {

  int whatIsData = 0;
  int byte1 = 0 , byte2 = 0 , byte3 = 0 , byte4 = 0 , byte5 = 0;
  float data = 0 , hum = 0 , buf = 0;

  /*Serial.println("STATUS register from IRQ ISR :  ");
    digitalWrite(8, 0);
    SPI.transfer(0x07);
    delay(10);
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);*/

  digitalWrite(8, 0);
  SPI.transfer(0x61);
  delay(10);
  whatIsData = SPI.transfer(0xff);
  delay(10);
  byte1 = SPI.transfer(0xff);
  delay(10);
  byte2 = SPI.transfer(0xff);
  delay(10);
  byte3 = SPI.transfer(0xff);
  delay(10);
  byte4 = SPI.transfer(0xff);
  delay(10);
  byte5 = SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);   //flush RX_FIFO
  SPI.transfer(0xe2);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xf0);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  switch (whatIsData) {
    case 1: {

        buf = byte2;
        data = byte1 + buf / 10;
        buf = byte4;
        hum = byte3 + buf / 10;

        Serial.print("Received data from DHT22 -> temp:");
        Serial.print(data);
        Serial.print("  humidity:");
        Serial.println(hum);

        break;
      }
    case 2: {

        Serial.println("Received data from PIR -> Move detected");

        break;
      }
    case 3: {

        buf = byte2;
        data = byte1 + buf / 10;

        Serial.print("Received data from gas sensor -> %gas:");
        Serial.println(data);

        break;
      }
    default: {

        Serial.println("a problem accured");

        break;
      }
  }

}

void NRF_receiverBegin() {

  //reading
  /*digitalWrite(8, 0);
    SPI.transfer(0x00);
    delay(10);
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);*/

  pinMode(7, OUTPUT);  //CE
  pinMode(8, OUTPUT);  //CSN
  delay(100);
  digitalWrite(8, 1);
  digitalWrite(7, 0);

  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV4);
  SPI.begin();
  delay(100);

  digitalWrite(8, 0);   //flush TX_FIFO
  SPI.transfer(0xe1);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);   //flush RX_FIFO
  SPI.transfer(0xe2);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xf0);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  digitalWrite(8, 0);
  SPI.transfer(0x00 + 0x20);
  delay(10);
  SPI.transfer(0x0f);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  /*digitalWrite(8, 0);
    SPI.transfer(0x11 + 0x20);
    delay(10);
    SPI.transfer(0x01);
    delay(10);
    digitalWrite(8, 1);*/

  //Down for DYNPL
  digitalWrite(8, 0);
  SPI.transfer(0x1c + 0x20);
  delay(10);
  SPI.transfer(0x01);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x1d + 0x20);
  delay(10);
  SPI.transfer(0x04);
  delay(10);
  digitalWrite(8, 1);
  //Up for DYNPL

  digitalWrite(8, 0);
  SPI.transfer(0x01 + 0x20);
  delay(10);
  SPI.transfer(0x3f);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x02 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x03 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x04 + 0x20);
  delay(10);
  SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x05 + 0x20);
  delay(10);
  SPI.transfer(0x4c);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x06 + 0x20);
  delay(10);
  SPI.transfer(0x06);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x0a + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x10 + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

}

void NRF_startListening() {

  attachInterrupt(digitalPinToInterrupt(2), IRQ, FALLING);

  digitalWrite(7, 1);   //CE High
  Serial.println("Listening started");

}

void NRF_monitorRegisters() {

  for (int i = 0; i < 30; i++) {
    digitalWrite(8, 0);
    SPI.transfer(i);
    delay(10);
    Serial.print(i , HEX);
    Serial.print(" -> ");
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);
  }
  Serial.println("");

}

void setup() {

  Serial.begin(115200);

  NRF_receiverBegin();
  NRF_startListening();
  NRF_monitorRegisters();

}

void loop() {

  /*if (millis() - lastTime > 20000) {
    NRF_monitorRegisters();
    lastTime = millis();
  }*/

}


It is possible to program Linino to send HTTP requests and then use the returned values in sketch?

Take a look at Bridge example or TemperatureWebPanel example: you see you can receive kind of "commands" and react "doing things".

Then take a look at HTTP Client example, where you delegate an HTTP call to the linux side.

Now mix the two: you can make HTTP calls after receiving a command from outside your Yun.

A short test can be done by cutting and pasting the examples above.


The Serial Class of the Arduino uses Typical usage of the Serial Ports is the USART in Async mode. Which is hard coded to IDLE state of HIGH or 1 or VCC.

http://midas.psi.ch/mscb/hardware/bits.gif
(picture wont add - so here is a link to it)

If you need to drive the TTL inverted from its traditional values, the Serial Class can not do this. However, you can use the SoftwareSerial Class and enable the inversion in the constructor

SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

As for why would someone want to invert the TTL UART. In some cases it is possible to drive RS232 directly. As RS232 converters inverts the TTL to +12V/-12V. 5V = -12V and 0V = +12V. So depending upon the RS232 receiver, it may actually trip its TTL output  at 2.5V and not 0V. If so then using the SoftwareSerial Class with inverse logic may drive the RS232 input of another device, without requiring a RS232 transmitter on the Arduino's TXout pin.


Continuous voltage on IO Pins while 5V is not Connected?

For this I would recommend isolating the power from the batteries with P-channel MOSFETs and only switching them on when you want to sample the voltage. This means that there is no power consumption at all (aside from an absolutely minuscule leakage current) when turned off.
The whole setup would require 4 MOSFETs - two P-channel and two N-channel. They don't need to be big, since the currents involved are very small, but they do need to have "logic level" thresholds, ideally < 1.5V (-1.5V for the P-channel).
The basic circuit looks like this:

simulate this circuit – Schematic created using CircuitLab
The circuit is made up of two identical segments - M1+M3 and M2+M4.  The operation is fairly straightforward:

M1 (M2) is kept in the OFF state by R1 (R2) pulling the gate up to source.
M3 (M4) can pull the gate of M1 (M2) LOW turning it on and allowing current to flow
Any GPIO pin (D7 in this example) can control both M3 and M4 together
R5 keeps M3 (M4) off when there is no power - otherwise it floats.
R3/R4 are your existing voltage divider.

The purpose of M3 and M4 is to both turn the GPIO (D7) into "open drain" so that it's either pulling down or floating high (rather than driving high at 5V) and to isolate the two pullup gate voltages. The same effect could be achieved by two diodes and one MOSFET but it's simpler to just use two MOSFETs and not have to get diodes as well.


Yes, it sounds like that pin is fried.

You seem to have done all the things I would recommend:

Try your circuit on a different pin (works fine)
Try your circuit on the same (faulty) pin on a different microcontroller (works fine)

If you get different results between two chips that should be the same with the same code running on them then one of them is most likely faulty in some way, or has some other setting in it (fuse setting) that could be affecting it.  I am not aware of any settings like that on the '328P, certainly none that you would change without knowing you had changed them.


Why does a 4 digit 7 segment cathode display wired to an Arduino not need to be connected to ground?

The Uno is grounded. Current flows into the A-G and DP pins (that is: D2, D3, D4, D5, D6, D6, D8, and D9 on the Uno) when one of those pins is LOW and one of the display's digit pins is also low.

There is one "Common" pin for each of the 4 digits, labeled D1, D2, D3, and D4 on the display. Those common pins are connected to the Anodes (positive pin) of all segments in the specified digit. When 5V is applied to the base of the transistor, the NPN transistor is off. When 0V is applied to the base of the NPN transistor, current flows from the 5V source, through the transistor, and into the Anode of the digit.

When a segment pin (A-G, DP) is HIGH, it is at 5V. The Anode is also at 5V, so no current flows. When a segment pin in LOW, it s at 0V, and current flows from the Anode to Ground through the segment pin into the Uno.

This kind of display is meant to be multiplexed by digit. To light the first digit, The D1 transistor is turned on, and the segments to light up are set to LOW. All other transistors are off. Then, the first digit transistor is turned off and the 2nd digit transistor is turned on, and the segment pins are re-adjusted so that the desired output on the 2nd digit is displayed. Each digit is only on for a fraction of a second, but they are rotated through all 4 so quickly, that it gives the appearance of all 4 digits being on at the same time, without requiring 8x4=32 IO pins. Multiplexing means you only need 8+4=12 IO pins.

Search "multiplexed common anode 7-segment display" for more info.


Upload code on Arduino Leonardo using command line

After try some trial and error I have built a simple binary to upload into the Leonardo bootloader. This binary opens serial at 1200 baud then closes it, and wraps the avrdude binary to write .hex into flash.

In Arduino core CDC.cpp we can see that CDC not only waiting baudrate 1200, but CDC checking DTR value. If DTR goes high, CDC cancels to jump into the bootloader. That's why I cleared DTR value. I tried this in Ubuntu 16.04.

https://github.com/vanbwodonk/leonardoUploader

Only use this simple command:

leonardoUploader /dev/ttyACM0 Blink.ino.hex

I hope it helps other people searching for this.


From the Arduino playground:
This sensor board has a voltage regulator. When using 3.3V to the VCC the resulting voltage (after the onboard voltage regulator) might be too low for a good working I2C bus. It is preferred to apply 5V to the VCC pin of the sensor board. The board has pull-up resistors on the I2C-bus. The value of those pull-up resistors are sometimes 10k and sometimes 2k2. The 2k2 is rather low. If it is combined with other sensor board which have also pull-up resistors, the total pull-up impedance might be too low.


class enum was not declared in this scope

This is a known bug of Arduino builder, if you have functions before structs, classes or enums in sketch.
The sketch:
void foo() {
}

enum class CYCLE { TypeA, TypeB };

String cycleToString (CYCLE cycle) {
  if (cycle == CYCLE::TypeA) {
    return "TypeA";
  }
  else if (cycle == CYCLE::TypeB) {
    return "TypeB";
  }
  return "Undefined";
}

void setup() {
}

void loop() {
}

is processed to this .cpp file
#include <Arduino.h>
#line 1 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
#line 1 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"

#line 2 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
void foo();
#line 7 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
String cycleToString(CYCLE cycle);
#line 17 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
void setup();
#line 22 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
void loop();
#line 2 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
void foo() {
}

enum class CYCLE { TypeA, TypeB };

String cycleToString (CYCLE cycle) {
  if (cycle == CYCLE::TypeA) {
    return "TypeA";
  }
  else if (cycle == CYCLE::TypeB) {
    return "TypeB";
  }
  return "Undefined";
}

void setup() {
}

void loop() {
}

as you can see the forward declarations of functions are before the first function so before the enum.
The workaround for this bug is to follow good practice and declare all the structs, enums and classes before the first function definition.


I have made a Nano send 4 pot values to an Uno please help with code

If your goal is to "talk" to a computer vs. a human, then a format that can be parsed easily is better than one that is easy to read.
For example, you have:
I received: 255
I received: 247
I received: 11
I received: 0

While this could be parsed by your Uno, it will be a lot simpler if you send the data something like:
255|247|11|0

Now you can use a "C" string parsing function like strtok() to parse on the "|" character.  Of course there are many other ways to do this as well but this is one possible solution to your question.


There seems to be an incompatibility between recent versions of the IDE and the library I was using.

Installing the latest version of the library from GitHub and replacing the lcd.init() command with lcd.begin() in my sketches solved the problem.


Make system with ultrasonic sensor and servo

Look at your code sequence. An ultrasonic measurement is only taken, when you use pulseIn(). At the end of the loop() function you call your servo() function. In it you tell the Arduino to first go from 0° to 180° and then back to 0°. AFTER THAT (!) the function exits and the loop() function continues. This means, that nothing else happens during the servo motion. The measurement only takes place between the motions, meaning about every 10s.

To solve this problem you need to make the servo code non-blocking. It is mostly a bad thing to use delay(), since you cannot do anything else during waiting. Think about how you are backing a pizza. You are not sitting in front of the oven the whole time, until the pizza is ready. Instead you are looking at your clock regularily and check, if it is time to take the pizza out of the oven.

You can do the same thing on an Arduino with the millis() function. It will return the milliseconds since the last reset/powerup of the Arduino. This has to be used as a clock. To do something after a specific time you first save the current time in a timestamp:

unsigned long timestamp=0;
...
timestamp = millis();

Then in the loop() function you are regularly (on every loop iteration) checking, if the difference between the timestamp and the current time is above your set interval:

if(millis() - timestamp > 30){
    // do something here, like moving a servo
    timestamp = millis(); //update timestamp for next event
}

The Arduino will not do the things simultaneously, but will switch between the different code parts so fast, that it will seem simultaneous. Also refer to the BlinkWithoutDelay example of the Arduino library.

Note: The current delay between two consecutive servo values is ok. If you want to go way faster with the servo, you have to watch out, that the rest of the code in loop() doesn't take to long. If this happens and you cannot make the other code parts non-blocking too, you can also do the servo part in an interrupt routine from a timer.


In your situation, your best bet is probably to use the standard C function strcpy:

payload_t payload;
char* source = "abcdef";
strcpy(payload.sensorid, source);

Note that source string does not have to be declared as char source[20] and can be declared as the rather standard C string char*.

Also, since you are limiting the size of the string to be passed in payload, you may prefer to use strncpy which will ensure no more than 20 characters get copied:

payload_t payload;
char* source = "abcdef";
strncpy(payload.sensorid, source, 20);
// Explicitly add a string termination to the end of string
payload.sensorid[19] = 0;

In the snippet above, please notice the last line, it is necessary in the situation where source string length is 20 or more non-null characters, as in this case, strncpy will copy all 20 characters but will not add the terminating 0 at the end of the string.


Yes. To use standard D.C. motors, you must use a motor shield or the L239D chip. This is mainly due to motor noise, and control to run the motor at different speeds and directions. Also you get very easy to use libraries!


ESP8266 sending GET Request and getting 408 Timeout error

I assume you're doing all this from the serial monitor. You can't use escape sequences like \r in the serial monitor entry box. Everything you enter is evaluated as a string of separate ASCII characters; \r is just a backslash character followed by lowercase r. To send a HTTP request, you make the serial monitor send the \r\n for you.

First set the serial monitor to BOTH NL & CR permanently; it will serve you well for commands and HTTP requests as it appends \r\n to everything you send.
Count the number of bytes in the your HTTP request, including the carriage return and newline characters. I count 61 characters in your request.
Use this count in AT+CIPSEND
Type the first line of your request, and stop right before the first \r\n, and click Send. Because of your setting, the monitor will now send what you typed with \r\n suffixed to it.
Type and send each line of the request, just like you sent the first line, until you've sent the last line.
Since there is an additional \r\n after the last line, you click Send again, without typing anything. And since the module requires \r to indicate the end of the data packet, you click Send one last time.

Hopefully, this should give you the right results.


The main issue is with pins 0 and 1.

Many pins have multiple functions assigned to them, such as A4 and A5 are also the I2C pins, pins 10/11/12/13 are also the SPI pins, etc.  But pins 0 and 1 are the only multi-function pins that actually have something attached to them on the board.

All the other pins, while being multi-function, have their function defined basically by what you attach to them.  Since the pins 0 and 1 are already attached on the board to the USB interface chip their usage possibilities are somewhat more limited.

As soon as you enable Serial in your sketch (Serial.begin()) those two pins can no longer be reliably used for digital IO.

That means that you can either use the hardware serial port or you can use the pins for digital IO, but not both.

Devices connected to pins 0 and 1 can interfere with the serial connection

That includes uploading of sketches.  You have serial data coming in from the PC while the same pins are being affected by other things connected to them.  The most common one is things like GPS modules which connect to those pins and constantly send serial data.  That serial data will conflict with the PC's serial data and neither will arrive right.

How do you upload sketches if the serial is being interfered with by your sketch? How do you "reset" the board?

You don't.  It's not your sketch that's interfering with the serial, it's what is physically connected to those two IO pins that are interfering.  Just disconnect those two pins from whatever is connected and you will be able to upload sketches again.  Many shields now are starting to add a small switch on them to disconnect those pins so you can upload sketches without unplugging the shield.  You can also use the same trick with other devices you wire up to those pins - add a double-pole-single-throw or double-pole-double-throw (and not use one position) to easily isolate both pins from the rest of your hardware when you need to.

Does this affect all Arduino boards?

No, only those that use a USB to Serial bridge chip - that's things like the Uno, Due, Mega, etc.  Boards that have a direct USB connection don't use the TX and RX pins for uploading sketches - they use the dedicated USB D+ and D- pins.  That's boards like the Leonardo, some of the smaller (mini? micro? I forget which) boards, etc.


You have far too many variables and unknowns there. Primarily you need to know what the average current draw for your circuit is. Secondly you need to decide how long the solar powers are allowed to take to recharge the battery. You have to think not only about runtime but also charge time. The charge time dictates the maximum capacity of the battery, and that then dictates the runtime of the Arduino. So here's some napkin maths to illustrate:

Assuming you want the battery to charge from almost flat to full within 8 hours, and with a 1.1W 6V solar cell, that gives you a peak of 183mA.

Assuming the Arduino circuit takes 83mA on average (let's give ourselves nice round numbers here) that leaves 100mA peak for charging the battery.

If you're charging at, say, 0.2C, that gives a full charge in 5 hours. 100mA / 0.2C = 500mAh capacity (at peak sunlight and current).

At 500mAh capacity and 83mA average current draw that would give you (0.5/0.083) 6 hours of runtime without the solar panels.

So that's just not going to work.  It'll be dead by morning.

Now assume that you can turn off everything for 99% of the time.  That effectively reduces our average current draw to 0.083*0.01 = 830µA. Let's plug that into the same reasoning as above.

Current draw = 0.00083A
Incoming peak current = 0.183
Available charge current = 0.183-0.00083 = 0.18217
Charge at 0.2C = 910mAh.
1Ah battery would charge in about 5.5 hours of peak sunlight.
1Ah would last about 1200 hours, or 100 days.

None of this takes into account varying light levels or light incidence angles. As a rule of thumb, take the light as averaging 50% over the course of the 8 hour period. You will only get 1.1W when the angle of incidence is 90° to the solar panel. At all other times it will be reduced. So if we reduce the current from 183mA to, say, 100mA, the charge capacity changes to:

Incoming peak current = 0.100
Available charge current = 0.100-0.00083 = 0.099
Charge at 0.2C = 496mAh
A 500mAh battery would charge in about 5 hours.
A 500mAh battery would run for about 50 days at 830µA average current.

So you see everything really hinges around the current consumption of the Arduino. How much current it consumes dictates how much is available to charge the battery, which in turn dictates the size of battery you can support, which dictates the amount of current you can draw for your desired runtime, which in turn dictates the amount of charge current available, which determines the size of battery you can support, which dictates ... etc.  You get the idea.

You can support larger batteries, of course - I illustrated this at 0.2C charge rate (that's 20% charge per hour to give a 5 hour charge time). As long as the net charge over time increases (so during the periods between the 5-7 days of complete darkness you gain more charge than is expended during the dark period - something which has not been specified) then it should function fine.

Also note that your battery voltage should be below your solar panel voltage. A 6V solar cell would be able to charge a 4.5V lead acid battery (assuming low dropout schottky protection diodes). Also the capacity of the battery depends also on what you determine your "cut-off" voltage to be. That's how low the battery voltage is allowed to go before your system is determined to be unworkable. This could be at a point where the battery is in danger of being damaged by over-discharge, or at a point where your circuit no longer receives enough voltage to function (which could be linked to oscillator frequency on ATMega chips), etc. For this reason it is often better to choose a board that is designed to run at a lower voltage (3.3V) and use high efficiency switching regulation to get the most out of your battery. A 5V Arduino is seldom a great choice.

Finding that right balance is now entirely up to you.

And, in answer to your other question, yes there are ways to turn things on and off. You can "sleep" the Arduino. You can use high efficiency power circuits. You can add power switching circuits (P-MOSFETs) to switch power on and off to other modules. All things can (and mostly should) be done to save power when running on batteries.


SPI Problem with K-Thermocouple and Potentiometer?

The wiring diagram, if accurate, shows a couple of problems.

First, A0 has nothing attached to it, so sensorValue may read in as zero or some small random number.

Second, attaching the digital pot's analog output pin 6, P1W, to the Uno's digital input pin 12 is pointless.  Instead connect P1W to whatever it is supposed to control.  If you want to handle data from the MCP42X1, connect its pin 13, SDO, to an Uno input.

However, neither of those problems appears to be related to misreading the MAX6675 temperature.  I don't know of a good approach to solving that problem, but if I were working with the circuit, would remove the wire between P1W and the Uno's digital pin 12, and would use 12 as the input from the MAX6675; that is, would wire it to d12 instead of d8, and instead of int ktcSO = 8 would say const int ktcSO = 12.  Also, I'd probably replace the bit of code

  }
  else
  {
    while (ktc.readFahrenheit() < 85)
      {

with just a closing }.  In the Arduino paradigm, loop() runs repeatedly, and the if–else sequence adequately guards each of the digitalPotWrite() calls.

Note, the digitalPotWrite() function should be defined or declared before any calls to it appear.  Instead of placing that function at the end, put it before  loop() or before setup().


Not getting pure color while using the FastLED with WS2812b

I can see what the problem is, I put FastLED.show(); where it should not, that's also why I saw the flash ... fix it and here's the result:

void loop() {
  ReadMySerial();       //This function take data from serial port and set the color for the leds
  FastLED.setBrightness(brigth);

  for (int pinNo = 0; pinNo <= 2; pinNo++){
    leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
    FastLED.show();
    if (digitalRead(pinNo+3) == HIGH){
      leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
    }
  }

  FastLED.show(); //NOW IS IN THE RIGHT POSITION
}


Can't detect I2C displays with Arduino Nano

You seem to have two issues here:

As already pointed out, you have the white wire connected to the wrong pin on the Arduino
Also, you need to solder the headers on the Arduino. There is no solder on the pins, which means that there is no connection. You need to solder those headers on; it looks like you just set the Arduino on top, which won't work with headers


How to get 3v3 pins on Arduino Mega Sensor shield v2.0?

They are all 5V as the Mega2560 uses 5 V logic.  However, there is a 3V3 pin at the bottom, second pin from the left, that you could use:

However, unfortunately, the pin isn't protruding above the shield, so you'll have to make an ugly solder link to the top of the pin. Either that, or remove the row of pins and replace with a female header (carefully avoiding the SD card pins):

As an aside, the Iteaduino MEGA 2560 works at 3V3 but unfortunately the Mega shield that you have won't fit it.

The Uno equivalent of your shield will fit it though:


ESP8266 not able to communicate over serial connection with arduino UNO

The problem is in your loop() function. On each iteration, you will receive at most one character from the SoftwareSerial, while writing the same AT command again and again. As a result, your slave device (ie. ESP8266) will overflow its UART buffers, resulting in garbage being sent and received.

You should keep receiving data from the slave for as long as it has data:

while (ESP.available()) {
    char inData = ESP.read();
    Serial.println("Got response from ESP8266: ");
    Serial.write(inData);
}


Playing WAV file from Arduino Uno using Ethernet R3 Shield

Your Arduino UNO won't play any wave file the way you're expecting. There's not enough processing power to do that.
In order to play audio using small MCUs such as AVR (or PIC for example) you must use the BTC algorithm. Please, check this out : http://www.radanpro.com/Radan2400/mikrokontroleri/How%20to%20make%20sound%20with%20a%20PIC%20chip.htm
and download the software which can convert your wave file into an array which can be then played by Arduino using a BTC algorithm. Schematics on how to place reistors and speakers to match impedance are provided and suggested on the software as well.


Do I need a pull-up/down resistor for button LED circuit?

The circuit you have made is only using Arduino as a 5V power source. You aren't using any GPIO pins to read the state of the button or to control the LED by an output pin. You've just made a plain-old circuit with a button and LED in series with a power source.

Often for a button-controlling-LED sketch, you will have a button connected between GND and an I/O pin defined as an INPUT_PULLUP, which means the Arduino will be able to read the state of the pin as HIGH (5V) or LOW (0V). The PULLUP part indicates that when the button is not completing the circuit between GND and the pin, a weak voltage is applied to get it up to 5V. In this way it's not "floating" at an unspecified voltage, but is being actively driven to 5V. When you press the button, the input pin is shorted to GND.

A pull-up resistor causes an otherwise un-driven pin to go to logic HIGH. A pull-down resistor causes an otherwise un-driving pin to go to logic LOW.

In the case of a pull-up resistor, reading a logic LOW means the button is pressed, which is kind of the reverse of your circuit operation, so in your sketch code, you would look for LOW to turn on the LED.


Flash size in boards.txt ATmega 328p 32u4

1KB is 1024 bytes, not 1000 bytes.

Therefore 32kb = 32768 bytes.

32768-512=32256, which is exactly the value used for upload.maximum_size for the 328p.

4kb=4096 bytes. 32768-4096=28672 which is the value for the 32u4.


Cannot write lock byte on Arduino Pro Micro

Meanwhile, I managed to solve this problem.
The reason for the verification error is that the two most significant bits of the Lock Byte are read-only on my variant of the Arduino Pro Micro. Which means that, if you (try to) write a value of 0x00 = 0b0000 0000, it will result in a value of 0b1100 0000 = 0xC0 on the hardware.
The solution, then, was to simply ignore those two bits.

> avrdude -p m32u4 -P /dev/ttyUSB0 -c stk500v2 -b 115200 -U lock:w:0xCF:m


After wondering over it for quite a long time, I finally came to the conclusion, that the interrupt should be made to trigger at RISING edge, if I want it to go into ISR the moment it gets HIGH.

Hence the setup line was change to

attachInterrupt(4,bump,RISING);

And the cod e works well.
I suppose that is because, when it receives a HIGH signal, than the period for which it receives HIGH is a bit long, during which it adds another interrupt into the queue, and so the ISR is executed once again.


To get an understanding of how to read from the various ADS1220 channels, first review Figure 38, Analog Input Multiplexer, in the Datasheet as obtained from a link on TI.com's ADS1220 technicaldocuments webpage.

As can be seen, you'll need to close a switch from an AINx input line to the AINₚ bus, and also close the switch between AINₙ and AVSS.  The IDACx switches and the BCS switches should remain open.

To operate those switches, first look at §8.6.1, Configuration Registers, in the Register Map section of the Datasheet.  You'll see that MUX bits are in register 0, BCS is in register 1, IDAC is in register 2, and IxMUX are in register 3.  To see what to put into those fields, look at Tables 16, 17, 19, and 20.  For the MUX field, you will want a binary value like 1000, 1001, 1010, or 1011 to select one of AIN0-AIN3 as the AINₚ input and AVSS as the AINₙ input.  BCS, IDAC, I1MUX, and I2MUX all should be zero.

For example, to read channels 0, 1, 2 in sequence, set MUX to 1000, set up other register fields, and trigger a conversion.  After reading the result, change MUX to 1001, trigger a conversion, read result,  change MUX to 1010, trigger a conversion, read result, etc.

Edit 1: In slightly more detail, one could do as follows.

  • Use a WREG command [as in §8.5.3.6; or some library equivalent] to send three bytes to set up Configuration Registers 1, 2, 3.
  • For i=0, 1, and 2 in turn, construct a configuration byte, send that byte to Configuration Register 0, start a conversion, await result, read result; as follows:

    Set the MUX field of a byte to i
    Set PGA as desired (ie, to 1, 2, or 4, via codes 000, 001, or 010)
    Set the PGA_BYPASS bit (as required when AINₙ = AVSS)
    Use a WREG to send the constructed byte to Configuration Register 0
    Use a START/SYNC command to start a conversion (see §8.5.3.2)
    Wait for DRDY to go low
    Use an RDATA command to read iᵗʰ ADC result (see §8.5.3.4)

Edit 2: In Protocentral's ADS1220.ino sketch, one finds the code sequence

  MSB = SPI_RX_Buff_Ptr[0];
  data = SPI_RX_Buff_Ptr[1];
  LSB = SPI_RX_Buff_Ptr[2];
  bit24 = MSB;
  bit24 = (bit24 << 8) | data;
  bit24 = (bit24 << 8) | LSB; // Converting 3 bytes to a 24 bit int
  bit24= ( bit24 << 8 );
  bit32 = ( bit24 >> 8 );     // Converting 24 bit two's complement to 32 bit two's complement

More competently and concisely, and with SPI_RX_Buff_Ptr renamed to SPI_RX_Buff, this could be written as:

  bit32 = (((long)(SPI_RX_Buff[0]<<8 | SPI_RX_Buff[1])<<8 | SPI_RX_Buff[2])<<8)>>8;

which acts as follows:  Assemble three bytes from SPI_RX_Buff into a 24-bit twos-complement-signed number.  Shift that number left 8 bits so that its sign bit now sits in the sign bit position of a 32-bit signed integer.  Shift that result 8 bits right with sign extension so that the final result is a signed 32-bit integer with possible values from -2²³ up to (2²³-1).

Sign extension occurs – usually – because in many implementations of C, the >> operator does an arithmetic shift instead of a logical shift when its operand is signed.


Hardware-wise this should be pretty easy to do. You need to connect pins 2 and 3 of each GSM shield to separate serial ports on the Arduino board. The best way to do this is to use an Arduino Mega, which has 4 hardware serial ports, this leaves you Serial for uploading sketches and communication to Serial Monitor. It's also possible that you could use a software serial library like AltSoftSerial but I wouldn't recommend it. You can carefully bend the pins 2 and 3 of two of the shields out before stacking them and then use jumper wires to connect those pins to the hardware serial pins of the Mega. The other pin of interest is pin 7, which is the modem reset pin. If you leave all the modems connected to pin 7 on the Arduino that means that there is no way to only reset a single modem. I'm not sure how much of an issue that would pose. So you might be better off to bend pin 7 on two of the shield out also and connect those to separate pins. You will also need to be sure to provide a power supply capable of supplying sufficient current. The product page says each shield may require up to 1000mA.

Software-wise it gets much more tricky. Unfortunately the stock Arduino GSM library was not written to be very flexible. Instead of allowing you to pass it a Serial object it's hardcoded to do software serial on pins 2 and 3 so you would need to do quite a bit of work on the library to make it work for your needs. I'd recommend looking around to see if a more suitable library exists.


Majenko showed you one of your mistakes.

Then you wrote:

//Enable to interrupt Compare Match A
TIMSK1 = (1<<OCIE1A);

And this is your other mistake. You should not enable an interrupt
unless you have defined an ISR for it. Otherwise your program will
restart every time the interrupt fires.


GET /ilyen_nincs HTTP/1.1\n is 26 characters long so string indices are from 0 to 25. Since, your second argument in substring(0, firstEOLAt); exceeds the end index of the string, you are running into unexpected behavior as per the documentation and getting an empty string.

  Caution: make sure your index values are within the String's length or you'll get unpredictable results. This kind of error can be particularly hard to find with the second instance of substring() if the starting position is less than the String's length, but the ending position isn't.


A general hint first: indent your code correctly. It makes it much easier to read and easier to spot logical errors.

Another improvement would be to name the pins with the same names as you name them when explaining the problem to us. I expected to find a int buttonRunPin and int buttonStopPin.

The first issue I see is:

buttonNew=digitalRead(buttonPin);
buttonOff=digitalRead(buttonPin);

This reads the same button twice. You probably wanted to read two different buttons: the "run" button and the "stop" button.

The next issue I see is:

delay(8000);
delay(2000);

During these 10 seconds, you can press and let go the button many times. But since there is no digitalRead() during that time, the button press will not be recognized.

The same applies to

int dt=100;
delay(dt);

If you press the button within these 100 ms, it will not be noticed.

Unfortunately, to fix that, you need to learn a completely new concept: interrupts. And even worse, not all pins support interrupts. On the Arduino Uno, it's only pin 2 and pin 3, which means you would need to change your hardware setup (because you use pin 12 and 13). Put both buttons from the pin to ground, so that it closes when pushed.

You would then prepare the interrupt in the setup() routine:

pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin), toggleRun, CHANGE);
pinMode(buttonPinOff, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPinOff), toggleStopped, CHANGE);

You also define global variables for the state of the buttons:

volatile bool running = false;
volatile bool stopped = false;

volatile is needed here to prevent the compiler from optimizing too much. The compiler does not know about the interrupts and thus can't know when the variable changes.

Next, you need two methods that are being executed whenever an interrupt occurs, i.e. you press a button:

void toggleRun() {
    running = !running;
}
void toggleStopped() {
    stopped = !stopped;
}

Note: the above x = !x; pattern is a short and efficient form of

if (x == false) {
    x = true;
}
else if (x == true) {
   x = false;
}

Once you have all that, you don't need the two digitalRead()s any more.

I'm afraid I haven't understood what your code's supposed to do. You have a lot of state variables that seem to have no use and especially they don't correspond to the motors. E.g. once RELAYGrnState is set to 1, it never changes back to 0.

This is what I have in the end:

int LEDYelState=0;
int LEDRedState=0;
int LEDGrnState=0;
int RELAYRedState=0;
int RELAYYelState=0;
int RELAYGrnState=0;
int LEDRedPin=10;
int LEDYelPin=9;
int LEDGrnPin=8;
int RELAYRedPin=7;
int RELAYYelPin=6;
int RELAYGrnPin=5;
int buttonPin=13;
int buttonNew;
int buttonOld=1;
int dt=100;
int buttonOff;
int buttonPinOff=12;

volatile bool running = false;
void toggleRun() {
    running = !running;
}

volatile bool stopped = false;
void toggleStopped() {
    stopped = !stopped;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(LEDRedPin, OUTPUT);
  pinMode (LEDYelPin,OUTPUT);
  pinMode (LEDGrnPin, OUTPUT);
  pinMode (RELAYRedPin, OUTPUT);
  pinMode (RELAYYelPin, OUTPUT);
  pinMode (RELAYGrnPin, OUTPUT);

  pinMode(buttonPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonPin), toggleRun, CHANGE);
  pinMode(buttonPinOff, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonPinOff), toggleStopped, CHANGE);
}

void doSomething() {
  digitalWrite(LEDRedPin,HIGH);   // red LED is on
  LEDRedState=1;
  digitalWrite(RELAYRedPin,LOW);  // red motor off? others unclear
  RELAYRedState=1;

  digitalWrite(LEDYelPin, HIGH);  // yellow LED and red LED are on
  LEDYelState=1;
  digitalWrite(RELAYYelPin, LOW);  // yellow motor off?
  RELAYYelState=1;
  delay (8000);
  digitalWrite(LEDYelPin,LOW);     // red LED on
  digitalWrite(RELAYYelPin,HIGH);  // yellow motor on

  digitalWrite (LEDGrnPin,HIGH);  // red and green LED are on
  LEDGrnState=1;
  digitalWrite (RELAYGrnPin, LOW);  // green motor off
  RELAYGrnState=1;
  delay(2000);
  digitalWrite  (LEDGrnPin,LOW);    // red LED on
  digitalWrite (RELAYGrnPin,HIGH);  // green motor on
  RELAYGrnState=1;
}

void doLess() {
  digitalWrite(LEDRedPin, LOW);     // red LED off
  LEDRedState=0;
  digitalWrite(RELAYRedPin, HIGH);  // red motor on
  RELAYRedState=0;
  digitalWrite(LEDYelPin,LOW);      // yellow LED off
  LEDYelState=0;
}

void loop() {
  if(running){
    if (!stopped){
      doSomething();
    }
    else{
      doLess();
    }
  }
  delay(dt);
}


You can avoid using the attach(); method by programming without the servo library.

  for(x=0; x<150; x=x+1)
  {
    digitalWrite(Servomotor, HIGH);
    delayMicroseconds(2350); //Change the delay here to change the angle it goes to
    digitalWrite(Servomotor, LOW);
    delayMicroseconds(18550);
  }

This is an example code for how it worked for me. It sends a pulse to the servo which makes it turn a bit until it reaches a "barrier".


Performance of internal vs external resistors

If you are using the pin as an input in close proximity to the Arduino there is little reason to use an external pullup.

There are a number of factors to consider.

If the switch is some distance from the chip and/or in a noisy environment it will be more susceptible to interference as the internal pullups are high impedance (20kΩ to 150kΩ depending on model).

If the pin is used as both input & output the pullup can reduce the voltage swing.

In other applications e.g. Raspberry Pi the state of the pin between boot and software initialisation can be significant, but this should not be an issue with Arduino.


Print output on 16x2 LCD and Serial Monitor

If you are using clasical UNO, then pins 0 and 1 are Serial. Declaring lcd(1,... make LCD use the pin 1 too, so Serial is confused and garbled.

Use other pins for lcd and adjuct the wires acordingly.


My brand new LCD screen doesn't display anything, even though there is no code errors?

Turns out that the diagram was wrong. Needed to move the potentiometer 1 pin to the right, now it works!


As far as I understand, using an if statement wouldn't make any difference, but using a while statement would.

The serialEvent() function is executed within each execution of your loop() function if there is data available, so it would be something like:

while (true)
{
    loop();
    if(data_available)
        serialEvent();
}

If you only have one byte of information in the buffer, then you wouldn't have any problem at all.

But if you want to read multiple bytes at the same time, you would have to wait until the loop() is executed again to read the next byte.

You will solve that problem if you write your  serialEvent()  like this:

void serialEvent()
{
    while (Serial.available())
    {
        // do something
    }
}

That way, you will read all the information available at once and then return to the loop.


I am not able to use ESP8266 12E with Arduino

I agree with Paul, you shouldn't use the Arduino, you can get break out boards at £1 for 10, but that's not what your problem is...

You are using a couple of resistors to do the level shifting taking the 5V to 3.3V.  This is a bad plan, you need a proper bidirectional level shifter, particularly at higher baud rates, i.e. above 1000.

You are supplying the top VCC rail with both 3V from the batteries and 3.3V from the Arduino, not the best plan IMO.

You are not supplying the Arduino with any power, I guess this is a drawing error but just in case it isn't I though I best mention it.

You have no level shifting on the Arduino's Rx line.  Its not technically needed, but you might require it particularly when the batteries are going flat.

You are using batteries and that's not a great plan.

Have you configured the ESPs using the AT command set, since you won't program them.

Just for the record the ESP has more memory it has a faster processor (80MHz) and you can still use the Arduino IDE.  You should be able to pick up boards to mount the ESPs so you can use them more easily for less that the price of the level shifters, but its your call.


Using c_str() on String for IPAddress with NTPClient provides wrong values

The String object created as return from IPAddress.toString() as parameter to constructor of NtpClient is temporary. It contains the char array returned by c_str(). NTPClient doesn't copy the string, only stores a reference to it. And the referenced string (char array) doesn't exist at the time the NTPClient wants to use it.

class TestClass {
public:
  TestClass(const char* _ip) : ip(_ip) { }

  void test() {
    Serial.println("--");
    Serial.println(ip);
    Serial.println("--");
  }

private:
  const char* ip;
};

//String s("abc");
//TestClass Test(s.c_str()); <- this works

TestClass Test(String("abc").c_str()); // <- this can't work

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


Sending hex data serially and receive it back

Here is your code fixed: if you want to send numbers encoded as hex strings that's exactly what you have to do on both ends.
The standard function itoa() is what converts numbers to their string representation, but operating this way you are wasting a lot of resources because to send the number 1 (which can be accomplished by sending exactly one byte) you are sending the string 0x01 (which now requires 4 bytes to be transferred).

const byte numChars = 88;
word receivedChars[numChars];   // an array to store the received data

boolean newData = false;

void setup() {
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
}

void loop() {
    uint8_t message[] = {0xA5, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x0d };

    char buf[4];
    for (uint8_t i = 0; i < sizeof(message); i++) {
        itoa(message[i], buf, 16));
        Serial.write(buf, sizeof(buf));
    }
    delay(500);

    recvWithEndMarker();
    showNewData();
}

#define END_MARKER '\n'
void recvWithEndMarker() {
    static byte ndx = 0;
    char rc;

    while (Serial.available() > 0 && !newData) {
        rc = Serial.read();

        if (rc != END_MARKER) {
            receivedChars[ndx++] = rc;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        } else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData) {
        Serial.print("data ");
            for (unsigned int i = 0; i < numChars; i++) {
            Serial.print(receivedChars[i], HEX);
        }
        Serial.println();
        newData = false;
    }
}


In the second code example, the value of sizeof(cmd)/sizeof(cmd[0]) is 9, due to the declaration unsigned char cmd[9] ...

Thus, the for loop will write out 9 bytes, with indices 0, 1, ... 8.  Due to cmd[8]=0; earlier in the code, the last byte will be zero.  To prevent that, one might instead use the expression  sizeof(cmd)/sizeof(cmd[0])-1 in the for loop:

for (int i=0; i< sizeof(cmd)/sizeof(cmd[0])-1; i++)
   RS485Serial.write(cmd[i]);

Note, this doesn't explain why it should be so that “If I remove the allocation for the null-byte in the second code, it does not get a response from my device”, although practically anything can happen if you say cmd[8]=0; after allocating only 8 bytes of storage.


A quick google search turned up a solution in the very first result:

https://forums.adafruit.com/viewtopic.php?f=31&t=36560

It is a contribution from an Adafruit customer.
All credits go to them.

Source thread: https://forums.adafruit.com/viewtopic.php?f=31&t=36560


NeoPixel library performance: Adafruit vs. FastLED

You can't rely on the timing reported by millis when comparing FastLED and Adafruit's neopixel library.  Writing out Neopixel data involves disabling interrupts, which is what the clock uses to advance.  FastLED accounts for this and attempts to update the system clock time after writing out led data to account for the amount of time that interrupts were disabled, but the adafruit NeoPixel library doesn't.  You need to use something else to compare timing.

(WS2812 data has a pretty strict data rate - 800khz, or about 30µs per rgb led)

(I should know, I wrote FastLED :)


Potentiometer on motor for position control

I am trying to get a wiper motor to have a known position 360 degrees around.

There might be a few possibilities.

First there are continuous rotation potentiometers on the market. They seem expensive though and I can't comment on how accurate they are.

Second, if your device is only ever going to turn through say ten revolutions then go back, you could just get a multiturn pot that will handle that range of turns. (Depends what you're building of course - for example I've heard of servo winches for model sailboats that use this method.)

Thirdly, and I accept this may not be a good answer to your question, but have you thought about using incremental encoders instead? In theory they could be more accurate too. The hardware is quite easy but a bit more programming is required to make these work...


Safe place to download CH340G drivers from

Linux doesn't need drivers (indeed, the whole concept is pretty alien to Linux users).

The CH340G is fully supported by the default kernel in all distros I have ever used. On my Ubuntu machine the CH340G on my NodeMCU is detected automatically:

[ 8195.450566] usb 4-1: new full-speed USB device number 2 using uhci_hcd
[ 8195.630710] usb 4-1: New USB device found, idVendor=1a86, idProduct=7523
[ 8195.630714] usb 4-1: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[ 8195.630716] usb 4-1: Product: USB2.0-Serial
[ 8196.675137] usbcore: registered new interface driver usbserial
[ 8196.675153] usbcore: registered new interface driver usbserial_generic
[ 8196.675166] usbserial: USB Serial support registered for generic
[ 8196.677581] usbcore: registered new interface driver ch341
[ 8196.677600] usbserial: USB Serial support registered for ch341-uart
[ 8196.677620] ch341 4-1:1.0: ch341-uart converter detected
[ 8196.690670] usb 4-1: ch341-uart converter now attached to ttyUSB0

Nothing to download, nothing to install, nothing to risk the security of your system with.


Why Can't I Program my Atmega168 Pro Mini?

Your hookup seems to be correct. However check if there is a capacitor on the pro-mini board between DTR and reset pin, some arduino clones don't come with one.
If there isn't any you can simply connect a capacitor like this:
Reset pin (Arduino Uno) -> Capacitor (0.01uF for example) -> DTR (pro mini). The reason for this hookup is exmplined well here


Generate 5VDC signal when external sensor input changes from high to low

This is literally the simplest Arduino program possible.  I can't believe you couldn't find an example of making one pin HIGH when another goes LOW.

void setup(){
  pinMode(yourInputPin, INPUT_PULLUP);
  pinMode(yourOutputPin, OUTPUT);
}

void loop(){
  if(digitalRead(yourInputPin) == LOW){
     digitalWrite(youOutputPin, HIGH);
  }
  else {
     digitalWrite(yourOutputPin, LOW);
  }
}

All you need to do is supply the appropriate pin numbers.


Error while connecting Arduino to Macbook: “serial port already in use. try quitting any programs that may be using it”

Sorry about providing this as an answer, rather than comments; however, I do have some suggestions to troubleshoot the connection.

First, check the usb connections with lsusb

    lsusb |grep -i arduino

Similarly, you can try following the output of dmesg; though, I'm not sure about the version of dmesg your system's installation is running.  Newer version of dmesg have a "follow" option available. On my Fedora system it's:

    dmesg -wH

Check the output as you plug in the arduino for messages related to the device, such as the resulting location of the tty. As a desperate measure, you can also look in the /dev/ folder for the last modified device, and search your logs for those devices:

    ls -alrth /dev/


tinkercad arduino simulator integers being outputted as larger numbers than they are?

Bug. No other explanation. Real hardware (Arduino Uno) prints 12000.

Even the debugger tells me that the value of that variable is 12000.

Outputs:

Number: 12222
12000
12222 something

Most interestingly if you Serial.println() the number, it is outputted correctly. The bug must be in the constructor of the String object, as demonstrated by the "test" String. This bug also occurs on other data types, e.g. int.

If you only use direct Serial.print[ln] calls you should be able to workaround that bug.


SMD Voltage Regulator 662k very hot, how to repair it?

From the picture I guess it is a roboduino. The only voltage regulator is the 662k, it is too small compared to other voltage regulators!!! (have a look at the size and sink of the official arduino), so it is normal that the temperature is high. (arduino uno can get up to 1A and the regulator is bigger)

To reduce temperature just use the lowest input source (for instance, for arduino 5 volts, use 7 volts source, not 12 volts source). The bigger input voltage, the higher temperature in the regulator.

Solutions.

replace the 662K with another 662K one.
use a bigger voltage regulator. Since 66K space is tight (SOT-23) and no sink space I suggest to solder a TO-92 like voltage regulator. Not nice solution, but handy.


How to setup an I2C bus which stays valid if a slave is powered down or fails?

The 3 Arduinos are currently being powered by independent USB power supplies, but I intend to power all of them from one single power supply using their Vin pins.

I think your problem here is that if you power down one Arduino, it isn't really powered down, because it will get "parasitic power" from the I2C line, particularly from the pull-up resistors which should be there. The protection diodes (internal to the processor) will allow power to flow from the A4 and A5 pins to the Vcc pin of the chip, which will then power up, probably in some sort of indeterminate state.

Since you are planning to power them from the same supply anyway, your problem should simply go away when you do that. Connecting a device with active inputs to a circuit (ie. a voltage present) when the device itself is not powered up, is not recommended. Exceptions would be devices that are specifically designed to handle that, for example, commercially produced printers via their USB input.


As Majenko wrote in his comment, your problem lies with Serial.readString(). It is generally not a good way to handle Serial data. It reads data from the Serial interface, until the timeout (default 1s) occurs. So it will try to read until 1 second after your last change of the slider and return the whole data as one string. String.toInt() will then start to read the string from the first character and convert them to an integer, until it reads a non-digit character (meaning the n, that you send). It stops there and returns the already converted value.

This means, that out of all the data, that was send to the Arduino, only the first value will be used. The rest get's thrown away.

Better you should use a non-blocking code, that handles the messages (numbers in your case) correctly. This is done by reading the incoming serial data byte by byte, adding them into a buffer, until a special delimiter character get's received. Then the message get's processed as a whole. After that, the next message can be read and processed. This way you don't miss any of the send values.

The special delimiter character is arbitrary; you can use any character, that does not occur in the valid data. So using the character n is ok here. But mostly the newline character \n is used, so that you can also send messages with alphanumeric characters. Most likely you already meant to use \n.

As an example of this serial code, you can take the readline() function from Majenko's blog post:

char buf[80];

int readline(int readch, char *buffer, int len) {
    static int pos = 0;
    int rpos;

    if (readch > 0) {
        switch (readch) {
            case '\r': // Ignore CR
                break;
            case '\n': // Return on new-line
                rpos = pos;
                pos = 0;  // Reset position index ready for next time
                return rpos;
            default:
                if (pos < len-1) {
                    buffer[pos++] = readch;
                    buffer[pos] = 0;
                }
        }
    }
    return 0;
}

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

void loop() {
    if (readline(Serial.read(), buf, 80) > 0) {
        Serial.print("You entered: >");
        Serial.print(buf);
        Serial.println("<");
    }
}

You can convert the character buffer to an int with atoi() in the if statement in void loop() and use it for ´analogWrite()`.


How can you check how long a timer interrupt really is?

It doesn't fire every 33 milliseconds. First, you missed setting the CSn1 bit necessary for a 1024 prescaler; second, It looks like you want CTC mode (where the timer resets at OCRnA) but you didn't set the WGM21 bit necessary for that mode. After that your problem is that timer2 is an 8 bit timer and so OCR2A cannot store 515, but you math is correct.

You can get the period you want on a 16-bit timer; on the arduino mega thats timers 1,3,4, and 5.

Anyway here is a simple sketch for finding the average interval between interrupts. It just keeps track of the total time elapsed and the number of times the interrupt fired; the ratio of these two is the average time per interrupt.

In this case, with a prescaler of 1024, OCRA = 0xFF, and CTC mode, it runs at an interrupt every 16.384 ms.

volatile uint16_t interruptCount;
volatile uint32_t start;

ISR(TIMER2_COMPA_vect){
    interruptCount++;
}

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

    noInterrupts();
    TCCR2A = _BV(WGM21);
    TCCR2B = _BV(CS22) | _BV(CS21) | _BV(CS20); // prescale by 1024
    OCR2A = 0xFF;
    TIMSK2 = _BV(OCIE2A);
    // start the timer
    interruptCount = 0;
    start = micros();
    interrupts();
}

void loop(){
    // read interrupt count into a local variable atomically
    noInterrupts();
    uint16_t localCount = interruptCount;
    interrupts();
    uint32_t time = micros() - start;

    // time elapsed
    Serial.print(time);
    Serial.print(" ");

    // number of times the interrupt handler fired
    Serial.print(localCount);
    Serial.print(" ");

    // average number of microseconds per interrupt
    Serial.print(time / localCount);
    Serial.println();

    delay(30);
}