text:
Is there any option to connect XDTouch IrTouchScreen to Arduino?
Is there any option to connect XDTouch IrTouchScreen with USB interface or RS232 to Arduino board?
At the cable of this touchscreen i have something like at the photo.
At the top of the photo pins (+, t, r, -) from touchscreen to SP232EEN, and at the bottom of photo pins (+, D-, D+, -) from CY7C63803-SXC module to USB output.

Looks like your touch screen may talk RS-232. It uses the SP232EEN (a MAX232 clone) to interface with an MCU (Cypress CY7C63803) to get USB.
Connect wires to T1 IN and R1 OUT (I assume it's on channel 1) to your Arduino for UART communication. You would most likely need to disconnect those pins from talking to the Cypress chip, or they will interfere. Use the +5V and GND pins of the USB interface to power it direct from the Arduino.
Alternatively cut that board off and use a cheap MAX232 interface board to connect to the Arduino - that may be cheaper.  T and R are TX and RX (though from which PoV is anyone's guess).

Thanks for Your reply. I disconnect board from cable and I connect to FTDI RS232 module via RX and TX wire.
Red(+) ------>  5V FTDI module,
Blue(T) ------>  RX FTDI module,
Yellow(R) ------>  TX FTDI module,
Black(-) ------>  GND FTDI module
And when I touch touchscreen in response I get weird data.
I checked response at all popular baudrate and nothing.

Example response from touchscreen on 9600 baud example response

Your typical FTDI board ISN'T RS-232. It's UART. RS-232 uses inverted NRZ high voltage (10V) logic and RISKS DAMAGING YOUR FTDI BOARD. DISCONNECT IT NOW.  You need a MAX232 BASED BOARD LIKE I STATED IN MY ANSWER

Ok I see. I bought MAX232EPE 5V and i connect to touchscreen like in this schema and FTDI connect to my computer. Is this connection is ok? I'm asking because I'm afraid I can break something.

If the MAX232EPE you have is an entire module with the required boost capacitors etc then yes, that is fine. If it's just a bare chip you will need more components to get it to work.


text:
Unable to flash Arduino when TXD pin of HC-6 Bluetooth module is connected to Arduino RXD pin?
Unable to flash Arduino when TXD pin of HC-6 Bluetooth module is connected to Arduino RXD pin?
I get the following error:

Flashing with command:C:/Users/home/.arduino-create/arduino/avrdude/6.3.0-arduino9/bin/avrdude.exe -CC:/Users/home/.arduino-create/arduino/avrdude/6.3.0-arduino9/etc/avrdude.conf -q -q -patmega328p -carduino -PCOM4 -b57600 -D -Uflash:w:C:/Users/home/AppData/Local/Temp/arduino-create-agent051272951/sketch_jun10a.hex:i
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x48

Most* Arduino devices are flashed through a bootloader which communicates over the serial pins. If you've connected another device to those pins, that communication may fail. You may need to disconnect the device while you flash the Arduino.
(*: The exceptions are the 32u4-based devices, like the Leonardo and Micro. These communicate directly over USB.)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
I want to control a single DC motor with an Arduino. Why would I use an Arduino motor shield as opposed to an H-circuit and a MOSFET?
I'm new to electronics. I'm trying to build something that will involve controlling the direction of rotation of a DC motor. A lot of online resources seem to recommend using an Arduino motor shield. But why shouldn't I just use some combination of an H-circuit (to control the direction of rotation) and a MOSFET (to switch power to the motor on and off)?

You can use the H-circuit (and even use it to switch the power on and off), nothing wrong with that, but you have the potential for more errors that way which is probably why the recommendations are to use a pre-built solution

I was just about to edit to my question to also ask if an H-bridge by itself would be enough. I just drew a little circuit diagram that made me think it would be. Thanks for your response.

Using a shield is more convenient since it should just work. Especially for beginners it is frustrating if things do not work as expected and debugging that takes some experience (which you don't have). You can always build your own MOSFET based circuit for that if you like at a later stage when you have more experience.

@Bimpelrekkie I hear what you're saying, but I don't see how using an H-bridge would be difficult (unless the H-bridge was malfunctioning somehow). Maybe I just don't know enough. Thanks for the warning.

Isn't the Arduino "motor shield" one or more H-bridges with drivers? In other words, your two choices are essentially identical. What do you see as the difference?

@DaveTweed Good question. What I see as the difference between an H-bridge and an Arduino motor shield may not be an accurate reflection of the actual differences between those two items. Here are the main differences I perceive (although I may be mistaken): cost, size, and complexity. The Arduino motor shields seem to me to be more expensive, larger, and more complex than an H-bridge. And I wonder what else might be different. If I'm wrong, or if I'm not considering something important, please help me to understand.

The heart of the Arduino Motor Shield is an L298 dual full bridge driver IC. It also has indicator LEDs, current sense amplifiers and a bunch of connectors that you might not need. If you don't need the extras and price is an issue then you could get a basic L298 driver board such as this:- http://www.ebay.com/itm/New-Dual-Channel-Motor-Driver-Shield-L298P-DC-Stepper-Driver-Board-For-Arduino-/292039557649?hash=item43feea0211:g:fRAAAOSwTuJYs4k3

@BruceAbbott - perhaps the original motor shield, but the newer better designs use FET drivers rather than the lossy, antiquated L298/L293.

Thank you @ChrisStratton and Bruce Abbott. I appreciate your discussion about the specific technology used in Arduino motor shields. I will look more into FET drivers.

@lostinthecloud - compare for example the Adafruit Motor Shield v2 to generic older bipolar designs from them, Arduino itself, etc.  This is particularly important if you plan to use batteries.

The major benefit to using a shield vs building the same circuit yourself is convenience. Assuming that your circuit is identical to the circuit on the shield then they should both work in an identical manner (barring any minor variations due to the quality of solder joints or circuit paths). The nice thing about the shield is it is almost plug and play. It has the same footprint as the Arduino and you don't have to design and assemble the circuit on a perf board. Generally, you will end up with fewer wire leads running around making for a cleaner assembly and easier prototyping.

Thank you for your response. I appreciate your points about convenience and fewer wire leads.

A Arduino motor shield is just a H-bridge (plus some other bits), but it's a H-bridge that works.
Drawing a H-bridge and a MOSFET is easy. Building one that works is much harder. Online resources recommend the shield because trying to walk someone through the development of a functional equivalent is complex.

Sure, but the fair comparison is to an H-bridge IC on a shield, and the same IC on a smaller generic or custom board.

Thank you @ChrisStratton for your comment that helps to clarify Heath's posted answer. I am very new to electronics and statements such as "an Arduino motor shield is just an H-bridge" have the potential to confuse me.

Heath's point is that building an H-bridge out of four discrete FETs (or less preferably bipolar transistors) is a lot harder to get right than using a bridge IC.  Generally one would only do it when trying to handle very high currents, or perhaps in a few cases of extremely high production volume if that looked cheapest.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
SIM800C developer board "SIM not inserted"
I bought this SIM800C development board (vendor unknow):

I conected it to an Arduino and put a brand new SIM card in it. This is the model of SIM I'm using:

Problem is, development board doesn't detect SIM card:
at+cfun=1,1
OK
at+cpin?
+CME ERROR: SIM not inserted
at+csmins?
+CSMINS: 0,0

This is the scenario:

6 pin SIM in a 6 pin SIM card holder.
SIM works fine in a cel phone. Send/receive voice call/sms.
Older, working SIM from various providers doesn't get detected either.
Every other non-SIM related aspect works.
No reboots, no flickering.
Board takes care of regulating voltages and signal levels.

I put an oscilloscope probe on the SIM_VDD pin (against board ground) and got this on every power-on:

Two 1.8v and two 3v pulses. That's all.
Please, note that I have no access to all SIM connexions (multi layer PCB).
How do I solve this problem?

In this project I'm using a nodeMCU for green-house control and a SIM800C for remote access. This is very IoT to me.

And only people in the IoT field have real experience with SIM800C fails.

How are you powering the board?

You might ultimately have IoT plans, but your question has nothing to do with IoT.  And the idea that only IoT people have awareness of this is absurd beyond reason.

@TisteAndii. The board is powered with a 10V - 1.5A power supply. Yes, it is less than 2A, but I'm not transmitting or receiving anything.

Best you try with a 2A supply to rule out the possibility that your supply cant yield enough current. Maybe pass the 10V supply through a buck first. Your SIM looks like it was shut off from power after initial attempts to power it failed.

The print on the PCB and product description at sellers site states it is GSM/GPRS board. The  module on the board comes from SIMCom. This particular SIM800 module seems to have following capabilities as per SIMCom:

Compliant to GSM phase 2/2+
GPRS multi-slot class 12/10
Quad-band 850/900/1800/1900MHz

I think at the best you can only use a 2G SIM card on this board. Any 3G/4G SIM will not work.
Thanks for those images in the problem description, it gave me relevant keywords to search.

I tested with an old SIM (no 2G, 3G or 4G marking ), circa 2007, and same result.

According to several Internet sources, you can mix 2G/3G/4G SIM cards with 2G/3G/4G cel phones. I think the same apply to this board.

@LookAlterno, here's the generally supported combinations.
4G phone supports 4G/3G/2G SIM.
3G phones support 3G/2G SIM.
2G phones support only 2G SIMs.
Backward compatibility is the norm. The cellular modems are built to be backward compatible.

This is a hardware problem.
We have experience the same issue in the company I'm working for and after a short discussion with a SimCOM Engineer we conclude it was a soldering issue. The problem may lies in the PCB or inside the SimCOM module. In both cases some part/parts are not soldered or the solder contact is broken. If the problem is outside you may fix it by inspecting the parts. If it is inside the SimCOM module there are very little you can do with the usual tools.
Just to be clear I quote a little bit of the discussion
Original question to SimCOM:

A)We apply a zero pulse to PWR-key pin as you can see in the channel-1(yellow line)
and immediately the SIM800c module wakes up, the net and status led pins
become active (one led on the other blinks).

B) After a short time <1.5sec the SIM800c deploy a signal to SIM_VDD pin
(channel-2 - blue line)

Now in some boards the SIM_VDD pin goes to 1.8V as it appears in the
first of the 4 pulses and stay there. This situation is true if there is
a SIM card in the slot and the SIM800c is working properly. In that case
we can proceed and register to the network, send SMS etc...

In some boards though, as you can see in the screenshots, the SIM800
seams not to recognize the SIM card and tries again with 2 more pulses in
3V and one last one in 1.8V. The behavior is like there is no SIM-card in
the slot. Just to be clear. The SIM card is the same in all tests.
VBAT=3.9V, SIMVDD produced fine at 2.8V etc... The boards are identical
and no further code with AT commands is running.

Quite final answer from SimCOM:
It must be a soldering issue then. Did they followed recommended Solder
Reflow Profile?
https://www.elecrow.com/download/SIM800C_Hardware_Design_V1.02.pdf page 46

Please ask them where they measured signal from the scope pictures. From
the SIM card pins? If no, can they repeat that on them and send pictures.

This happened to me too with a SIM808 module on my own PCB. I would get those same 4 pulses on SIM_VDD and then nothing. I got the same +CME ERROR: SIM not inserted error with any AT command that had to do with the SIM card.
After futzing for wayyy too long, it turned out I had soldered the SIM slot on backwards! I am using the SIM8051-6-0-14-01-A holder and it has locating pins, but they're symmetrical. As a result, my SIM card was connected backwards and wasn't working.
Flipping it around fixed everything. Good luck!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
mega2560- Interrupts reading digital input
Hi I am very new to Arduino, with very little programming experience.
I am using mega 2560 and trying to understand how interrupt works.
I have a code written, it is very similar as the example code Memsic2125, so i am gonna use that in here.
For my case, I am reading from my hardware, 5x5 array of sensors.
What I would like to do is to have it --   print out x and y using interrupts   , I want to print outputs the x and y every 10ms. Instead of printing it continuously right now.
I will be sending it out in 16 bits. I tried some other example and read a lot of material. but still couldn't get it to work.
Any idea, suggestion, help, comment is appreciated.

const int xPin = 2;
const int yPin = 3;

void setup() {

  Serial.begin(9600);
  pinMode(xPin, INPUT);
  pinMode(yPin, INPUT);
}

void loop() {

  int pulseX, pulseY;

  int x, y;

  // read pulse from x- and y-axes:
  pulseX = pulseIn(xPin, HIGH);
  pulseY = pulseIn(yPin, HIGH);

  x= ((pulseX / 10) - 500) * 8;
  y= ((pulseY / 10) - 500) * 8;

  // print x,y
  Serial.print("x,y= ( ");

  Serial.print(x);   Serial.print(,);
  Serial.print(y);   Serial.println(")");

  delay(100);
}

You are already printing every ~100 ms.

You can’t truly have an interrupt within the code (it’s a hardware thing) but you can simulate an interrupt through an ISR which you don’t have

There isn't any interrupt code in what you posted. What exactly is the problem?  One important note is that you shouldn't try to print to Serial line in the interrupt handler as serial is itself driven from interrupts which are switched off during your handler code.  If all you really want to do is to print something every 10ms then you don't need any interrupt.  Just use the "Blink Without Delay" style of timing and keep the other code from blocking.

The simplest would-be to read the data and loop around for your desired time.
Alternatively, time stamp the events and onkybread the data if the desired time has elapsed.
Or to use a timer interrupt for that.

What does  “onkybread the data” mean?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Serial Communication between ESP8266 and Arduino Uno
I want to send data from arduino to ESP8266. I have done all the RX and TX connections.
The problem is that data is not sent every second, it stops after a single byte. When I remove the arduino cable then data is read.
My Arduino Code :
void setup() {
    Serial.begin(9600);
}

void loop() {

    Serial.write("50");
    delay(1000);
}

My ESP8266 Code :
void setup() {

Serial.begin(9600);

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  while (WiFi.status() != WL_CONNECTED) {

    delay(500);
  }
  Serial.println("Connected !");

}

void loop() {

 Serial.print(Serial.readString());

}

Since you are  Arduino Uno, it has only one Serial. This Serial can be used to transmit data in USART mode to another Serial Device as well as see any Debug data in the Serial terminal.
However, both the functionality can not be used simultaneously. The Tx Rx pair of Arduino can be connected to one pair of other device i.e. either to the computer via the cable or to the Tx Rx of ESP8266.
But if you really need to plug in the Uno to the computer and send data to ESP8266 simultaneously, then you have to use SoftwareSerial library to convert any digital pin to Tx Rx pin, and connect them to ESP8266 for transmitting data.

As explained by goddland_16. Using Software Serial library will solve the issue. Code is given below. By Initializing other digital pin as communication pin, Interupption between Tx and Rx and to ESP8266 is seperated.
Arduino UNO / Nano Code :
/*
 * bismillah hir rahman nir raheem
 * UNO/Nano = Pin 7 & Pin 8
 * Note: Uno and ESP8266 cross connection
 */

#include <SoftwareSerial.h>

SoftwareSerial ArduinoUno(7,8);
String f;

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

void loop() {
    float i = (random(100) + 1);
    float j = (random(100) + 1);

    f = String('H') + String(i) + String('T') + String(j);
    ArduinoUno.println(f);
    delay(2000);
}

ESP8266 Code :
/*
 * bismillah hir rahman nir raheem
 * ESP8266 = Pin D7 & Pin D8
 * Note: Uno and ESP8266 cross connection
 */

#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>

SoftwareSerial NodeMCU(D7,D8);

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

    pinMode(D7,INPUT);
    pinMode(D8,OUTPUT);
}

void loop() {
    String content = "";
    char character;

    while (NodeMCU.available()) {
       character = NodeMCU.read();
       content.concat(character);
    }

    if (content != "") {
        Serial.println(content);
    }

    Serial.println("Temperature");
    Serial.println(content.substring(1, 6));
    Serial.println("Humidity");
    Serial.println(content.substring(7, 12));
    delay(2000);
}

Hi and welcome to the Arduino Stack Exchange. Please improve your answer by explaining to everyone what your code does and how it fixes the problem.


text:
Power a Raspberry Pi 3 from an Arduino Uno
I would like to power my Raspberry Pi 3B using an Arduino Uno.
I have been able to do this by connecting the 5v on the Arduino to the 5 V on the Pi and connecting the GND to GND, and the Pi turns on. But I get a constant under voltage sign.
How can I get the Arduino to output the right amount of power (5 V and 2.5 A)?

Neither Arduino nor RPi can produce electricity, so "powering one using the other" isn't representative of what's happening. You're powering both using whatever power supply you have, and the evidence is that it's not enough.

You can't.
The on-board regulator of the Uno, the NCP1117, is only able to supply up to 1A before starting to dropout voltage (hence your undervoltage warning).
Even worse, because the NCP1117 lacks a proper heatsink, it will probably start dropping out voltage before reaching 1A, due to its internal thermal shutdown protection.

If you are using PC USB, your total current cap is <500mA. Arduino + Pi + accesories is exceed this cap.
Use an adapter for Arduino. Ardiuno will suck up some current and rest can flow to Pi or whatever else is there.
Arduino has a linear voltage regulator. Try not to use >5v adapters. Voltage regulator will generate more heat as more current pass.

Could you give me an example of the type of adaptor needed?

This 5V adapter would be good. Connect the output to both 5V pins in parallel.  https://www.mpja.com/5-Volt-DC-Plug-Power-Supply-4A-Regulated/productinfo/18520+PS/

If you reverse which board gets the power adapter you should be able successfully power them both from a single 5V 2.5A power supply.
Connect the power adapter to the Raspberry Pi3 and power the Arduino from the Pi's 5V pin.  The Uno should only draw about 200mA @ 5V from the Pi (depending on everything else you have connected).


text:
My Arduino code will not compile, when I can't see anything wrong with it
It keeps on giving me the error:
Error compiling for board Arduino/Genuino Mega or Mega 2560.

Other sketches work fine, but this one will not compile, even though I have all the libraries.
Here is the link for the code:
https://drive.google.com/open?id=0B3R5NMiGZ3RPSk9WS0Y1amtEYms
The full error:
Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

(.text+0x0): multiple definition of `__vector_13'

libraries\IRLibRecv\IRLibRecv.cpp.o (symbol from plugin):(.text+0x0): first defined here

d:/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.9.2/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

collect2.exe: error: ld returned 1 exit status

exit status 1 Error compiling for board Arduino/Genuino Mega or Mega
2560.

This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences.

Thank you everyone. all i had to do was get rid of the tone() function.

ps. is there a way i could still use it?

Link is now dead, so your question is not of much use to others. This is why it is always best to include the code in the question and not a link. If the solution was to remove the tone() function, why don't you post that as an answer, explaining why that helped fix your code?

@Greenonline This thread is almost 2 years old...

There are questions on Electrical Engineering that are 10 years old which are still useful ... I came across your question whilst looking for a solution to an issue that I'm having, but it wasn't as useful as it might have been. That's all I'm saying... :-)

What do you need help with? I haven't used arduino for a while, but I might still be some help

It was a simple compile error, I have fixed it now, thanks :-)

There are a number of issues with your code besides the actual error:

You are dividing an unsigned long by an integer which results in an unsigned long, then rounding it. Makes no sense.
You are assigning (I assume - without seeing your code I can't be sure) long constants (eg 0xFFE01F) to an integer - which overflows and whinges.

However your main problem is that you have two interrupt service routines (ISRs) for the same interrupt (vector 7). What that interrupt is I can't say, since it is different on different chips, and you don't seem able to make your mind up if you're using an Uno or a Mega (you tagged your question both for some reason). So you will have to change code and/or libraries to use different interrupts or combine the two together to use just one ISR.

should i change the int 'heldDown' to a long?

Yes. Better still, uint32_t.

what is uint32_t. ?

and how should i fix the vector errors?

I can't see you code, but my guess is that you are passing an unsigned value into round().
millis() returns an unsigned long, this means it can never be negative, so if you test millis() >= 0 it will always be true.  That is your issue.
Write you own round function that doesn't check its greater than 0.

I don't think that's the error, it's just a warning. The real problem is in: (.text+0x0): multiple definition of `__vector_7' (link error)

just some warnings about generally unsafe/unsound code pieces.
the major issue (potentially unresolvable) is the vector-7 error. you should look into the datasheet to see what interrupt vector it is referring to first. There are more than one of such ISRs declared in your code.

how should i fix that

I searched but couldn't find an answer, then I suddenly released my Arduino external power caused this problem. When I shut down the external power I could install it in my device. I hope it works for your problem.


text:
Wire library compatibility Arduino Pro Mini - nodeMCU (I2C/TWI) problem
I'm writing PortExtender, a library to convert an Arduino Pro Mini in a port expander and I ran into what seems to be a compatibility problem between Arduino and nodeMCU: I got different answers depending on who is the master (Arduino or nodeMCU).
This is my test configuration:

At the center, the Slave Arduino, with buttons, leds, and ldr for testing pin access.
I have two master, but only one is used at a time. The inactive one is powered off and disconected from the two others. The slave get its power from the master.
I compiled and ran the same Master program in the two master, while the slave remains the same. This is the Master test program:
#include <Wire.h>
#include <PortExtender.h>

const int SLAVE_ADDRESS = 42;

PortExtender port = PortExtender(SLAVE_ADDRESS);

void setup ()
{
  Serial.begin(9600);
  delay(1000);
  Serial.println("Master");
  Serial.println("-----");

  Wire.begin();
  int r;
  do {
    r = port.reset();
    Serial.print("Resetting Port Expander. Status=");Serial.println(r);
    delay(100);
  } while(r != SLAVE_ADDRESS);
}

void loop() {
}

The test just sent a soft-reset to the slave. The slave answers with its own address (42), just to check that the command works.
Master 1 execution
This is the correct result from Master 1 (Arduino Pro Mini):

In fact, I can run a complete test suit with no problems, testing the button, controlling the LED and reading the LDR.
Master 2 execution
This is the result from Master 2 (nodeMCU):

Response is some random value that change from run to run. Slave, however, receive the command and return the right response, as checked thru Serial Monitor connected to the slave.
Everything seems to work fine, but answer from slave looks like it changed "in the wire".
PortExtender library code
The relevant methods involved are:
int PortExtender::reset() {
    return send(CMD_RESET);
}

int PortExtender::send(byte cmd) {
    Wire.beginTransmission(slave);
    Wire.write(cmd);
    Wire.endTransmission(false); // Also tested with true.
    return readAnswer();
}

int PortExtender::readAnswer() {
    short answer;

    Wire.requestFrom(slave, sizeof(answer));
    PortExtender::read((byte*) &answer, sizeof(answer));
    return (int) answer;
}

void PortExtender::read(byte* p, int len) {
    while (len > 0 && Wire.available() > 0) {
        *p++ = Wire.read();
        len--;
    }
}

Arduino ints are 2 bytes, nodeMCU ints are 4 bytes. Data from slave is send as short (Arduino, 2 bytes), received as short (nodeMCU, 2 bytes) and then promoted to int (nodeMCU, 4 bytes).
PortExtender.h
#ifndef PortExtender_h
#define PortExtender_h
/*
 *
 */
#include <Arduino.h>
#include <inttypes.h>

#define NO_CMD             0
#define CMD_DIGITAL_WRITE  1
#define CMD_DIGITAL_READ   2
#define CMD_ANALOG_WRITE   3
#define CMD_ANALOG_READ    4
#define CMD_PIN_MODE       5
#define CMD_SET_WATCHDOG   6
#define CMD_START_WATCHDOG 7
#define CMD_STOP_WATCHDOG  8
#define CMD_RESET          9
#define CMD_PLAY          10
#define CMD_PLAY_STEP     11
#define CMD_DEBOUNCE      12
#define CMD_TONE          13
#define CMD_TONE_LEN      14
#define CMD_NO_TONE       15

#define ERROR_NO_RESET    -1
#define ERROR_PARAMETER   -2

struct PAR_TONE {
    byte pin;
    unsigned int freq;
};

struct PAR_TONE_LEN {
    byte pin;
    unsigned int freq;
    unsigned long len;
};

class PortExtender
{
  private:
      short slave;
      int send(byte* b, int len);
      int send(byte cmd);
      int send(byte cmd, byte arg1);
      int send(byte cmd, byte arg1, byte arg2);
      int readAnswer();

  public:
      PortExtender(int slaveAddress);

      /*
       *     All same as Arduino, except as noted.
       */
      int pinMode(int pin, int mode);
      //    Set debouncer.
      int debounce(int pin, short debounce);

      int digitalWrite(int pin, int value);
      int digitalRead(int pin);
      int analogWrite(int pin, int value);
      int analogRead(int pin);
      int tone(int pin, unsigned int freq);
      int tone(int pin, unsigned int freq, unsigned long len);
      int noTone(int pin);

      /*
       * Watchdog functions
       */
      //    Designate the output pin and watchod parameters.
      int setWatchdog(int pin, unsigned long time, unsigned long pulse);
      int startWatchdog();
      int stopWatchdog();

      /*
       *    Timed switching of a pin, with a giving set of intervals.
       */
      int play(int pin, unsigned int score[]);

      /*
       *    Reset Port Extender.
       */
      int reset();
      static void read(byte*, int len);
};

#endif

Slave PortExtender (Arduino Pro Mini)
This is work in progress. Digital/Analog read/write completed, other methods (play, watchdog and tone still to be tested).
/*
   Programable Port Extender by Look Alterno.

   Convert your Arduino in a I2C slave that extends
   the number of pin for your master Arduino.

   Your master Arduino will be able to:
   - Read/Write digital/analog pins.
   - Program one-shot pulses of any length.
   - Program PWM with arbitrary period and duty cycle.

   Applications:
   - Make timers for external appliances.
   - Implement watchdogs for resetting things.
*/

//  ---- Change this address to a suitable value if needed ----
#define MY_ADDRESS  42

#include <Bounce2.h>
#include <Wire.h>
#include <PortExtender.h>

//  A CMD_RESET has been received from master.
boolean bReset = false;

//  These port are programmables.
struct {
  byte pin;
  byte exp;
} pins[] = {{2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}, {7, 0},
  {8, 0}, {9, 0}, {10, 0}, {11, 0}, {12, 0}, {13, 0},
  {A0, 0}, {A1, 0}, {A2, 0}, {A3, 0}
};

const short nPins = sizeof(pins) / sizeof(pins[0]);

struct {
  Bounce debouncer;
  short pin;
  short interval;
} debouncer = {Bounce(), 0, 0};

#define WD_NORMAL 0
#define WD_PULSE  1

struct {
  int pin;
  int state;
  boolean active;
  unsigned long lastBeat;
  unsigned long time;
  unsigned long pulse;
  unsigned long wait;
  unsigned long startPulse;
} watchdog;

#define SCORE_MAX_STEP 50
struct {
  boolean active;
  int pin;
  unsigned long time; // start time of current step.
  int freeStep;       // for filling the array.
  int currentStep;    // for playing the array.
  unsigned int step[SCORE_MAX_STEP];
} score;

typedef void (*fcnptr)();

void cmdBeat();
void cmdDigitalWrite();
void cmdDigitalRead();
void cmdAnalogWrite();
void cmdAnalogRead();
void cmdPinMode();
void cmdWatchdog();
void cmdStartWatchdog();
void cmdStopWatchdog();
void cmdReset();
void cmdPlay();
void cmdPlayStep();
void cmdDebounce();
void cmdTone();
void cmdToneLen();
void cmdNoTone();

struct {
  byte  cmd;
  fcnptr fcn;
} commands[] = {
  { NO_CMD,             cmdBeat},
  { CMD_DIGITAL_WRITE,  cmdDigitalWrite},
  { CMD_DIGITAL_READ,   cmdDigitalRead},
  { CMD_ANALOG_WRITE,   cmdAnalogWrite},
  { CMD_ANALOG_READ,    cmdAnalogRead},
  { CMD_PIN_MODE,       cmdPinMode},
  { CMD_SET_WATCHDOG,   cmdWatchdog},
  { CMD_START_WATCHDOG, cmdStartWatchdog},
  { CMD_STOP_WATCHDOG,  cmdStopWatchdog},
  { CMD_RESET,          cmdReset},
  { CMD_PLAY,           cmdPlay},
  { CMD_PLAY_STEP,      cmdPlayStep},
  { CMD_DEBOUNCE,       cmdDebounce},
  { CMD_TONE,           cmdTone},
  { CMD_TONE_LEN,       cmdToneLen},
  { CMD_NO_TONE,        cmdNoTone}
};

unsigned long now = millis();
byte  lastCommand;
short answer;

void setup() {
  Serial.begin(9600);
  Serial.println("--- Port Extender ---");

  initAll();
  Wire.begin(MY_ADDRESS);
  Wire.onReceive(receiveCommand);
  Wire.onRequest(sendAnswer);
}

void loop() {
  now = millis();

  checkDebouncer();
  checkWatchdog();
  checkPlay();
}

void checkDebouncer() {
  debouncer.debouncer.update();
}

/*
   Start playing a score on pin.
   The pin start at the last value set by master (HIGH or LOW)
*/
void startPlay() {
  noInterrupts();
  score.active = true;
  score.time   = millis();
  score.currentStep = 0;
  digitalWrite(score.pin, !digitalRead(score.pin));
  interrupts();
}

void checkPlay() {
  noInterrupts();

  if (score.active) {
    unsigned long stepEnd = score.time + score.step[score.currentStep];

    if (now >= stepEnd) {
      score.currentStep++;

      if (score.currentStep >= score.freeStep) {
        score.active = false;
      } else {
        digitalWrite(score.pin, !digitalRead(score.pin));
        score.time = now;
      }
    }
  }

  interrupts();
}

/*
   Each if is time to reset the master.
   After resetting the master, soft-reset the slave.
*/
void checkWatchdog() {
  if (watchdog.active) {

    switch (watchdog.state) {
      case WD_NORMAL:
        if (now - watchdog.lastBeat > watchdog.time) {
          pinMode(watchdog.pin, OUTPUT);
          digitalWrite(watchdog.pin, HIGH);
          watchdog.startPulse = now;
          watchdog.state = WD_PULSE;
        }

        break;

      case WD_PULSE :
        if (now - watchdog.startPulse > watchdog.pulse) {
          digitalWrite(watchdog.pin, LOW);
          cmdReset();
        }

        break;
    }
  }
}

/*
    Receive a command from Master
*/
void receiveCommand(int howMany) {
  lastCommand = Wire.read();
  //  Serial.print("command="); Serial.println(lastCommand);
  answer = 0;

  if (!bReset && lastCommand != CMD_RESET) {
    //  The first command received must be a CMD_RESET.
    answer = ERROR_NO_RESET;
  } else {
    fcnptr f = commands[lastCommand].fcn;
    f();

    watchdog.lastBeat = now;
  }
}

  // called by interrupt service routine when outgoing data is requested
  void sendAnswer() {
    Wire.write((byte *) &answer, sizeof(answer));
    lastCommand = NO_CMD;
  }
  void cmdBeat() {
  }

  void cmdReset() {
    //  Make a soft reset.
    initAll();
    bReset = true;
  }

  /*
     Initialize all variables and pins.
  */
  void initAll() {
    score.active = false;
    watchdog.active = false;
    debouncer.pin = -1;

    int size = sizeof(pins) / sizeof(pins[0]);

    for (int i = 0; i < size; i++) {
      int pin = pins[i].pin;
      pinMode(pin, OUTPUT);
      digitalWrite(pin, LOW);
    }

    answer = MY_ADDRESS;
  }

  void cmdPinMode() {
    if (Wire.available() == 2) {
      byte pin = Wire.read();
      byte val = Wire.read();
      pinMode(pin, val);
    }
  }

  void cmdDebounce() {
    if (Wire.available() == 2) {
      byte pin = Wire.read();
      byte val = Wire.read();
      debouncer.pin = pin;
      debouncer.interval = val;
      debouncer.debouncer.attach(pin);
      debouncer.debouncer.interval(val);
    }
  }

  void cmdDigitalWrite() {
    if (Wire.available() == 2) {
      byte pin = Wire.read();
      byte val = Wire.read();

      digitalWrite(pin, val);
    }
  }

  void cmdDigitalRead() {
    if (Wire.available() == 1) {
      byte pin = Wire.read();

      if (pin == debouncer.pin) {
        answer = debouncer.debouncer.read();
      } else {
        answer = digitalRead(pin);
      }
    }
  }

  void cmdAnalogWrite() {
    if (Wire.available() == 2) {
      byte pin = Wire.read();
      byte val = Wire.read();

      analogWrite(pin, val);
    }
  }

  void cmdAnalogRead() {
    if (Wire.available() == 1) {
      byte pin = Wire.read();

      answer = analogRead(pin);
    }
  }

  void cmdTone() {

  }

  void cmdToneLen() {

  }

  void cmdNoTone() {
    if (Wire.available() == 1) {
      byte pin = Wire.read();
      noTone(pin);

    }
  }

  void cmdPlay() {
    if (Wire.available() == 1) {
      score.active = false;
      score.pin = Wire.read();
      score.freeStep = 0;
    }
  }

  void cmdPlayStep() {
    unsigned int val;

    if (Wire.available() == 2) {
      val = Wire.read() << 8 | Wire.read();

      if (val > 0) {
        Serial.print("val=");
        Serial.println(val);
        score.step[score.freeStep++] = val;
      } else {
        startPlay();
      }
    } else {
      answer = ERROR_PARAMETER;
    }
  }

  void cmdWatchdog() {
    PortExtender::read((byte *) &watchdog.pin, sizeof(watchdog.pin));
    PortExtender::read((byte *) &watchdog.time, sizeof(watchdog.time));
    PortExtender::read((byte *) &watchdog.pulse, sizeof(watchdog.pulse));
    watchdog.active = false;
  }

  void cmdStartWatchdog() {
    watchdog.active = true;
  }

  void cmdStopWatchdog() {
    watchdog.active = false;
  }

  int searchPin(int pin) {
    int i = 0;

    while (i < nPins && pins[i].pin != pin) {
      i++;
    }

    return (i < nPins) ? i : -1;
  }

The question
What is going wrong here?

Please show a working sketch with a complete PortExtender.h and the code of the slave. I can not recognize a pattern: 22272 = 0x5700 = 0b0101.0111.0000.0000, 47 = 0x2A = 0b0010.1010. You don't even know if you are reading something at all. Could you test if Wire.available is not zero ?

@Jot. Remember: an Arduino Master can control LED, read buttons, read analog input, but nodeMCU fails.

Thanks. You should add that test to check if Wire.requestFrom actually received some bytes. Does the nodeMCU support I2C clock pulse stretching ? The Slave code working with the Arduino as Master does not matter. The code could have some details that makes the nodeMCU fail. The slave code does not set 'lastCommand' and 'answer' as volatile and the interrupt routine 'receiveCommand' can be long. If the nodeMCU does support I2C clock pulse stretching does it allow a very long stretch by the Slave 'receiveCommand' code ? Do you have a logic analyzer ?

@Jot. I added "volatile". Same result. And reset() is short and fixed-time. I printed requestFrom() and available() and both returns "2". And clearly the slave is receiving the requestFrom() because it's executing the callback. I don't have a logic analyzer.

I can not pinpoint the problem. The 0x5700 is very suspicious, there must be something in it. What is the Endian Byte Order for Arduino and nodeMCU ? Is everything running at 3.3V ? A 5V Arduino board needs 3.5V on the I2C bus to see it as a valid high. My best advice is to add more tests. For example send in the slave 0x33 instead of 'answer'. Check in the master the error return of Wire.endTransmission. And so on.

@jot. port.reset() return a random value (different in each run). nodeMCU and Arduino Pro Mini are both 3.3v. I also tested with master and slave both connected to USB for power. In first iteration, commands like reset() returns byte, but it also fails. Wire.endTransimission() works, because slave did receive the command and executed it, and, yes, I also checked the return code and it was OK.

How random is random ? Is the lower byte always zero ? It could be a bug in the ESP8266 Wire library, then you need a logic analyzer.

Hardware problem!
The nodeMCU I'm using fails (mostly resets and garbage in the Serial Monitor) when inserted in the breadboard. That is. Them run OK when I let them just hanging from the USB cable.
I tested two of them in different breadboards. I also tested the breadboard for shorts and failed connections with an ohmmeter.
These are culprits:


text:
SPI Arduino communication
I want two Arduino cards to communicate with each other using SPI and move the servo motor with potentiometer as a result. I've done the pre-burning led or the led burning led on the SPI, I am waiting for your help. I will give the code below.
MASTER Arduino code
#include <SPI.h>
/* SPI haberleşmesinde Master olarak görev yapan Arduino kodu */
const int pot=A0;   // Servo kontrol potunu bağlayacağımız analog giriş.
int potdurum=0;
int pos = 0;
const int SSpini = 8;
/* Slave görevindeki Arduino'nun seçilmesi için 8 bumaralı pin SS olarak belirlendi */

void setup()
{
  Serial.begin(9600);
  pinMode(SSpini, OUTPUT);
  /* SS pini çıkış olarak ayarlandı */
  digitalWrite(SSpini, HIGH);
  /* Slave olan Arduino başlangıçta haberleşmeye geçmemesi için SS pini HIGH yapıldı */
  SPI.begin();
  /* SPI haberleşmesi başlatıldı */
}

void loop()
{
  potdurum=analogRead(pot);
  pos= map(potdurum,0,1023,0,180);//Pottan okunan değeri  180e oranlıyoruz.
  veriGonder(pos,SSpini);
}

/* SPI üzerinden veri göndermek için yazılmış fonksiyondur */
void veriGonder(int veri, int SSpini)
{
  digitalWrite(SSpini, LOW);
  /* Diğer Arduino'nun veri dinlemeye başlaması için SS hattını LOW düzeyine çekmeliyiz */
  delay(1);
  /* Kısa bir süre bekleyelim */
  Serial.print("Aci Degeri = ");
  Serial.println(veri);
  delay(15);
  SPI.transfer(veri);
  /* veri karakteri diğer Arduino'ya yollandı
  * Fonksiyon diğer arduino'dan gelen veriyi vermektedir
  * Geri gelen veri LEDDurumu değişkeninde tutulmuştur
  * Bu değişken Seri port üzerinden bilgisayardaki Serial monitöre yollanmıştır
  */
  digitalWrite(SSpini, HIGH);
  /* Haberleşmeyi bitirmek için pin LOW konumuna çekilmiştir */
}

SLAVE Arduino code
#include <Servo.h>
int i = 0;
Servo myservomotor;

void setup()
{
  Serial.begin(115200);
  myservomotor.attach(3);
  pinMode(MISO, OUTPUT);
  pinMode(SS , INPUT);
  /* MISO pini OUTPUT, SS pini INPUT olarak ayarlandı */

  SPCR  |= 0b11000000;
  SPSR  |= 0b00000000;
  /* Slave mod ve interrupt için ayarlamalar yapıldı */

  sei();
  /* Interruptlar çalıştırıldı */
}

void loop()
{
}

/* SPI kesmesi olduğunda çalışacak fonksiyon */
ISR(SPI_STC_vect)
{
  cli();
  /* Interruptlar durdurulmuştur */
  while(!digitalRead(SS))
  {
      SPDR = i;
      i ++;
      if ( i > 255)
        i = 0;
      while(!(SPSR & (1 << SPIF)));
      /* SPI hattında veri aktarımı bitene kadar bekle */
      int gelenVeri;
      gelenVeri = SPDR;
      myservomotor.write(gelenVeri);
      Serial.print("Aci Degeri Slave= ");
      Serial.println(gelenVeri);
      delay(15);

//      if(gelenVeri == 'a'){
//        digitalWrite(SERVO,HIGH);
//      }else if(gelenVeri == 'b'){
//        digitalWrite(SERVO,LOW);
//      }
      /* SPI üzerinden gelen verinin değerine göre LED'in konumu değiştirildi */
  }
  sei();
  /* Interruptlar başlatılmıştır */
}

What's your question?

The basic error is too much code in the SPI ISR. Focus on capturing the SPI value and then flag to the loop() function that a new value is available. Avoid delay and serial print in ISRs.

@LookAlterno - this site requires posts and comments to be in English, thanks.

I am waiting for your help. - for what, exactly?

/* SPI kesmesi olduğunda çalışacak fonksiyon */
ISR(SPI_STC_vect)
{
  cli();
 ...
      Serial.print("Aci Degeri Slave= ");
      Serial.println(gelenVeri);

Don't do serial prints inside an ISR.


text:
UECIDE: linker error with U8g2 library
This sketch:
#include <SPI.h>
#include <Wire.h>
#include <U8g2lib.h>

//  OLED display.
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
void setup() {
  u8g2.begin();
}
void loop() {
}

Compile OK with Arduino 1.8.3, but under UECIDE 0.8.9-pre15 fails to link, with this message:
Compiling...
• Preprocessing...
• Compiling sketch...
• Compiling core...
‣ arduino
• Compiling libraries...
‣ U8g2 [/home/look/Documents/UECIDE/libraries/U8g2]
‣ SPI [/home/look/.uecide/libraries/Communications/arduino/SPI]
‣ U8g2 [/home/look/Documents/UECIDE/libraries/U8g2]
‣ Wire [/home/look/.uecide/libraries/Communications/arduino/Wire]
• Linking sketch...
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::write(unsigned char)':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:248: undefined reference to `u8g2_DrawGlyph'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::initDisplay()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:101: undefined reference to `u8x8_InitDisplay'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::clearDisplay()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:104: undefined reference to `u8g2_ClearDisplay'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::setPowerSave(unsigned char)':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:107: undefined reference to `u8x8_SetPowerSave'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:62: undefined reference to `u8x8_ascii_next'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:62: undefined reference to `u8x8_ascii_next'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::home()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:278: undefined reference to `u8x8_utf8_init'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2_SSD1306_128X64_NONAME_1_HW_I2C':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_cb_r0'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_cb_r0'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_Setup_ssd1306_i2c_128x64_noname_1'
collect2: error: ld returned 1 exit status
Compiling Fail

Both IDEs are set for Arduino Pro Mini 3.3V 8Mhz. In UECIDE I'm using GCC 4.9.2 for AVR. I copied the same U8g2 source code to both Arduino and UECIDE own libraries directory.
U8g2 library is version 2.15.2 by Oliver, installed via Arduino IDE and copied to the UECIDE libraries directory,
The problem, so far, only happens with U8g2 and not other libraries.
How do I solve this problem?

Can you provide a link to the exact version of U8g2 library you are using?

I'm using U8g2 library version 2.15.2 by Oliver, installed via Arduino IDE and copied to the UECIDE libraries directory,

Got it.  The layout of that library is a complete mess and uses a non-standard folder layout that UECIDE doesn't like. It's simple enough to clean it up though. I'll show you how.

The layout of that library is in a non-standard format with folders that UECIDE doesn't know to look for or how to deal with.
The main culpret is the inclusion of big chunks of code in a "clib" directory (why on earth?!?!) which doesn't get included in the compilation. Then on top of that you have header files in there that are referenced both from inside it and outside it.
The simplest fix is just to copy and move the files to better locations:
$ cd ~/Documents/UECIDE/libraries/U8g2/src
$ mv clib/*.c .
$ cp clib/*.h .

Note you move the source, but copy the headers. That's to get around the problem of the headers being referenced from two locations with relative paths.
The problem stems from UECIDE having (by necessity) much stricter rules than the Arduino IDE over the layout of a library. This is to facilitate better identification and categorization of the libraries so that recursive dependency detection can take place.

But UECIDE is just applying Arduino own rules about libraries, not inventing new ones. Am I right?

Arduino IDE is very lax with its rules. UECIDE is far more strict in what rules it applies. UECIDE applies what the Arduino specifies, but because Arduino doesn't really care people don't always follow those rules. They made it more complex and woolly by adding this new library format for cross architecture libraries which is just plain nasty.

Another big part of the problem is that, because the Arduino IDE has been so flippant with its own rules those rules have actually never been strictly defined anywhere. So it's very much a "best guess" as to what should and shouldn't be done. For instance: when do you recurse a source folder and when don't you? In an old library format you mustn't, because the source folder is the root. In the newer 1.5.x format you maybe could, but should you? It's not defined.

I am working on improving the file finding routines for libraries - get it to work better for newer style libraries.


text:
How do I prevent Arduino from running on startup?
I just uploaded a sketch to my Arduino Leonardo, which presses a key on the keyboard. The code was unfortunately bugged and now as soon as the Arduino is powered on, the key is being pressed.
When I try to upload a new sketch that fixes the issue, I am unable to do so as the Arduino is executing the sketch, preventing the new sketch from being uploaded.
How can I prevent the Arduino from executing the sketch once powered on? Pressing the reset button or wiring it in does not work...

Welcome to Arduino Stack Exchange.  Please take a moment to look at the tour at https://arduino.stackexchange.com/Tour to get the most out of this site.  Meanwhile, we're going to need more info in order to help with this question.  Start with posting the code.

I no longer have the code, it presses a key as soon as the code starts... I can't upload a new sketch because of the old code executing and pressing the key...

Yeah, you said that already.  Normally you have to press the reset button and hold it until just the right instant during upload.  It usually takes several attempts to hit it just right.  From now on, code a little delay in setup for projects like this to give yourself a chance.

Releasing the reset button at the right time as @Delta_G wrote should make it work. If you enable more output for the upload in the preferences, then you should release the reset button after the polling starts. If that fails, you could burn a new bootloader into the Leonardo to stop the current sketch, but then you need a programmer.

Does this answer your question? How to stop uno from running program when powered on?

The Leonardo should wait a couple of seconds after resetting to see if a new sketch arrives.

Power off the board completely (remove the USB cable).
Hold down the Reset button, and keep it held down (or, run a jumper wire from the RESET pin to the GND pin). This stops the problem sketch from starting.
Still holding down Reset, reconnect the USB cable.
Start uploading a sketch that does not have this problem (eg. Blink)
Once the IDE reports "Uploading" release the Reset button (or remove the jumper wire).

After 6 attempts, it finally worked. Thanks mate!!


text:
Why is a delay(1) necessary before Wire.requestFrom?
I had a problem communicating an nodeMCU with an Arduino Pro Mini with I2C.
To find the culprit, I finally wrote an Echo Server in Arduino: it receives a byte and responds the same byte. In the nodeMCU I wrote a test program: it sends bytes to the Echo Server and verifies the response, in addition to any error conditions in the Wire methods.
Both processors are connected GND-GND, VCC-VCC, SDA-SDA and SCL-SCL. SDA and SCL have 10K pull-up resistors. Both are connected via USB to my PC, and I have two serial monitors to trace the execution.
In the tester program line 38 there is a delay(1). If you comment it out, some requestFrom() fails randomly with return value != 1, but the Echo Server still received the byte.
As ATmega328 included TWI in the silicon, I can't understand what is failing here and why delay(1) seems to solve the problem. What I'm missing here?
The tester program
/*
 * Echo Server Test
 * Send one byte to the Echo Server and read it back.
 * Do it for bytes from 0x01 to 0xDD
 */
#include <Wire.h>

#define SLAVE_ADDRESS  42
byte car = 1; // car to be send to the Echo Server.

void setup() {
    Serial.begin(9600);
  // We have a nodeMCU con I2C on pins D5 and D6.
    Wire.begin(D5, D6);
    delay(1000);
  Serial.println("");
    Serial.println(" Echo Server Tester");
    Serial.println("---------------------");
    Serial.println("###  Sent   Received");
    delay(1000);
}

/*
 * Send one byte in each loop().
 */
void loop() {
    byte status;

    if(car > 0) {
        do {
            Wire.beginTransmission(SLAVE_ADDRESS);
            int written = Wire.write(car);
            status = Wire.endTransmission();

            switch(status) {
            case 0:
        delay(1); // Comment this out and watch requestFrom() fails.
                if(Wire.requestFrom(SLAVE_ADDRESS, 1) == 1) {
                    byte r = Wire.read();
                    printChar(car, r);
                    car++;
                } else {
                    Serial.println("error in return");
                    status = 4;
                }

                break;

            case 1:
                Serial.println("Data too long");
                break;

            case 2:
                Serial.println("NACK on address");
                break;

            case 3:
                Serial.println("NACK on data");
                break;

            case 4:
                Serial.println("Some error");
                break;
            }
        }

        while(status != 0);
    }
}

/*
 * Utility: print in bytes sent and received
 */
void printChar(byte s, byte r) {
    Serial.print(s);
    Serial.print(" ");
    printBits(s);
    Serial.print(' ');
    printBits(r);

    if(r != s) {
    //  Mark invalid responses.
        Serial.print(" *");
    }

    Serial.println();
}

/*
 * Print a simple byte in binary
 */
void printBits(int car) {
    byte bit = 0x80;

    for(int i = 0; i < 8; i++) {
        int digit = car & bit;
        Serial.print(digit ? '1' : '0');
        bit >>= 1;
    }
}

The Echo Server program
/*
 * I2C Echo Server
 * Receive one byte from Master, echo the same byte to Master.
 */
#define MY_ADDRESS  42

#include <Wire.h>

volatile byte received;
volatile int count = 0;

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

  Wire.begin(MY_ADDRESS);
  Serial.println("--- Echo Server ---");

  Wire.onReceive(receiveCommand);
  Wire.onRequest(sendAnswer);
}

void loop() {
  static int lastCount = 0;

  if (count != lastCount) {
    Serial.print(lastCount + 1); Serial.print(" ");
    printChar(received);
    lastCount++;
  }
}

/*
 * Receive a byte from Master
 */
void receiveCommand(int howMany) {
  received = Wire.read();
  count++;
}

/*
 * Send a byte to Master
 */
void sendAnswer() {
  Wire.write(received);
}

/*
 * Utility print byte received/sent
 */
void printChar(byte car) {
  Serial.print("Char ");
  byte bit = 0x80;
  for (int i = 0; i < 8; i++) {
    byte digit = car & bit;
    Serial.print(digit ? '1' : '0');
    bit >>= 1;
  }
  Serial.println();
}

the TWI interface needs to wait a whole cycle before it requests again, otherwise the clock and buffer can get messed up.

THIS fixed my I2C problems, delay(1) I had not seen this mentioned anywhere previously, so thanks for the question and the answers as I have been going in circles why my first 2 reads worked but not my second read 2, although commenting out the first 2 reads then let the second 2 behave correctly. I will now find out the clock cycle and change delay(1) to a micros delay.

The 1 millisecond is not needed, try delayMicroseconds with 50 or maybe 20 µs.
The Arduino as a slave is totally different than for example a sensor. The Arduino as a slave uses a combination of hardware and software. The onRequest and onReceive functions are executed while the Arduino keeps the SCL line low. That is called clock pulse stretching.
With an Arduino Uno (ATmega328P microcontroller) connected to an Arduino Uno, this delay problem between a write and read on the I2C bus existed for a long time. A few years ago it was solved. It was a bug, a real bug. That delay is no longer needed.
There are still ways to make it unreliable, for example by disabling the interrupts for too long in the slave.
I read that is still exists with the Arduino Due. With the Due as a master and for example an ATmega328P (at 3.3V) as a slave, the Due still needs a delay.
The nodeMCU and the Raspberry Pi might still have some problems when an Arduino is used as a slave. The Arduino as a slave should at least run at 3.3V or a I2C level shifter should be used.
I don't know if the nodeMCU Wire library supports clock pulse stretching.
That delay might still be needed. Even then, I don't know how reliable the communication will be.
The Wire.endTransmission is the function that transmits the data (not the Wire.write). If that is followed too soon by a Wire.requestFrom and there is a bug in the Wire library, that can cause troubles.


text:
Can I get the arduino to run ESP8266 code?
So I got this water flow sensor that measures the flow of water. I also got an ESP8266 module to help me make HTTP requests.
So as far as I know, one must set the board type to Generic ESP8266 and upload a sketch that the ESP8266 runs.
However, how can I write code in such a way that when the water flow goes over say 30 Litres, it makes a GET request to the Api that alerts the user? I am not able to use both the modules in one sketch. Any possible methods?

Can you add a link to the water flow sensor? What coms method does it use or is it have an analog output? Can you show us what you have tried so far? We aren't a code writing service.

@sa_leinad I added a link to the sensor. Majenko's answer was the one I was looking for. I've got what to do now.

why do you even need the uno?

I think you have a fundamental misunderstanding of what you are working with.
There are two ways of working with an ESP8266:

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

It sounds like you are wanting to do (2) but are mistakenly trying to so (1).
Option 2 does rely on the ESP8266 having the AI Thinker AT firmware installed on the ESP8266, which most come preinstalled with. If you have uploaded code to your ESP8266 using the ESP8266 boards package that firmware will have been replaced with your code and you will need to put the original firmware back on. There's many tutorials on the web showing you how.
If you do want to program the ESP8266 directly then it's the ESP8266 that you need to program, not an Arduino. Everything will be done by the ESP8266 - the GET request, the water flow sampling, the decision making, etc. The Arduino will be relegated to your bits box where it will gather dust.


text:
Can the WiFi on ESP8266 be disabled?
I've been reading a lot on the ESP8266, but still my understanding is shaky. I have the Arduino IDE running on a PC, which uses wires to connect to the ESP8266 via a USB device (Device Manager > Ports (COM & LPT) > Silicon Labs CP210x USB to UART Bridge). This is how I uploaded a simple sketch to the ESP8266.
It works and has been installed in the wall. I'm happy and relieved to complete the project... except for one small thing: I noticed that it shows up on WiFi. I can connect to it without a password, with a "Limited" connection. After that I'm lost, but I wonder if someone who knows what they are doing can use this unsecured connection to hack my install. I'd like to disable the WiFi, if possible, since I'm not using it.
The worst part is my learning curve now starts over. I thought that when my sketch gets uploaded, it replaces the original firmware. Now "firmware" is an elusive concept. I keep thinking that it shows up on WiFi because of something running in firmware. My sketch hasn't any code for WiFi. What am I missing/do I have wrong?

Please post the code (sketch) you are running. And to turn of the WiFi use WiFi.forceSleepBegin();

@ MatsK I use the Arduino IDE to flash my esp8266, and tried adding "WiFi.forceSleepBegin();"  in the "void setup () {" section, but uploading gave an error about not being in the "scope".  So I tried Sketch > Include Library > Contributed Libraries > WiFi This time the uploading error was "'class WiFiClass' has no member named 'forceSleepBegin'" I don't know how to post the code I'm running, but I'm trying to learn how. When I do, I will post the code as per your request. Thanks

Did you #include <ESP8266WiFi.h> ?

@ Jaromanda X  Thanks so much, I had included the wrong library because I forgot to change from "Arduino Pro Mini" to  "Generic ESP8266 Module". After selecting the right board, the code uploaded without error and this seems to have solved my problem since I no longer see the esp8266 in the list of available WiFi connections. I'm still very confused as to how the WiFi got turned on in the first place, and about the question of firmware. I think I will post another question about this subject.

@ MatsK Since I  can now disable the WiFi, I don't think there is any point in posting the code. However, if you could help with my confusion about firmware I mentioned in my question, it would be most appreciated

@Ray71 It is also god if you click the up arrow to the left of the comment, that will give me credits, and that is what gives you score and motivation to answer more ;-)

To turn of the WiFi add the WiFi library and use WiFi.forceSleepBegin();

Firmware is the program/sketch that controls a MicroController Unit aka MCU (and in this case a Arduino).
Best explanation I know is here: https://en.wikipedia.org/wiki/Firmware

Many esp8266 devices by default start in (WIFI_AP) SoftAP mode, and will appear as a wifi network access point, waiting for stations to connect.
User code in any sketch, should explicitly set wifi to the appropriate mode. If you do not need wifi, set the wifi mode off. To do this with the Arduino IDE, an esp8266 must run a sketch at least once that includes the wifi class to use its .mode() method.
#include <ESP8266WiFi.h>

void setup() {
   Serial.begin(115200);
   WiFi.mode(WIFI_OFF);
   if (WiFi.getMode() == WIFI_OFF)
      Serial.println(F("\nWifi mode is WIFI_OFF, until it is explicitly changed"));
}

The mode setting persists across power on and restart/reset cycles, until user code specifies a different mode. So once run on the esp8266, the all the lines above (except setup()) could optionally be removed from subsequent sketches uploaded to the esp8266, and the wifi will remain off.
Firmware is lower-level software that runs between the hardware and your higher-level sketch. Many esp8266 came with Espressif firmware and a sketch installed.
If you are concerned about energy consumption, investigate waking up the esp8266 with the radio disabled, eg.
ESP.deepSleepInstant (microseconds, WAKE_RF_DISABLED);

You control WiFi using wifi.setmode().
ESP8266's WiFi is very versatil. You can be a client and/or an access point. You can get your IP from DHCP or static.
Per default, ESP8266 start in STATIONAP mode (as client and access point).
This is the pertinent part from the official page
wifi.setmode()
Configures the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

Station mode, where the NodeMCU device joins an existing network
Access point (AP) mode, where it creates its own network that others can join
Station + AP mode, where it both creates its own network while at the same time being joined to another existing network
WiFi off

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.
Note
WiFi configuration will be retained until changed even if device is turned off.
Syntax
wifi.setmode(mode[, save])

Parameters
mode value should be one of
    wifi.STATION for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
    wifi.SOFTAP for when the device is acting only as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
    wifi.STATIONAP is the combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local WiFi connection and connect to another WiFi router.
    wifi.NULLMODE changing WiFi mode to NULL_MODE will put wifi into a low power state similar to MODEM_SLEEP, provided wifi.nullmodesleep(false) has not been called.

save choose whether or not to save wifi mode to flash
    true WiFi mode configuration will be retained through power cycle. (Default)
    false WiFi mode configuration will not be retained through power cycle.

Returns
current mode after setup
Example
wifi.setmode(wifi.STATION);

See also
wifi.getmode() wifi.getdefaultmode()

Note: this answer refers to NodeMCU Lua code. The ideas can be used by Arduino ESP8266, but method names must be modified.

This is the best solution I have found so far (source: GitHub gist)
The two functions below are all you need to toggle your WiFi chip. The huge advantage of using these is that they work without having to invoke an ESP.deepsleep() call.
Mind you, if you have already done an ESP.deepsleep(time, WAKE_RF_DISABLED) that means that your WiFi chip has been disabled altogether, and calling WiFiOn() will NOT be able to toggle it back ON. In this case you MUST do ESP.deepsleep(time, WAKE_RF_DEFAULT). But once you WiFi chip has been re-enabled, you can call WiFiOn() and WiFiOff() as many times as you please, they will work fine.
extern "C" {
    #include "user_interface.h"  // Required for wifi_station_connect() to work
}

#include <Arduino.h>
#include <ESP8266WiFi.h>

#define FPM_SLEEP_MAX_TIME 0xFFFFFFF

void WiFiOn();
void WiFiOff();

//------------------------------------------------------------------------------

void setup() {

    WiFiOn();
    delay(5000);
    WiFiOff();
    delay(5000);
    ESP.deepSleep(1e6 * 10, WAKE_RF_DEFAULT); // sleep 10 seconds

}

void loop() {
    ;
}
//------------------------------------------------------------------------------

void WiFiOn() {

    wifi_fpm_do_wakeup();
    wifi_fpm_close();

    //Serial.println("Reconnecting");
    wifi_set_opmode(STATION_MODE);
    wifi_station_connect();
}

void WiFiOff() {

    //Serial.println("diconnecting client and wifi");
    //client.disconnect();
    wifi_station_disconnect();
    wifi_set_opmode(NULL_MODE);
    wifi_set_sleep_type(MODEM_SLEEP_T);
    wifi_fpm_open();
    wifi_fpm_do_sleep(FPM_SLEEP_MAX_TIME);

}

WiFiOff caused a crash for me. I called it from the program loop once, and it triggered a Soft WDT reset.

Note: the code in this answer relies on SDK functions, which may be unfamiliar and confusing to Arduino IDE users, especially early in their learning, like the OP. Better to focus on one system or the other first.


text:
Arduino port relocation (PORTD to PORTB)
So I'm trying to connect the chip with an 8-bit data bus. All works good, but...
Arduino Uno uses D0 and D1 for serial TX/RX (USB connection with PC). When I try to open a serial connection (on serial.begin stage) ports D0 and D1 blocks and the chip stops working. This is a problem.
I think I should relocate pins D0 and D1 to another port. But the chip uses 8 pins (8bit chip). So I need to relocate the first pin (D0) and the second pin (D1) to port b. Maybe I can use B4 and B3?
But I don't know how to use PORTD[PD2, PD3, PD4, PD5, PD6, PD7] and PORTB[PB4, PB3] in one time like:
var portX = PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];
portX = data;

My code:
#include <avr/io.h>     // For I/O and other AVR registers
#include <util/delay.h> // For timing

/* Pinmap (Arduino UNO compatible) */
#define YM_IC (5) // PC5 (= pin A5 for Arduino UNO)
#define YM_CS (4) // PC4 (= pin A4 for Arduino UNO)
#define YM_WR (3) // PC3 (= pin A3 for Arduino UNO)
#define YM_RD (2) // PC2 (= pin A2 for Arduino UNO)
#define YM_A0 (1) // PC1 (= pin A1 for Arduino UNO)
#define YM_A1 (0) // PC0 (= pin A0 for Arduino UNO)
#define YM_CTRL_DDR DDRC
#define YM_CTRL_PORT PORTC
#define YM_DATA_DDR DDRD

#define YD0 (0)(= pin D0 for Arduino UNO)
#define YD1 (1)(= pin D1 for Arduino UNO)
#define YD2 (2)(= pin D2 for Arduino UNO)
#define YD3 (3)(= pin D3 for Arduino UNO)
#define YD4 (4)(= pin D4 for Arduino UNO)
#define YD5 (5)(= pin D5 for Arduino UNO)
#define YD6 (6)(= pin D6 for Arduino UNO)
#define YD7 (7)(= pin D7 for Arduino UNO)

#define YM_DATA_PORT PORTD // Whole PORT D for data bus (= pins D0 to D7 for Arduino UNO)
#define YM_MCLOCK (1) // PB1 = OC1A (= pin D9 for Arduino UNO)
#define YM_MCLOCK_DDR DDRB

extern uint8_t chflash[6];
uint8_t dacflash;
#define NOTEONFLASH 4
#define VGMWAIT 15

static void write_ym(uint8_t data) {
  YM_CTRL_PORT &= ~_BV(YM_CS); // CS LOW
  YM_DATA_PORT = data;
  _delay_us(1);
  YM_CTRL_PORT &= ~_BV(YM_WR); // Write data
  _delay_us(5);
  YM_CTRL_PORT |= _BV(YM_WR);
  _delay_us(5);
  YM_CTRL_PORT |= _BV(YM_CS); // CS HIGH
}

/**
 * Write data into a specific register of the YM2612
 *
 * @author Furrtek
 * @param reg Destination register address
 * @param data Data to write
 */
static void setreg(uint8_t reg, uint8_t data) {
  YM_CTRL_PORT &= ~_BV(YM_A0); // A0 low (select register)
  write_ym(reg);
  YM_CTRL_PORT |= _BV(YM_A0);  // A0 high (write register)
  write_ym(data);
}

void call() {
  setreg(0x28, 0xF0); // Key on
  _delay_ms(1000);
  setreg(0x28, 0x00); // Key off
}

uint8_t getfilebyte() {
  return Serial.read();
}

int main() {
  init();

  //Serial.begin(9600);
  /* Pins setup */
  YM_CTRL_DDR |= _BV(YM_IC) | _BV(YM_CS) | _BV(YM_WR) | _BV(YM_RD) | _BV(YM_A0) | _BV(YM_A1);
  YM_DATA_DDR |= _BV(YD0) | _BV(YD1) | _BV(YD2) | _BV(YD3) | _BV(YD4) | _BV(YD5) | _BV(YD6) | _BV(YD7);
  YM_MCLOCK_DDR |= _BV(YM_MCLOCK);
  YM_CTRL_PORT |= _BV(YM_IC) | _BV(YM_CS) | _BV(YM_WR) | _BV(YM_RD); /* IC, CS, WR and RD HIGH by default */
  YM_CTRL_PORT &= ~(_BV(YM_A0) | _BV(YM_A1)); /* A0 and A1 LOW by default */

  /* F_CPU / 2 clock generation */
  TCCR1A = _BV(COM1A0);            /* Toggle OCA1 on compare match */
  TCCR1B = _BV(WGM12) | _BV(CS10); /* CTC mode with prescaler /1 */
  TCCR1C = 0;                      /* Flag reset */
  TCNT1 = 0;                       /* Counter reset */
  OCR1A = 0;                       /* Divide base clock by two */

  /* Reset YM2612 */
  YM_CTRL_PORT &= ~_BV(YM_IC);
  _delay_ms(10);
  YM_CTRL_PORT |= _BV(YM_IC);
  _delay_ms(10);

  /* YM2612 Test code */
  setreg(0x22, 0x00); // LFO off
  setreg(0x27, 0x00); // Note off (channel 0)
  setreg(0x28, 0x01); // Note off (channel 1)
  setreg(0x28, 0x02); // Note off (channel 2)
  setreg(0x28, 0x04); // Note off (channel 3)
  setreg(0x28, 0x05); // Note off (channel 4)
  setreg(0x28, 0x06); // Note off (channel 5)
  setreg(0x2B, 0x00); // DAC off
  setreg(0x30, 0x71); //
  setreg(0x34, 0x0D); //
  setreg(0x38, 0x33); //
  setreg(0x3C, 0x01); // DT1/MUL
  setreg(0x40, 0x23); //
  setreg(0x44, 0x2D); //
  setreg(0x48, 0x26); //
  setreg(0x4C, 0x00); // Total level
  setreg(0x50, 0x5F); //
  setreg(0x54, 0x99); //
  setreg(0x58, 0x5F); //
  setreg(0x5C, 0x94); // RS/AR
  setreg(0x60, 0x05); //
  setreg(0x64, 0x05); //
  setreg(0x68, 0x05); //
  setreg(0x6C, 0x07); // AM/D1R
  setreg(0x70, 0x02); //
  setreg(0x74, 0x02); //
  setreg(0x78, 0x02); //
  setreg(0x7C, 0x02); // D2R
  setreg(0x80, 0x11); //
  setreg(0x84, 0x11); //
  setreg(0x88, 0x11); //
  setreg(0x8C, 0xA6); // D1L/RR
  setreg(0x90, 0x00); //
  setreg(0x94, 0x00); //
  setreg(0x98, 0x00); //
  setreg(0x9C, 0x00); // Proprietary
  setreg(0xB0, 0x32); // Feedback/algorithm
  setreg(0xB4, 0xC0); // Both speakers on
  setreg(0x28, 0x00); // Key off
  setreg(0xA4, 0x22); //
  setreg(0xA0, 0x69); // Set frequency

  call();

  while(1000) {
    if (Serial.available() > 0) {
      _delay_ms(1000);
      call();
      _delay_ms(1000);
      char var = getfilebyte();
      Serial.print("Yeah: ");
      Serial.println(var);
    } else {
      Serial.print("Nooo: ");
      Serial.println(Serial.available());
      call();
    }
  }
  while(1);
}

Consider a Leonardo type (ATmega32u4) board which does not rely on the hardware UART pins for host communication, or consider a different platform entirely.

You cannot set pin states in multiple ports simultaneously, if that's what you're asking.
At the instruction set level, setting pin states is a single that writes to an 8-bit register which corresponds to the 8 pins in a port. There is no way to write to two different registers in the same instruction, so if you need all eight bits to change exactly at the same time you're out of luck. However, if you can tolerate a little bit of time between 6 bits in one port changing state and 2 bits in another port changing state, then you can simply write a wrapper function.
PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];
void set_ym_ctrl_port(uint8_t data) {
    PORTD &= ~(0x3f<<2);
    PORTB &= ~(0x3<<3);
    PORTD |= (data & (0x3f<<2));
    PORTB |= (data & 0x3)<<3;
}

Or something like that. If you need even less delay and you think you can do better than the compiler, inline assembly can be helpful.
As an aside, syntax like
var portX = PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];

is not valid for a number of reasons.

Thanks a lot! Maybe i can test my luck in fast serial.begin and .end.

@ThaneKrios no, that simply will not work.  You either use the hardware UART pins as a hardware UART or you don't - you have no practical hope of coordinating changing their role on the chip side with changing the electrical connection to the pins, without horribly breaking things.

Adding to what @uint128_t said, if you really need to change the state of many pins at the same time, you can add some external latched shift registers as a SIPO (serial-in/parallel-out) interface towards the outer world.
The price you pay is that you have to load the entire register with the data you want to send before you can update the output pin states. This requires a clock cycle for each loaded bit (here I'm speaking of the clock of the external register, not Arduino's) and thus may add too much latency in your system, depending on what you are trying to do.
The 74HC595 is a classic (8-bit shift register with output latches), and can be cascaded to obtain a register of the desired width.
Here is an excerpt from the datasheet of TI's 74HC595 (yellow emphasis mine):

It's also sold in 16-pin DIP package, very convenient for breadboarding, in case you need it (common need for people that play with Arduinos).
The internal logic diagram is the following (from the same datasheet):

It is so common in the Arduino world that there are also open libraries do drive it, for example this. But even without pre-written libraries, it is not difficult to drive it from an Arduino, if you have a little experience in digital logic and can understand the timing requirements stated in its datasheet (the table in section 7.6 is fairly easy to understand, once you know what setup and hold times are).

This is intended as a complement to uint128_t's answer. I would like to
point out that the code in that answer changes the outputs in four
steps:

set to LOW the pins of PORTD that need to be LOW
set to LOW the pins of PORTB that need to be LOW
set to HIGH the pins of PORTD that need to be HIGH
set to HIGH the pins of PORTB that need to be HIGH

I compiled it on my system (with gcc 5.4.0): the generated assembly
shows that the whole process takes 18 CPU cycles. I.e. during
1.125 µs the outputs can be in an inconsistent state.
I then tried this alternative version:
void set_ym_ctrl_port(uint8_t data) {
    uint8_t new_portd = PORTD & ~(0x3f<<2) | (data & (0x3f<<2)),
            new_portb = PORTB & ~(0x03<<3) | (data & 0x03)<<3;
    cli();
    PORTD = new_portd;
    PORTB = new_portb;
    sei();
}

This changes the outputs on two steps:

update PORTD
update PORTB

The generated assembly showed that the updates are only one CPU cycle
apart. I.e. the outputs are inconsistent during only 62.5 ns.
Your mileage may vary. In case of doubt check the generated assembly.


text:
When uploading a sketch to an esp8266, isn't that the same as "flashing firmware"?
I thought that I read that using a PC running the Arduino IDE to "upload a sketch" to an esp8266 overwrites the original firmware (with the AT commands), and is actually "flashing the firmware" each time a "sketch" is uploaded. If I have that right, then why does the esp8266 WiFi still visible in available connections? There must be some code instructing the esp8266 to do this, but where is it? My sketch was simply the hello blinky thing and contained no #include statements. Where have I slipped?

Uploading a "sketch" is indeed "flashing firmware".

why does the esp8266 WiFi still visible in available connections?

I'm not sure what you mean by that.

Sorry, poor grammar. Should have been "...then why IS the esp8266 still visible..."  And by "available connections" I mean the list of access points within range of the WiFi enabled device being used. Like on my PC there's a WiFi icon in the system tray which I click on when looking to join a network. I don't know what that menu list is called.  Anyway I'm puzzled as to how my esp8266 would still show up on that list even after the original AT commands firmware was overwritten by my little "sketch".  I assume there must be some code somewhere making that happen, and I'm curious to understand.


text:
Using special Arduino "boolean" Data Type instead of standard "bool" data type
There is a special, non-standard Arduino data type called "boolean".
How does it compare with the standard C++ data type "bool", and what are the reasons to use one or the other?
If they are identical in usage, why do both exist, and which one is preferred in Arduino code?

This is a basic programming question, not specific to Arduino. The Definitive C++ Book Guide and List. Or Google

Welcome to Arduino Stack Exchange.  Please take the tour at https://arduino.stackexchange.com/Tour to get the most out of this site.  Boolean means binary, like true/false.  Do a Google search on "Arduino data types" to find out about it.

I disagree that this is not an Arduino specific question. boolean is a non-standard type alias for bool set in the Arduino core library and therefore is very much Arduino specific. See my answer for details.

Renaming something doesn't mean it's then specific to Arduino.

While the other answers give generally useful information, the authors seem to have not read the question very carefully because they are talking about the bool type rather than the boolean type. In the Arduino API, boolean is a type alias for bool, as defined in Arduino.h:
https://github.com/arduino/Arduino/blob/1.8.3/hardware/arduino/avr/cores/arduino/Arduino.h#L125
typedef bool boolean;

So you can use the boolean type just as you would bool and any standard C++ programming reference will instruct you in the use of bool. For this reason the other answers which mistakenly refer to bool are still somewhat useful.
Apparently at some point in the past the Arduino folks decided the name boolean would be more beginner friendly than bool, perhaps to be consistent with the Processing language. However, as discussed here:
https://github.com/arduino/Arduino/issues/4673
the unnecessary use of a non-standard type is now considered by some to be a poor decision as its use makes code less portable and really doesn't provide any clear advantage over bool. A proposal is in the works to remove the use of boolean from all official Arduino code and document bool in the Arduino reference and some even wish to formally deprecate boolean. Therefore my advice is to use bool instead of boolean in your code.

A Boolean variable type is one that has only 2 possible values, true or false.
Internally, it is created as an int (16-bit integer) or a uint8_t type (8-bit integer).
You can assign the "values" of true or false using the assignment operator:
bool foo;
foo = true;
if (foo) {
  do_something();
}

Internally, a true is a 1 and a false is a 0, and the number values could be equally substituted.
Boolean types in Arduino and C++ mostly exist for readability, and not for any particular efficiency over int type.

The official reference can be found here
It is best to always use true and false, and not use numbers.
Below some examples are given
Assign false resp true to a Boolean:
bool a = true;
bool b = false;

Check the Boolean value:
if (b)
{
   // Executed when b is true
}
else
{
   // Executed when b is false
}

if (a && b)
{
   // Executed when a is true and b is true
}

if (a || b)
{
   // Executed when a is true or b is true
}

If b is false, a will be false, otherwise a will stay as it was
a &= b;

If b is true, a will be true, otherwise a will stay as it was
a |= b;

// If a is true it will be false and vice versa.
a = !a;

That last one should be a = !a shouldn't it?  ~ is a bitwise not.  Depending on how true is defined ~true may still be true.


text:
How to detect if LED is switched on in external circuit using Arduino NANO?
I want to detect when an LED is powered on using an Arduino NANO. The LED is part of an external circuit. The LED uses about 1.8V. Would the circuit below allow me to detect when the LED is switched on? Is this the correct method of doing it? (The LED in the diagram represents the external circuit).

What's that component hiding under that blue wire on rows 6 to 10, column B, on the breadboard? (this is just for my benefit, I can't see it)

You could use A0 to sense the actual voltage or use an light-depended-resistor (LDR) to measure if the LED is lit (but take environmental light into account).

@KingDuken a pushbutton, one of the single row types. (Which is why schematics are usually preferred)

@KingDuken It's a push to connect button switch.

@Paul How would the circuit be setup to use A0 to detect the voltage? Would the above method also work?

I'm afraid your circuit does not work.
In fact, the base of the transistor is always connected to the power, regardless the LED being ON or OFF. Therefore the BJT would be always in the ON-state. Also a current limiting resistor in series to the LED is missing (but I think that it was just for sake of simplicity).
Assuming that:

you can mount in series something to the LED
an additional 1.3-1.5V voltage drop will not cause too much issues (to be short: if the external circuit power supply is "large enough", and if you will not be too much upset if the LED luminosity will be smaller).
You want to sense a signal LED, i.e. let's say with a current smaller than 20 mA.

Then, the safest way would be to use an optocoupler, such as 4N25-4N35. Put the LED of the optocoupler (transmitter side) in series to the LED you want to "sense", and use the phototransistor side to sense the LED status: it's emitter goes to the GND to your Arduino Nano, the collector to any input, with pull-up (The pull-up is mandatory!).
In this way, when current flows across the LED, it will also flow in the optocoupler LED, therefore the optocoupler phototransistor will be ON.
Also, using the optocoupler the two systems are electrically insulated each other (and you won't need to share the grounds).
Below you can find an example.

EDIT:
If you cannot wire the optocoupler LED in series (e.g. not enough voltage headroom because the power supply is too close to the LED Vf, or your LED is already on a PCB), you can connect the optocoupler in parallel.
Assuming the LED current is much larger than 1mA, you can use the following circuit. Choose RO so that the current flowing on the optocoupler will be 1mA (390-470 Ohm in your case). Usage of high current-transfer-ratio (CTR) optocoupler is suggested, but this might work also with a 4N25 or 4N35 (you'll be pretty close to the limit...)

Unfortunately I am unable to mount anything in series to the LED, only in parallel as it is on manufactured PCB.

Then you could connect the series of a 470-Ohm resistor and the optocoupler's LED in parallel to the LED you want to sense. When the LED is ON, there will be 1.8V across it. 1.4 V fall across the optocoupler's LED, and the remaining 0.4V across the 470-Ohm resistor. You'll have therefore 0.85mA into the optocoupler's LED, and assuming a 0.2 CTR (current transfer ratio) for the 4N35, you'll get 170 uA out of the collector. If the internal pull-up is something about 30k, that should be enough. Instead of 4N35, I suggest using a SFH618A, which is low-input current and has far higher CTR values.

Would this prevent the LED on the actual device from illuminating?

No, as you're not directly connecting in parallel the optocoupler's LED to your LED (this would prevent the original LED from turning on, as the optocoupler has a lower forward voltage than your LED). Instead, you're connecting the series "resistor + optocoupler's LED" in parallel to the LED you need to sense. Of course, the LED you need to sense will be a bit dimmer, as 850 uA will flow in the optocoupler's LED instead of the original LED. However I assume that the LED you're sensing is driven with a much higher current (5-20mA), so 850uA make little difference.

Edited the answer to include the parallel connection.

The answer depends on your definition of "on".
An led is on if

There is voltage across I th or
There insufficient voltage across it, or
There is current through it, or
It generates light output, or
It generates sufficient light output.

...
Based on each of the above, there is an answer to your question.

No, you will not detect the LED state at all, as your transistor base is connected to the target circuit's supply rail, not a switched node.
Additionally, your circuit risks burning out the LED as it lacks a current limiting resistor.
Speaking more generally, the only safe way to do this with a fully unknown circuit is to have an optical sensor looking at the LED.
If you can determine that it is safe to make an electrical connection to the circuit (ie, that the internal ground is not riding on mains voltage) and that the point of the circuit you want to measure is within an allowed voltage above that, then you can connect the grounds and measure the switched side of the LED / resistor.  But until you have far more electrical engineering experience, you are probably not in a position to make this safety determination.  Even battery powered devices can generate dangerous voltages internally.
It's important that you not connect between the LED and resistor, but rather to whichever side of that series unit is not connected to a supply rail, as the voltage drop on the LED itself may not be sufficient to register.
Certain fancier LED drivers may give you problems, for example if they regulator current internally.  Also, LEDs with PWM brightness control may require filtered polling, or even interrupts / hardware pulse-in.


text:
USB or external power
I have an arduino mega that i am using as a clock. I would like it to detect if it is connected to a USB or external power supply (e.g. a battery). I then want to set a variable to different values depending on the result, so i can display it on an OLED.

Use a simple transistor where the Vin (external power) is connected to the base, which switches the transistor. Than connect the collector to +5V, and the emitter to a GPIO input pin and read the status with the Arduino. If it receives a HIGH you know external power (via Vin) is used.
See the useful 'good' answer as comment of Majenko below ... I will leave the answer above as is, to keep his remarks clear.

Slightly more involved than that - you want to have the transistor (NPN or N-channel FET) between the GPIO and Ground, not +5V, and a pullup resistor (or enable the internal pullup resistor of the GPIO pin) and look to see if it's reading LOW for "External Power Applied". Also a resistor in the base of an NPN is needed.


text:
Changing the order of blinking LEDs with the push of a button

I am new to Arduino and I have written code that makes 3 LEDs blink while the push button is off, so the lights are blinking from left to right (1,0,0)(0,1,0)(0,0,1) and then repeat from left to right.
Now I am trying to modify this code so that whenever the system receives a High from the switch it reverses the order, so it should start blinking from right to left and keep blinking that way until I press the push button and then return to left to right.
I hope my issue is clear. I only know how to use the if & else.
Here is my code:
int switchState;
int switchst = LOW;
int d=LOW;

void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(2,INPUT);
}

void loop() {
  switchState = digitalRead(2);
  if (switchState == HIGH) {
    d= ~d;
    if(d==LOW) {
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
  }  else {
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
  }
}

The problem with this code is that it doesn't keep blinking if I release the push button.
This is the old code. It only goes from left to right and keeps repeating.
int switchState = 0;
int switchst = LOW;

void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(2,INPUT);
}

void loop() {
  switchState = digitalRead(2);
  if (switchState == switchst) {
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
  } else {
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
  }
}

You need to learn more constructs than if and else.  Learn to use a loop, you can then blink the LEDs in an infinite loop, with less and cleaner code too.

hi thanks for your comment I have done it in the class with only if & else but I forgot how and I am only allowed to use if and else.

You also need to present code properly indented for legibility. Use blank lines only to separate logical sections. I've edited the first few lines for you ... and you've just overwritten the changes with a simulataneous edit. Oh well!

The first thing I saw was a cartoon where apparently a schematic should have been.  Not gonna look at the rest, so closing as unclear.

What on earth are you studying if you're not allowed to use loops?

@Oskar Skog - The requirement for a student to "only use if else" to solve a problem is common when people are first learning how to write code. It's possible that Bro JJ has not been taught how to work with "loops" yet. That may be tomorrows lesson.

I'm voting to close this question as off-topic because it's a generic programming problem, not Arduino specific.

The easiest is to use a 'mode', which is a boolean that keeps the state if it is blinking right, let's call it blinkToRight. Initially this is true.
An if statement will be used to change the order.
So the program will be something like (not tested):
global:
bool blinkToRight = true;

in Setup:
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(2,INPUT);

In Loop:
// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(true, false, false);
   show(false, true, false);
   show(false, false, true);
}
else
{
   show(false, false, true);
   show(false, true, false);
   show(true, false, false);
}

void show(bool led1, bool led2, bool led3)
{
   digitalWrite(2, led1);
   digitalWrite(3, led2);
   digitalWrite(4, led3);
   delay(200);
}

checkReverse will check the input button and returns true if the mode should be reversed.
However, you cannot simply check for the button state. The problem is bouncing. But check in the Arduino examples to a debounce example for this problem and the program should work as expected.
See example: Debounce example
Since only one led will be on, you can also use the following functions for Loop and show:
In Loop:
// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(3);
   show(4);
   show(5);
}
else
{
   show(5);
   show(4);
   show(3);
}

Show:
void show(int ledOn)
{
   digitalWrite(ledOn == 3);
   digitalWrite(ledOn == 4);
   digitalWrite(ledOn == 5);
   delay(200);
}

And it's even better to use constants:
const int LED1   = 3
const int LED2   = 4
const int LED3   = 5
const int BUTTON = 2

Setup:
pinMode(LED1  , OUTPUT);
pinMode(LED2  , OUTPUT);
pinMode(LED3  , OUTPUT);
pinMode(BUTTON, INPUT);

Loop
// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(LED1);
   show(LED2);
   show(LED3);
}
else
{
   show(LED3);
   show(LED2);
   show(LED1);
}

Show:
void show(int ledOn)
{
   digitalWrite(ledOn == LED1);
   digitalWrite(ledOn == LED2);
   digitalWrite(ledOn == LED3);
   delay(200);
}

you should add some delays between the "show()" functions, or have some kind of timing, othewise all the LED will appear as ON...

@next-hack Thanks for the comment, you are absolutely true, and I updated my answer (part of the show function).

In my opinion, there are two things I'd change. The first one is that delay functions should be avoided whenever possible, the other is that the switch bounces.
In order to solve the bounces, you will have to wait some time to stabilize the signal:
if (debouncedValueOfButton != (digitalRead(button_pin) == HIGH))
{ // Is there a change?
    if (((byte)currMillis) - lastMillisForButton) >= millisButtonDebounce)
    { // Yes, without bounces
        debouncedValueOfButton = !debouncedValueOfButton;
        if (debouncedValueOfButton)
        { // Rising edge
            if (increment > 1)
                increment = 1; // Go in one direction
            else
                increment = 2; // Go in the other direction
        }
    }
}
else
    lastMillisForButton = (byte)currMillis;

So, if the value is different from the one I think it is I'll wait for some milliseconds; if it is stable then I change the value I think it is.
As for removing the delay, I think it is better to use an approach similar to the "blink without delay" sketch:
if ((((uint16_t)currMillis) - lastMillisForBlink) >= millisBetweenBlinks)
{
    lastMillisForBlink += millisBetweenBlinks;
    currentLed = (currentLed + increment) % 3;

    digitalWrite(led0_pin, currentLed == 0);
    digitalWrite(led1_pin, currentLed == 1);
    digitalWrite(led2_pin, currentLed == 2);
}

In this implementation, you use a variable increment to decide whether you have to go forward or backwards; when increment is 1 the led to be colored are 0 -> 1 -> 2 -> (3)0 -> 1 ...; when it is 2 the led are 0 -> 2 -> (4)1 -> (3)0 -> 2 ....
The complete code is (DISCLAIMER: NOT TESTED)
const byte led0_pin = 3;
const byte led1_pin = 4;
const byte led2_pin = 5;
const byte button_pin = 2;

int8_t currentLed, increment;
unsigned int lastMillisForBlink;
const unsigned int millisBetweenBlinks = 200;

bool debouncedValueOfButton;
byte lastMillisForButton;
const byte millisButtonDebounce = 50;

void setup() {
    pinMode(led0_pin,OUTPUT);
    pinMode(led1_pin,OUTPUT);
    pinMode(led2_pin,OUTPUT);
    pinMode(button_pin,INPUT);

    increment = 1;
    currentLed = 2; // At first run, currentLed will be increased by 1, so it starts at 0
    lastMillisForBlink = millis() - millisBetweenBlinks; // trigger a refresh at first loop

    debouncedValueOfButton = (digitalRead(button_pin);
}

void loop() {
    unsigned long currMillis = millis();

    if ((((uint16_t)currMillis) - lastMillisForBlink) >= millisBetweenBlinks)
    {
        lastMillisForBlink += millisBetweenBlinks;
        currentLed = (currentLed + increment) % 3;

        digitalWrite(led0_pin, currentLed == 0);
        digitalWrite(led1_pin, currentLed == 1);
        digitalWrite(led2_pin, currentLed == 2);
    }

    if (debouncedValueOfButton != (digitalRead(button_pin) == HIGH))
    { // Is there a change?
        if (((byte)currMillis) - lastMillisForButton) >= millisButtonDebounce)
        { // Yes, without bounces
            debouncedValueOfButton = !debouncedValueOfButton;
            if (debouncedValueOfButton)
            { // Rising edge
                if (increment > 1)
                    increment = 1; // Go in one direction
                else
                    increment = 2; // Go in the other direction
            }
        }
    }
    else
        lastMillisForButton = (byte)currMillis;
}


text:
Arduino external 5V power supply
I'm designing a shield for the Arduino Uno with some sensors that require +5V, +3V3 and +3V Vdd. I want to power everything with a single DC adapter so I have a voltage regulator that converts the DC input (+12 - +26V DC) to 5V DC with a maximum current of 1A. That output goes into the 5V sensors, 3V3 and 3V regulators.
Since this is already regulated power can I connect the 5V 1A output to the +5V pin on the Arduino, bypassing the voltage regulator on the Arduino? Or is it better to have another +10V voltage regulator parallel to the 5V regulator that goes into the 9-12V Vin on the Arduino (that than goes to the 5V voltage regulator on the Arduino)?
If I do the first option, is it then save to have the USB connector plugged in?

There is no "better", you can do either and both ways are OK to use. You can also just leave a USB connection plugged in, when all the voltages are close to 5 V there is no risk that large (damaging) currents start to flow.

"converts the DC input (+12 - +26V DC) to 5V DC"  Are you using a switching regulator for that? That'd be most efficient.  A part like Murata Power Solutions, OKI-78SR-5/1.5-W36-C, available at Digikey for example. 7V to 36V in, 5V out, 1.5A capacity.  Or roll your own from a switching regulator IC; pay attention to the components and layout recommended by the manufacturer.


text:
How do I know the size of the bootloader of ATtiny? Is it the same as ATMega328P?
I burned the bootloader in ATtiny45 with the Arduino tool.

I want to know how much memory it has taken.
Is this bootloader the same code of a bootloader used in the 328P or other chips?
Can I see this code in any way, to know how it works?

no, it's not the same bootloader. well, a tiny part of it might be, read up on bootloaders.

What bootloader? Please edit your question to post a link to where you got this "bootloader" from.

1) I want to know how much memory it has taken

Look to see how big the bootloader is. If it's a HEX file you will either want to load it into a HEX (Intel HEX, not hexadecimal representation) file editor, or convert it to binary with avr-objcopy.
$ avr-objcopy -I ihex <hex file> -O binary <bin file>

2) and if this bootloader is the same code of a bootloader used in the 328P or other chips

No, each chip requires its own special bootloader - simply because all chips are different: that's why they exist.  If they were all the same there would only be one chip.

3) Can I see this code in any way, to know how it works ?

If it's open source and you download the bootloader from wherever it's stored (probably Github somewhere), then yes, you can. Of course, that also assumes that you would understand what you are seeing which, judging by this question, is not that likely.

The '45 doesn't have an actual UART so I suspect that the "bootloader" is just a stub that allows the IDE to set the fuses properly.

Or... it uses software serial, or it uses software USB (as the digisparks do on the '85).