text:
I2C send and read 2 bytes many slave
I've already sent you the code but you told me to format it, so I tried this way ..
the problem I got is it doesn't read good the 2 slave (sender) to the master
(reader) ...you told me LAST TIME (DON'T DO SERIAL PRINTLN IN THE CALLBACK
ROUTINE) so I tried this code (I've got some data from both but not in order)
here's the slave 1 and 2 code (I only change the  slavedeviceId address)
#include "Wire.h"

//
// i2c_test_01

//
// This demonstrates a master transmitting to a slave.
//

// The master transmits a value read from an analogue port.

// The slave sends the value to the serial device.
//

byte x = 0;
//
const byte AnalogueInputPin = 0;

const byte SlaveDeviceId = 2;

void setup() {
  // Start I2C bus as master
  Wire.begin();
}

void loop() {
  int input0 = analogRead(x);
  // Send two bytes to slave.
  Wire.beginTransmission(SlaveDeviceId);
  Wire.write(input0 >> 8);
  Wire.write(input0 & 255);
  Wire.endTransmission();

  delay(10);

  x++;
  if (x == 4) {
    x = 0;
  }

  delay(40);

}

here's the master (reader)
thanks for your time it is realy intructive for me !!!
#include "Wire.h"

const byte SlaveDeviceId = 1;
const byte SlaveDeviceId2 = 2;
int S1;
int S2;
int c;
int cc;

void setup() {
  // Start I2C bus as a slave
  Wire.begin();
  Wire.onReceive(receiveCallback);
  Serial.begin(9600);
}

void SLAVEone() {
  Wire.begin(SlaveDeviceId);
  delay(5);
  Wire.onReceive(receiveCallback);
  delay(5);
}

void SLAVEtwo() {
  Wire.begin(SlaveDeviceId2);
  delay(5);
  Wire.onReceive(receiveCallback2);
  delay(5);
}

void receiveCallback(int aCount) {
  if(aCount == 2) {
    int receivedValue  = Wire.read() << 8;
    receivedValue |= Wire.read();
    //Serial.print(c);
    //Serial.print(" S1 = ");
    //Serial.println(receivedValue);
    S1 = receivedValue;
  } else {
    Serial.print("Unexpected number of bytes received: ");
    Serial.println(aCount);
  }
  c++;
  if (c == 4) {
    c = 0;
  }
}

void receiveCallback2(int aCount2) {
  if (aCount2 == 2) {
    int receivedValue2  = Wire.read() << 8;
    receivedValue2 |= Wire.read();
    // Serial.print(cc);
    //Serial.print(" S2 = ");
    //Serial.println(receivedValue2);
    S2 = receivedValue2;
  } else {
    Serial.print("Unexpected number of bytes received: ");
    Serial.println(aCount2);
  }
  cc++;
  if (cc == 4) {
    cc = 0;
  }
}

void loop() {
  for(int y = 0; y <= 3; y++) {
    SLAVEone();
    Serial.print(c);
    Serial.print(" = S1 = ");
    Serial.println(S1);
    delay(10);
  }
  for(int y = 0; y <= 3; y++) {
    SLAVEtwo();
    Serial.print(cc);
    Serial.print(" = S2 = ");
    Serial.println(S2);
    delay(10);
  }
}

I have formatted your code, without changing anything else.
Please take a moment to check how it is done. Just hit edit on your question.

Don't do serial prints in an ISR (callback).

There are so many mistakes in your code. I'll do my best to correct them using comments. The code for the slaves should be as follows:
#include "Wire.h"

//
// i2c_test_01

//
// This demonstrates a master transmitting to a slave.
//

// The master transmits a value read from an analogue port.

// The slave sends the value to the serial device.
//

int inp = 0;  // input pin

const byte SlaveDeviceId = 2;

void setup() {
  Wire.begin(SlaveDeviceId);  // here the slave joins the bus, with its address as argument to begin()
  Wire.onRequest(callback);  // here you indicate what the slave should do if a bus master queries it
}

void callback() {
  int input0 = analogRead(inp);
  // Send two bytes to master
  Wire.write(input0 >> 8);
  Wire.write(input0 & 255);

  inp++;
  if (inp == 4) {
    inp = 0;
  }

}

void loop(){}

This is the master's code:
#include "Wire.h"

const byte SlaveDeviceId = 1;
const byte SlaveDeviceId2 = 2;
char inputDev = 4;  // number of devices connected to slave analog inputs

void setup() {
  Wire.begin();   // no argument here since its a master
  Serial.begin(9600);
}

//the onReceive() method is for slaves receiving from a master, so we dont use it here

void loop() {
  Serial.println("\r\nSlave 1: ");
  for (char i = 0; i < inputDev; i++){
    Wire.requestFrom(SlaveDeviceId, 2);
    delay(1);  // more than enough time for all the data to come in
    int val = Wire.read() << 8;
    val |= Wire.read() & 0xFF;
    Serial.print(val);
    Serial.print(",");
  }
  Serial.println("\r\nSlave 2: ");
  for (char i = 0; i < inputDev; i++){
    Wire.requestFrom(SlaveDeviceId2, 2);
    delay(1);  // more than enough time for all the data to come in
    int val = Wire.read() << 8;
    val |= Wire.read() & 0xFF;
    Serial.print(val);
    Serial.print(",");
  }

}

I don't quite see how your code is supposed to work.  It seems like your "slave" devices are trying to write to your "master" as if they were master devices not slaves, and your "master" is rapidly switching between thinking it is one of two slaves. The whole methodology is backwards.  The "master" should connect to a "slave" and request the data not wait for a "slave" to randomly throw data at it.


text:
How to destroy my Arduino with I/O pins?
What are the most common ways of destroying a Arduino using the I/O pins?
Also, in what situation would it be acceptable to attach the positive or negative end of a power supply to an I/O pin?

putting a small firework under the micro and connecting an electronic match to a pin is a spectacular way to destroy and arduino using the I/O pins

Do the I/O pins have to be from the same Arduino we're trying to destroy? Or can they be from a different device?

There are many ways to destroy an Arduino, check out this article, 10 Ways to Destroy An Arduino.

Shorting I/O Pins to Ground
Shorting I/O Pins to Each Other
Apply Overvoltage to I/O Pins
Apply External Vin Power Backwards
Apply >5V to the 5V Connector Pin
Apply >3.3V to the 3.3V Connector Pin
Short Vin to GND
Apply 5V External Power with Vin Load
Apply >13V to the Reset Pin
Exceed Total Microcontroller Current

What are the most common ways of destroying a Arduno using the I/O pins?

Over-voltage and over-current.
Over-voltage involves putting too high (or too low) a voltage onto an IO pin.  Over-current involves trying to source (or sink) too much current through an IO pin.  Both can be fatal.

Also, in what situation would it be acceptable to attach the positive or negative end of a power supply to an I/O pin?

"Positive": When that power supply is no more than 5V and shares ground with the Arduino and you want to know if it's on or not, or measure the voltage (Analog Input).  Anything more than 5V will require a voltage divider to bring the voltage down to 5V.
"Negative": If by that you mean the ground terminal, and that ground terminal is shared with the Arduino ground, then you can do it any time - but why would you, since you'd just be connecting to the Arduino ground since they are one and the same. If it's not the ground terminal but a potential below ground, then never unless you use some circuitry to raise that potential above ground for measuring it.

source: Stack Exchange

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

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

sort: votes


text:
Why won't the slide switches control the motor in this 123d simulation?
int guard = 7;
int switchPin = 6;
int motorPin = 9;

void setup(){
  pinMode(guard,INPUT);
  pinMode(switchPin,INPUT);
  pinMode(motorPin,OUTPUT);
}

  void loop(){
   if (digitalRead(guard==HIGH)&&digitalRead(switchPin==HIGH))              //&&

   {

     digitalWrite(motorPin,HIGH);
    delay(500);
    digitalWrite(motorPin,LOW);
    delay(1000);
   }
        else {

     digitalWrite(motorPin,LOW);
   }

  }

This should be written like this:
if ( digitalRead(guard)==HIGH && digitalRead(switchPin)==HIGH ) {

// Rest of the code..

}

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


text:
What is the most accurate sensor for detecting ping pong ball?
What is the most accurate proximity sensor for a ping pong ball? I will be using this to calculate 3D positioning of a ping pong ball in flight. I only need to detect the ball within 0-5 feet (basically on one side of ping pong table).

The range of motion is roughly a ping pong table length and width and maybe 4 feet in height.

Perhaps you should look into something like a leapmotion, or Xbox kinect. Not arduino.

Steven Levy in Hackers reports a tale about Marvin Minsky nearly being swatted by an early ping-pong robot when his bald head satisfied the vision system's ball-detection criteria.

The Arduino itself isn't really fit for video processing. We've used two webcams, one top and one side, to get an 3D location. Your algorithm has to be fast, we had most luck by using an orange ping pong ball on a green tabletennis background, and by just searching for the first orange pixel. Circle detection was way too slow for us.

If you're looking to make something functional, using a 2D airhockey table is much easier. Especially if you think of making a keeper robot.

I've had some good luck with using the Pixy camera system.
http://www.cmucam.org/projects/cmucam5/wiki
You get a maximum of 50 FPS and can detect and locate different objects based on hue. The library function getBlocks() returns the X and Y center location of each of the objects the camera detects. You teach the camera what hues to recognize as blocks, and adjust the detection thresholds. I use mine in monochrome infrared light by adding a visible filter and lens kit from http://irlock.com/

In the meantime a student has made a really impressive implementation, that might answer your question: interactive tennis table


text:
Using ArduinoModbus library to read a holding register with value -1
client.read() function in ArduinoModbus library returns -1 on failure: https://www.arduino.cc/reference/en/libraries/arduinomodbus/client.read/. How can it be used to read a holding register with value -1?
One option would be to monitor client.lastError(), but there seem to be no way to reset the lastError, so it would work only up to the first failure.

My guess is that for a register with signed type value, e.g. int16_t, one has to extract the lower 16-bits from uint32_t value returned by client.read().

wouldn't modus transmit only bytes? ... those do not have a sign

@jsotola Modbus registers can have negative values, therefore sign matters.

my guess is that the data would be read as an unsigned integer ... the data could be 2 bytes and the value returned by the library 4 bytes ... the top two bytes used to make the number negative

@jsotola Yes, I think so. I was adding a comment to my post to this effect, while you've sent yours.

here is an example how this works ... the first line would be an error message ...  the second 32 bit value is not negative, but the 16 bit data is negative ... https://wokwi.com/projects/403163467946550273

There are two errors that return -1, for the Arduino Modbus library, an error from the client for -1 means "I/O error", for the Modbus protocol, the exception 1 means "illegal function code". calling client.lastError() would return a string interpretation of what the error code means. Please provide your code and what you are trying to reset/set via the modbus? are you using TCP or RTU protocol?

How do you send int16_t as the modbus function code? why there is a need for using int16_t for modbus function code instead of uint16_t or two bytes of uint8_t? Are you aware that Modbus is using Big Endian during transmission while whatever you stored in the Arduino is in Small Endian?

@hcheung I posted my code as an answer.

According to the Wikipedia description of the Modbus data
model, “input registers” and “holding registers” hold 16-bit
unsigned numbers, in the range 0–65,535 (0x0000–0xffff). This is
consistent with the ArduinoModbus client.write() prototype,
which takes an unsigned int parameter.
The client.read() function, on the other hand, returns a
long. This is typically a 32-bit number that can hold all the possible
legit values, and also −1 to signify an error condition.
If, contrary to the Modbus data model, your Modbus device transmits
signed values, you should check its datasheet to see how negative values
are encoded. It will most likely use the two's complement
representation, which is the one used internally in the Arduino. If this
is the case, what the device holds as −1 will be read by the library as
65,535. You can easily get the correct number by converting to
int16_t:
long result = client.read();  // use `long` to not loose information
if (result == -1) {
    handle_the_error();
    return;
}
int16_t value = result;  // convert to the device's type
if (value == -1) {
    handle_a_legit_minus_one();
}

Here is my code to solve this problem and additionally separate error code from read value. Modbus data model mentioned in another answer is insufficient for modern hardware, which forced many manufacturers to go beyond it, in order to use int32_t, uint32_t and float registers.
template<typename T>
bool holdingRegisterWrite16(ModbusTCPClient &modbus, int addr, T arg) {
  return modbus.holdingRegisterWrite(addr, arg);
}

template<typename T>
bool holdingRegisterRead16(ModbusTCPClient &modbus, int addr, T &arg) {
  static_assert(sizeof(T) == 2, "arg has to be a 16-bit type");

  auto res = modbus.holdingRegisterRead(addr);

  if (res == -1)
    return false;

  memcpy(&arg, &res, 2);
  return true;
}

template<typename T>
bool holdingRegisterWrite32(ModbusTCPClient &modbus, int addr, T arg) {
  uint16_t word0, word1;

  memcpy(&word0, &arg, 2);
  memcpy(&word1, (char*)&arg+2, 2);

  return
    modbus.beginTransmission(HOLDING_REGISTERS, addr, 2)  &&
    modbus.write(word0)  &&  modbus.write(word1)  &&  modbus.endTransmission();
}

template<typename T>
bool holdingRegisterRead32(ModbusTCPClient &modbus, int addr, T &arg) {
  static_assert(sizeof(T) == 4, "arg has to be a 32-bit type");

  if (modbus.requestFrom(HOLDING_REGISTERS, addr, 2) != 2)
    return false;

  auto res0 = modbus.read();
  auto res1 = modbus.read();

  if (res0 == -1  ||  res1 == -1)
    return false;

  memcpy(&arg, &res0, 2);
  memcpy((char*)&arg+2, &res1, 2);
  return true;
}

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


text:
Achieving low power with Seeeduino Cortex-M0+ powered from 12V battery
I have Seeeduino Cortex-M0+, which is similar to Arduino Zero, both using Atmel SAMD21 MCU. It is powered from 12V battery directly to 12V PWRIN jack. Current draw for LED blink test is 18mA. I tried two low power libraries:

https://github.com/rocketscream/Low-Power
https://github.com/adafruit/Adafruit_SleepyDog

with:

LowPower.standby(); delay(5000);
Watchdog.sleep(5000);

In both cases, the current draw dropped only to 12.7mA, which is still huge. I checked the datasheet of MP1496DJ-LF-2 step-down, switch-mode converter used by this board and its quiescent current is below 1mA, so it doesn't look like the source of high current consumption. I've read posts about Arduino Zero running on 5mA from 12V input in low power. What else can I do in order to get the current closer to 5mA?
I cross-posted at https://electronics.stackexchange.com/questions/607000/achieving-low-power-with-seeeduino-cortex-m0-powered-from-12v-battery

I did a few experiments with external DC/DC converters feeding 5V pin on Seeeduino Cortex-M0+ from 12V battery, bypassing its MP1496DJ-LF-2 power stage. Here are the results:

DC/DC model
sleep current [mA]
LED blink current [mA]

MP1496DJ built-in baseline
12.7
18.0

LM2596S generic
8.6
14.8

Pololu D24V22F5
5.0
11.2

Pololu D24V5F5
3.6
9.3

As @devnull at Electronics Stack has answered, the quiescent current of 5~10 mA from the LDO could be enough to make up for the lost currents.
I don't have any specific suggestions on code or parts, but I can give you some tips regarding methodology. If you're working on the software side to reduce current consumption, you might be better off eliminating the possibility of hardware imperfections entirely. I'd power the board with 3.3V directly and preferably cut the traces to 5V or other unused circuits. Reduce the current consumption to the lowest possible on software side, and then work on the hardware side. You could be better off with an external LDO or a 12V to 3.3V converter with a low quiescent current to power your board.
From my experience, currents can leak from even the most unexpected circuits. There could be a faulty or crappy capacitor with higher than usual leakage current, resistors in voltage dividers with resistance not high enough drawing a couple of mA in total, or some random transistors we didn't think of drinking 1~ mA per chip. Or combinations of everything above being responsible for only a few hundred uA per part, but totals to a few mA in total. It's best to make a board with the most barebone parts or get one.


text:
Arduino compatible ESP32 and ESP8266 board power consumption at sleep state
I have data on smaller modules with ESP32 and ESP8266, but can't find anything reliable pertaining to the whole board power consumption (current) with 12V input and microcontroller at low power or sleep state. The power subsystem on Arduino compatible boards like this one:

consists of step-down switching regulator to 5V and linear regulator to 3.3V. I wonder how this design behaves when the ESP microcontroller itself draws very small current, e.g. below 1mA. Does anyone have current measurement at DC input socket when microcontroller is in low power state without any peripherals attached to the board?

The datasheet for the regulator will tell you how it performs at different loads. And what's to stop you measuring the current yourself?

I always measure myself. Get one usb-voltmeter. They create wonders.

@Majenko I don't have the board. I'm asking before buying.

i would guess that's not the best board to use for low power consumption, due to usb serial, leds, etc. use a buck converter to turn 12v into 3.3v.


text:
How to make MQTT and ArduinoModbus libraries working on the same Ethernet port?
I have a SAMD51P20 based Arduino PLC with WIZnet W5500 based Ethernet shield. I'm using these libraries:
#include <Ethernet.h>
#include <MQTT.h>
#include <ArduinoModbus.h>

MQTT and Modbus-TCP clients run fine individually, but running them at the same time creates problems with both of them.
Is there a software solution to this problem, e.g. using separate sockets for MQTT and Modbus-TCP. WIZnet W5500 has 8 sockets available, but I don't see an API to select a socket for MQTT and Modbus-TCP client.
If not software, is there a hardware solution?

Here is the code snippet:
#include <fmt.h>
#include <P1AM.h>
#include <Ethernet.h>
#include <MQTT.h>
#include <ArduinoModbus.h>

using namespace std;

#define HOST_NAME "WIZnet"
uint8_t macPLC[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
uint8_t ipPLC[] = {192, 168, 0, 41};
uint8_t ipModbus[] = {192, 168, 0, 43};
char    ipMQTT[] = "192.168.0.42";
int     unitID = 98;

EthernetClient ethernet;
MQTTClient mqtt;
ModbusTCPClient modbus(ethernet);
int n = 0;

void messageReceived(MQTTClient *client, char topic[], char bytes[], int length) {
  if (length == 8) {
    int32_t commandID;
    float   commandArg;

    memcpy(&commandID, &bytes[0], sizeof(commandID));
    memcpy(&commandArg, &bytes[4], sizeof(commandArg));

    Serial.println(fmt::format("{} {}", commandID, commandArg).c_str());
  }
  else
    Serial.println("wrong length!!!");
}

void servoSetup() {
  modbus.coilWrite(unitID, 0x00C, 1);
}

void setup(){ // the setup routine runs once:
  P1.configWD(10000, 1);
  P1.startWD();
  Serial.begin(115200);  //initialize serial communication at 115200 bits per second

  while (!P1.init())
    delay(1); //Wait for Modules to Sign on

  Ethernet.begin(macPLC, ipPLC);
  mqtt.begin(ipMQTT, ethernet);
  modbus.setTimeout(500);

  if (!modbus.begin(ipModbus, 502))
    Serial.println("Failed to start Modbus TCP client!");
  else
    Serial.println("Connected to Modbus TCP client.");

  P1.petWD();

  while (!mqtt.connect(ipMQTT)) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nConnected to MQTT broker.");
  mqtt.subscribe("plc", 2);
  mqtt.onMessageAdvanced(messageReceived);
  servoSetup();

  delay(2000);
}

void loop() {
  P1.petWD();
  Serial.println(mqtt.loop());
  Serial.println(n++);
  int addr = 0x2407;

  if (!modbus.holdingRegisterWrite(unitID, addr, n))
    Serial.println(fmt::format("Modbus write failed: {}", modbus.lastError()).c_str());

  delay(1000);
  if (auto result = modbus.holdingRegisterRead(unitID, addr); result < 0)
    Serial.println(fmt::format("Modbus read failed: {}", modbus.lastError()).c_str());
  else
    Serial.println(fmt::format("holdingRegisterRead: {}", result).c_str());
  delay(1000);
}

In this case, Modbus-TCP writes and reads have no effect, mqtt.loop() returns 0 and messageReceived() callback is not called. If I comment out MQTT or Modbus-TCP client, the code behaves as expected.

What kind of problem? The 3-line of code doesn't tell us anything. You need to elaborate more on how you create the client for each connection?

@hcheung I posted the full test code.

ModbusTCPClient modbus(ethernet); and mqtt.begin(ipMQTT, ethernet);, you are sharing the same Ethernet client for two services. Create a separate client instance for each service.

@hcheung Thank you for looking into it.

There is no API to set the count of sockets used in the Ethernet library.
The MAX_SOCK_NUM is set in Ethernet.h based on available RAM.
#if defined(RAMEND) && defined(RAMSTART) && ((RAMEND - RAMSTART) <= 2048)
#define MAX_SOCK_NUM 4
#else
#define MAX_SOCK_NUM 8
#endif

So on SAMD51 you have 8 sockets available. Your problem with MQTT and Modbus TCP is elsewhere.
btw. the W5100 can handle only 4 sockets, but that is constrained at runtime.

EDIT: In your sketch you use the same EthernetClient for both libraries. Use two separate EthernetClient objects.
EthernetClient ethernet;
EthernetClient modbusClient;
MQTTClient mqtt;
ModbusTCPClient modbus(modbusClient);


text:
Substitute for FTDI board?
I am thinking forward to buy a set of Arduino pro mini. I have a very low budget and I can't think of buying a FTDI board. Is there any substitute for the FTDI board that is compatible with these arduino pro mini.

You could get an USBasp from eBay for around 2$, it can even program microcontrollers that don't have a bootloader (which may save you some), but they don't work for USB communication

Could you explain why you want to buy/use the Pro Mini in particular, and what else (if anything) you'll be using with it?

Actually, I had an Arduino Nano which I have burned So I thought of getting the Pro Mini as they are more smaller and cheap So I thought of buying them

if your computer has a serial port, you just need some solid-core wires..

@dandavis How can I do that ?

on a DB9 serial, 2-rx, 3-tx, 7 to gnd.

All prices in USD w/ free shipping.
FT232RL breakout board:

Aliexpress: $1.55
eBay: $1.81

They are probably counterfeit. A Windows driver update (AKA "FTDIgate") at one point "bricked" them but I'm not sure that's an issue anymore. Even if it is it's Windows only and easy enough to work around. I've used these for years on Windows and they work fine for me.
If that's still beyond your budget there are a few other common options. I haven't used these breakout boards but I do have quite a few boards that use the CH340G and they work perfectly once you install the driver. There's a decent chance some of these will also be counterfeit. Some didn't break out the DTR/CTS pin for auto reset but if you're on such a low budget maybe it's worth it to you to press the reset button on every upload to save a few cents. They may not have the standard FTDI header pinout and if so would require you to use jumpers to connect them to the Pro Mini rather than plugging directly into the header.
PL2303 breakout board:

Aliexpress: $0.50
eBay: $0.74

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.
CH340G breakout board:

Aliexpress: $0.72
eBay: $0.93

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.
CP2102 breakout board:

Aliexpress $1.00
eBay: $1.31

I live in India and I need DTR or CTS pins but In the worst scenarios I will adjust.

These are all shipped from China so the shipping should be free to India also. I verified that shipping on the Aliexpress FTDI FT232RL board is free to India. The nice thing about the Pro Mini is you can use one USB-serial board for all your Pro Minis so you really only need to buy one, though it's always nice to have a spare in case of magic smoke.

But the shipping takes one month

Yes, I have waited even longer than that here in the US for some of my orders but sometimes much shorter. I seem to get slower shipping from Aliexpress than eBay. You didn't say anything about needing it quickly in your question. Do some research for a supplier in India for the fastest delivery time.

Basically, you need any way to talk to the serial interface (on digital pins 0 and 1) on the Pro Mini. Remember that for programming you'll also need to be able to manipulate the reset line on the target board, usually done via DTR.
If you already have an Arduino board with USB, you could write a small sketch that uses that as the interface. Using the SoftwareSerial library or the AltSoftSerial library you could have the USB Arduino talk to the Pro Mini via a couple of data pins and relay the data back and forth. Depending on the Arduino you use and how you program it, it may or may not be able to keep up with 115,200 bps, but rates at or below 57,600 bps should be fine. You'll also need to handle the DTR and CTS signals for programming; this can be done with a couple more data pins.
In general what you're trying to do (whether you go with my solution or another one) is not a beginner project. If you're not familiar enough with Arduino systems to answer the question you posed, I'd strongly suggest buying an Uno, Nano or other board with integrated USB rather than trying to play with the Pro (which is called that for a reason).
If the cost of a single Arduino board is an issue, make sure you're looking around for the cheapest sources. You can find "non-brand" versions of many boards, such as this "Nano" for considerably lower prices than you'll see from the name-brand vendors. They're lower quality and you're not supporting the Arduino ecosystem, but they help when you have a very limited budget.

I have an Arduino Nano which is actually burned!


text:
RN-52 - Bluetooth Audio Module two way communication with Android
Im planning a project that involves sending data from a door phone to an android phone and vice versa using the RN-52 chip from sparkfun. Because of the nature of the project it is necessary to be able to send and receive audio simultaneously, is this possible? I've done some googling and it seems to me impossible because of sink/source, since you cant have both at the same time (using A2DP).
Can this be done with another profile I don't know of?
Even if that were to work, can the chip handle two way communication?
Is this project feasible with BT, or should I be looking at WIFI-communication instead?
Ultimately it would be nice to be able to use BT because of costs.
Edit: Can I use bluetooth hands free profile? This profile is (AFAIK) intended to send audio to and from a phone (amongst other functionality). The chip does support HFP/HSP, can this work?

Regardless of channel issues, full duplex audio is likely to cause feedback issues which are tricky to eliminate.

Well, I guess I could make it half-duplex though. I.e you hold a button on the phone to talk, and is not able to press it when someone is talking in the other end.


text:
How can program/arduino restarted by IDE?
I wrote my custom sketch, where I am printing some greeting text inside setup() method.
I found, that each time I am restarting IDE, and opening serial monitor, a greeting text is printed there again, i.e. setup() method running again.
How can this happen? I was thinking setup() method run once, when Arduino is powered up by connecting to the USB socket?
If it is possible to restart it already connected, then how this can be done?
UPDATE
Code is follows:
#include <Wire.h>
#include <Adafruit_BMP085.h>

Adafruit_BMP085 bmp;

String command;

String awaitingMessage = "Temperature and pressure sensor awaiting commands\r\nCommand \'help\' is for help";

void awaiting() {
  Serial.println(awaitingMessage);
}

void help() {
  Serial.println("Temperature and pressure sensor commands:");
  Serial.println("temp\t- output temperature in degrees Celsius");
  Serial.println("press\t- output pressure in Pascals");
  Serial.println("wait\t- print awaiting message");
  Serial.println("help\t- output this text");
}

void temperature() {
  Serial.println(bmp.readTemperature());
}

void pressure() {
  Serial.println(bmp.readPressure());
}

void unknown() {
  if( command.length() > 0 ) {
      Serial.println("Unknown command was \'" + command + "'");
    }
}

void setup() {
   Serial.setTimeout(50000);
  Serial.begin(9600);
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
  else {
    awaiting();
  }
}

void loop() {
  command = Serial.readStringUntil('\n');

  if( command.startsWith("temp") ) {
    temperature();
  }

  else if( command.startsWith("press") ) {
    pressure();
  }

  else if( command.startsWith("wait") ) {
    awaiting();
  }

  else if( command.startsWith("help") ) {
    help();
  }

  else {
    unknown();
    //awaiting();
  }

}

Video is here: https://youtu.be/-QBleGVxaus

When you open the serial monitor (or even just go to the serial port menu) the serial port is opened. When the serial port is opened the DTR line is asserted.  This is the method that the Arduino uses to reset so that you can access the bootloader and upload a new sketch.
Every time you open the serial port - through whatever means you choose - you reset the board, whether you like it or not.
There are a number of "fixes" for this - the simplest is to add a large (say 10µF) capacitor between the RESET and GND pins of the Arduino to filter out the reset pulse that would otherwise reboot the board.
There are also ways of disabling the reset within Windows, but that requires you to write your own software to interface with the board instead of using the serial monitor.
Some boards also come with a method of completely detaching the reset signal from the USB interface, but modifying the board itself isn't for beginners.
Just remember that once you have disabled reset through whatever means you will have to re-enable it (resolder the track you cut, remove the capacitor, whatever) before you can upload a new sketch.

So, how to use this for good? How to restart Arduino by means of /dev/ttyUSB0 device?

Note, that my Arduino is connected by USB, I don't believe there are some DTR line activating when I "open" the port. Also I don't understand, what is "opening" at all

The DTR line is generated by the USB interface chip form the USB protocol's line state data.  You can disable reset on Linux with stty -F /dev/ttyUSB0 -hupcl and re-enable it again with stty -F /dev/ttyUSB0 hupcl

I like the reset feature. How to use it for good? Suppose I did /dev/ttyUSB0 hupcl. Now how can I restart arduino?

You just need to open the port.  The simplest way from the command line is echo >/dev/ttyUSB0

If I just read /dev/ttryUSB0 with read or tail command, will this open the port also? Can I conserve power this way? May I start Arduino only once port readen and then shut it down again? I would like to read temperature each 5 min or similar, can I start arduino once per 5 minute then?

Yes, reading also opens the port. Any action on the /dev/ttyUSB0 device opens the port - even the stty command used to disable or enable resets.  You can't really use it to conserve power unless you put the chip into sleep mode after you have finished what you are doing when a reset would then start your sketch from the start again.  It may be usable like that, or not, depending on what you want to achieve.  You would always run once regardless, and then sleep until you next open the port.

This means your Arduino or ATmega328 is restarting due to another issue. Usually the Arduino will reboot when there is too much amperage draw which is called a brown-out.
It can also mean there is a bug in your code.
Please also note as you mentioned

I found, that each time I am restarting IDE, and opening serial monitor, a greeting text is printed there again, i.e. setup() method running again

The Arduino will reboot when opening the serial monitor.

How can restart happen exactly when I run IDE? How can "other reasons" know that I am restarting an IDE?

Can you post your code?

See my update please

See my edit to my answer


text:
Can't see second Arduino port on Ubuntu
I have connected two arduinos to /etc/ttyUSB0 and /etc/ttyUSB1.
Only one is visible in Arduino IDE. Why and how to force second?
UPDATE
$ ls -l /dev/serial/by-id
total 0
lrwxrwxrwx 1 root root 13 Jan  6 23:32 usb-1a86_USB2.0-Serial-if00-port0 -> ../../ttyUSB1

I.e. it shows port, which IS NOT SHOWN in Arduino IDE (only /dev/ttyUSB0 is shown.
ALSO
I can see both ports if run arduino with sudo. Should I run it with sudo?
Permissions are same
$ ls -l ttyUSB?
crw-rw-rw- 1 root dialout 188, 0 Jan  6 23:26 ttyUSB0
crw-rw-rw- 1 root dialout 188, 1 Jan  6 23:39 ttyUSB1

What means are you using to verify that both of these devices exist right now ?  Incidentally, unlike some other operating systems, these identifiers are newly assigned each time the device is connected, and may refer to different devices at different times.  You can even get the assigned numbers to increment with a single device, if a program holds the old device file open while it is re-plugged.

What does ls -l /dev/serial/by-id show?

You can also verify it with gtkterm. Click "Configuration" and "Port" and open the drop down menu "Port:". Check if they both are there. Perhaps you can try the Arduino IDE with sudo. Did you set some kind of permission to /etc/ttyUSB0? Remove all the Arduino and Java from the repositories. Unpack the newest Arduino IDE into a folder and start it from that folder. Be sure to remove the librxtx-java from the repositories (I use synaptic).

@Jot this looks blind guessing

@ChrisStratton I can communicate with them, and they answer differently

Dims, did you try to run the Arduino IDE with sudo ? Can you tell which Arduino boards are connected? Has one of them a unknown bootloader? Did you remove Arduino, Java and librxtx from the repositories ?

Terrible advice.  You should NEVER EVER run the Arduion IDE (or any similar software) as root.  It's not designed to be safe for such use, and you run the risk of leaving behind files which your normal user won't be able to clean up or change.  Instead, either set up proper udev rules, put yourself in the group that owns serial devices, and restart.  Or temporarily chown the device in question to yourself - but if you do that you'll have to each time you plug it in.

just because a user has permission to access a serial port, does not mean the a user has permission to access any other ports ... access has to be granted for each com port separately, or a user has to be belong to a group that has access to previously specified ports

You have to add use your user to the dialout group, as explained in the installation instructions for Linux.
sudo usermod -a -G dialout $USER

Then log out and back in again.


text:
Cannot power up Arduino Uno + Ethernet Shield with other than computer USB
I have successfully wrote a sketch for Ethernet Shield and Arduino. If I plug it into computer's USB, it works.
But if I plug into any other power source, like USB power adapter from iPhone or laboratory power source to power socket -- it doesn't work.
LEDs are doing various strange bursts, very different than if powered from computer.
What can be the reason?
UPDATE
I have updated sketch so that it doesn't refer serial:
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
// B6-62-C5-CC-48-81
byte mac[] = {
  0xB6, 0x62, 0xC5, 0xCC, 0x48, 0x81
};
IPAddress ip(192, 168, 10, 90);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

long requestCount = 0;
long upCounts[] = {0, 0, 0, 0, 0, 0};
long downCounts[] = {0, 0, 0, 0, 0, 0};
int currVals[] = {0, 0, 0, 0, 0, 0};
int prevStats[]= {0, 0, 0, 0, 0, 0};
int upThreshold = 1024-32;
int downThreshold = 32;

void setup() {
  // Open serial communications and wait for port to open:
//  Serial.begin(9600);
//  while (!Serial) {
//    ; // wait for serial port to connect. Needed for native USB port only
//  }

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
//  Serial.print("server is at ");
//  Serial.println(Ethernet.localIP());
}

void loop() {

  for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
    int sensorReading = analogRead(analogChannel);
    currVals[analogChannel] = sensorReading;

    if( prevStats[analogChannel] == 0 ) {
      if( currVals[analogChannel] >= upThreshold ) {
        prevStats[analogChannel] = 1;
        if( requestCount>0 ) {
          upCounts[analogChannel] ++;
        }
      }
    }
    else {
      if( currVals[analogChannel] < downThreshold ) {
        prevStats[analogChannel] = 0;
        if( requestCount>0 ) {
          downCounts[analogChannel] ++;
        }
      }
    }
  }

  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    //Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        //Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 2");  // refresh the page automatically every 2 sec

          client.print("X-Inthemoon-Request-Count: ");
          client.println(requestCount);
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            client.print("X-Inthemoon-Analog-To-Digital: ");
            client.print("Channel=");
            client.print(analogChannel);
            client.print("; ");
            client.print("Min-Value=0; ");
            client.print("Max-Value=1023; ");
            client.print("Value=");
            client.print(currVals[analogChannel]);
            client.print("; ");
            client.print("Up-Change-Count=");
            client.print(upCounts[analogChannel]);
            client.print("; ");
            client.print("Down-Change-Count=");
            client.print(downCounts[analogChannel]);
            client.println(";");
          }

          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          // output the value of each analog input pin
          client.print("Was counting: ");
          if( requestCount>0 ) {
            client.print("YES (request count is ");
            client.print(requestCount);
            client.print(")");
          }
          else {
            client.print("NO");
          }
          client.println("
");
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(currVals[analogChannel]);
            client.print(", up changes count is ");
            client.print(upCounts[analogChannel]);
            client.print(", and down changes count is ");
            client.print(downCounts[analogChannel]);
            client.println("
");
          }
          client.println("");

          requestCount++;
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    //Serial.println("client disconnected");
  }
}

The situation is the same:
https://youtu.be/vypaNOxZ5KI
It is plugged into Samsung tablet USB power of 2A, so insufficient current is unprobable reason.
UPDATE 2
I also tried to remove inclusion of SPI.h
UPDATE 3
If I connect another Arduino board  (but of the same vendor, it is from AliExpress), the behavior is the same.
UPDATE 4
I have compiled blink example and it works in any combination. If I connect Ethernet shield, then it blinks with both LEDs on Arduino board and on Ethernet shield.
UPDATE 5
I bought different Ethernet Board and it doesn't work too.
Please help. Have anybody ever powering Arduino + Ethernet not from USB?

This is basically unanswerable. Either your software requires communication from a host PC to function, or else some part of the setup is not what it is described to be.

Software is just Ethernet sample from here: https://www.arduino.cc/en/Tutorial/WebServer It is true that is contains writing to serial. Can this explain my situation?

Is the Ethernet shield status LEDs the same if you disconnect the network cable?

@MikaelPatel definitely not. If no Ethernet cable, then only power LED shines. If ETH cable connected, then other green LED bursting. But not the same way as when board works (if connect computer USB).

Have anybody ever powering Arduino + Ethernet not from USB? - yes I have one sitting around plugged into a wall-wart and connected to the (ethernet) network. It certainly works in that configuration.

It is plugged into Samsung tablet USB power of 2A, so insufficient current is unprobable reason. - I just measured my Uno and Ethernet card operating, and they were drawing about 200 mA of current.

Have you tried to measure voltage on board in different configuration ? This would help choosing between hardware and software problem (although update 4 makes me think about SW)

@Julien where to measure while connecting to computer?

@Julien can you check SW, what can be wrong there?

Between pins GND and 5V on the header. You should have between 4.5 and 5.5 on computer. The interesting measurement is on the not working power sources. I've not seen anything obvious in the source. You will need to learn to debugg ;)

@Julien can you provide some hints about how to debug in my situation?

@Dims Have you done the voltage measurements ? I think when ethernet powers up the peak current consumption makes the device reset. Try also pressing reset button instead of just plugging the USB. does this give same issue ? For debug, as the problem only occurs without connection to computer we cannot use print. You may try to add some 1s delays and LED blink before and after "critical" function call to see if the code is executed of if the device resets (or write some flags to EEPROM).

Sorry I didn't see this earlier but I suspect you have a bad earth, because:

It works with the PC
You are using a wall wart
You are wiring your board to another electrical source (Ethernet)
You are saying the LEDs are flashing differently.

Run a lead from the GND connector on the board to an Earth point.
(It might be the Ethernet that is at fault, but unless you have access to the switch I don't know how you could ground that properly)

Indeed, bring the board over to a friend's house, check if it also happens there.

Good idea, will try!

There should be absolutely no difference between powering your Arduino from a computer USB port or a wall plug, especially if you keep your serial monitor closed.
So this is the debug procedure I would advice:

disconnect the shield
connect the Arduino and upload a firmware with

no calls to Serial, but the most important one you must avoid is the while loop in the setup() function
a short blink of an LED (you can use the onboard one, if you wish so) every time the loop() function iterates

power your Arduino (without the shield attached) from your computer with no serial consoles and check the LED blinks at constant intervals
power your Arduino (without the shield attached) from your wall plug and check the LED blinks at constant intervals
disconnect the wall plug, attach the ethernet shield without an ethernet cable, reconnect the wall plug and check the debug LED and the LEDs on the shield are all blinking as expected
plug the ethernet cable and hit the Arduino reset button and check all the LEDs are blinking as expected

Possible faults i can currently think of:

STEP 3

the firmware running on your board is incorrect: double check the compilation and upload process has completed successfully and you have no error in the Arduino IDE console

STEP 4

the firmware still contains some code which expects some input from the serial console: start opening the libraries you use in search for such code
the voltage measured at the board between GND and 5V pins is insufficient and the board browns out: check the voltage is above 4.5V and the USB cable is not damaged or faulty

STEP 5

some of the code inside the ethernet shield library is trying to read data from a serial connection: check the library code again
some of the components on the ethernet shield are faulty and they are pulling enough current from your wall wart to actually make your board go into protection (hard to believe, a 2A serious wall plug should be much better power source than your PC)

STEP 6

same as for step 5, but your ethernet cable might be playing a role

This might not be an answer per se, but it might help you find out the answer you need.

This won't work, the code is designed to run Ethernet shield and may be blocking forever at some point if the shield is not present. Moreover Dims already wrote that a simple blink code works with and without Shield. The problem only seem to occur when using the ethernet library.

@Julien i didn't open the Ethernet library, so I can't state you are either right nor wrong when you say may be blocking forever, but I believe he can give a try to this.
Also, he said the board is blinking with the blink sketch, but I am suggesting to use a LED pulse at the beginning of his loop() function as a debug measure.... something you also suggested in the comments.

Maybe your laboratory power source is of poor quality. A computer's USB is a good power source. Try using a pack of 4x1.5v AA batteries. I have use this setup with arduino+ethernet shield+cheap servo.

Tried eveything, including this.

Maybe the alimentation part of your arduino is broken. Do you have another one to test ?

I too have had this problem with a Mega.  It was working with my SCADA package, running on linux and you could ping the Mega/ Ethernet board, but then something changed, and it wouldn't run/ read using the ehternet port.  Had two units, and both behaved the same.
When connected to the programming laptop ( runing W7) and the ethernet port, and running serial monitor, ethernet functions would work.  De powering and repowering using W7 usb port wouldn't work.  Tried removing all calls to Serial.print(ln) via if Debug type logic , didn't fix the problem.
Restoring the Serial messages didn't change the behaviour.
The "fix" is to press the reset button on the ethernet board after powering up, power source independent.
Giving the stack a general reset via the reset pins doesn't work, it needs to be the reset button on the ethernet module.
Did it via the unit connected to the linux machine and instantly got ping, and the SCADA system reading data.
If anyone can shed more light on the need to reset the ethernet module after power up I would be delighted.


text:
What if I just connect 5V DC to my UTP?
Here is the image of Ethernet shield near RJ45 socket:

These small boxes are probably SMD capacitors which may mean, that internal board is glavanically disconnected from the UTP line.
Is this true?
If this is true, then what will happen, if I pass 5V DC current just into my UTP? Won't I be able to wire appropriate conductors just into Arduino power input? Won't I be able to power Arduino this way?
The question is about not using premade PoE splitter. I have an injector, which injects 5V into line.
UPDATE
I found my injector put power to lines 4,5 and GND to 7,8. Can I take this power on Arduino side?

Not exactly. That RJ45 connector labeled HR911105A is internally connected like this:

It's possible with PoE version (but I suppose not with 5V but more like 12V or so)
Or there are variants without PoE module connected but with support, that should be possible to use 5V if you wire it correctly)
Or you can use external PoE injector and extractor:
For 100Mb networks are two unused communication pairs used as power lines:

What is the  purpose of connecting 4,5 and 7,8 on your first schematic? Lines are unused, then why to connect them this way?

HR911105A schematics just means I can't reach my power lines from board side, right?

Yes, you can't, but if you use injector/extractor from the secon picture, it doesn't matter in this case. Just don't forget wires are not suited for much current. (that's why some injectors are using 24 or 48Volts)

You could replace the RJ45 socket with a different one (-;


text:
Arduino Uno R3 not recognized by computer, TX and RX not blinking, neither are lit. Is it dead?
I was trying to make my arduino uno r3 to work on my Linux machine (including the IDE), but it wouldn't. At first I thought it was a software problem. Added myself to different groups and did everything, people discussed on the forums. It didn't work. It wasn't recognized by the computer at all. I reinstalled. Nothing again. Thought it was a hardware problem of my computer. Tried with dad's (Windows 7 machine). Didn't work. Then I saw that the two leds (TX and RX) are not blinking, neither are lit. I started doing a research on the internet but everybody suggests doing the loopback test from the IDE. My Arduino Uno R3 is not recognized by the computer, therefore the IDE. Is there any way to check if it's dead or if it's a minor problem?
Edit: I read a lot on the case last night and I reach to the conclusion that my ATmega16u2 (the usb-serial chip, I'm sure it is 16u2 and not 8u2, it's written on the chip itself) might be dead. Tried to reflash the firmware but cannot get it in DFU mode (as it says in this article click here). dfu-programmer (the Linux application) throws the following error: dfu-programmer: no device present. What to do?

Have you tried seeing if a programmer can talk to the two MCUs?

Pretty new to electrical engineering, what does MCU stands for. Google gives too much results.

"Microcontroller unit", or just "microcontroller" for short.

Ok, but how to check if the programmer can talk to the MCUs?

Hook it up and run the programmer software, and try to read something from them.

There is a chance that your bootloader is not working anymore. You can burn a new bootloader to the device with another Uno, there are nice guides on the Arduino-Website.

Before you can access serial TX/RX on Arduino make sure USB to serial converter on the board is working. To check it (on Linux) do the following:

Open the terminal, type 'dmesg' and press 'enter'. You will see some output with timestamps (number in square brackets). Note the timestamp of the last line. Run dmesg several times to make sure nothing writes to it and you still see the last timestamp.
Plug your board into USB port and run dmesg once again. You should see something like the output below. The first line is the last line of dmesg prior to plugging in the Arduino, the second line is actual detection. The board I used in this example is 2560, UNO will give you similar output. If you can see this output your board is recognized just fine. If you can't see it then either the USB to serial chip (just another AVR MCU) on the Arduino or USB host in your PC or both are defective.

    [279152.351690] systemd-logind[867]: New session c51 of user lightdm.
    [280362.732094] usb 3-2: new full-speed USB device number 3 using uhci_hcd
    [280362.931266] usb 3-2: New USB device found, idVendor=2341, idProduct=0010
    [280362.931275] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
    [280362.931282] usb 3-2: Product: Arduino Mega 2560
    [280362.931288] usb 3-2: Manufacturer: Arduino (www.arduino.cc)
    [280362.931293] usb 3-2: SerialNumber: 64938323331351213172
    [280362.986579] cdc_acm 3-2:1.0: ttyACM0: USB ACM device
    [280362.988470] usbcore: registered new interface driver cdc_acm
    [280362.988473] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
    [280362.732094] usb 3-2: new full-speed USB device number 3 using uhci_hcd
    [280362.931266] usb 3-2: New USB device found, idVendor=2341, idProduct=0010
    [280362.931275] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
    [280362.931282] usb 3-2: Product: Arduino Mega 2560
    [280362.931288] usb 3-2: Manufacturer: Arduino (www.arduino.cc)
    [280362.931293] usb 3-2: SerialNumber: 64938323331351213172
    [280362.986579] cdc_acm 3-2:1.0: ttyACM0: USB ACM device
    [280362.988470] usbcore: registered new interface driver cdc_acm
    [280362.988473] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

dmesg isn't changing it's output at all. lsusb doesn't detect it also. /dev/ttyACM0 or /dev/ttyUSB0 are not created.

If you need an answer to a question which part of my answer answers your question then please ask another question.

What? Why? Your answer doesn't answer my question, it just starts a series of "Do this!" and "Doesn't work comments".

Delete your Arduino IDE, but store your libraries if you need in future.
Download Arduino ERW 1.0.5 from here: http://forum.arduino.cc/index.php?topic=118440
Try your steps again with your connections belong to your schematic.

The hardware doesn't work on two independent machines and you're blaming the software?

Did the other PC has Arduino IDE or Arduino ERW? I guess, it was Arduino IDE not ERW. Shall we try ERW? If not, I will be in silence.

Arduino ERW is only for Windows and I use Linux. For now, I don't have a Windows PC around me, but even if I had, I need to make it work under Linux. I understand that, at least I will find out if the Arduino board is broken, but...


text:
What maximum length of wire can I use to connect a push button to an Arduino?
I am trying to get 8 stop buttons to cause an Arduino UNO to activate a single relay!
The stop buttons have been placed 30' to 250' away from the Arduino uno board.
Q: How far can you go with 5v and still get signal back?
Q: Is there a way to boost the signal?

Are the buttons all on the same pair of wires? Or on 8 separate pars?

Q: how far can you go with 5v and still get signal back?

That depends on two main factors:

The gauge of the wire
The noise in the environment

Assuming a low-noise (where noise is negligible) environment, we will first look at the wire.
All wire has an inherent resistance to it.  The thicker the wire, the lower the resistance.  This table has good information about the resistance of different gauges of wire: http://www.powerstream.com/Wire_Size.htm
Given a typical arrangement where the internal pullup resistor of the Arduino's IO pin is used to create an "active low" arrangement (pinMode(x, INPUT_PULLUP) the equivalent circuit can be seen as this:

Given that the "Input Logic Low" (VIL) level of an input pin (according to the ATMega328P Datasheet (Table 30-1) is 0.3Vcc, and Vcc is 5V, the input low level would therefore be 1.5V.  The voltage present at the IO pin has to be below 1.5V in order for the input to be seen as a LOW.
The circuit, when the button is pressed, can be simplified to this:

That is a simple voltage divider.  The formula for calculating Vout is (R2/(R1+R2))*Vin.  We know that the Vout limit is 1.5, and Vin is 5V.  Also that R1 is approximately 50KΩ (very approximately).  So we can rearrange the formula to:
R2 = R1(1/((Vin/Vout)-1))
Substituting our known values we have:
R2 = 50,000 × ( 1 / ((5 / 1.5) - 1)) = 21428.57Ω
So the total resistance of the wire permissible is around 20KΩ assuming the internal pullup resistor is 50KΩ (note: it could be as low as 10KΩ or as much as 70KΩ).
Divide that value by 2, since the wire has to run twice the distance (once there and once back again) and you get a total resistance of around 10KΩ for one leg of the journey.
Now assume a wire gauge of 24AWG.  That has a resistance of 84.1976Ω/km.  So we can work out that 10,000 / 84.1976 = 118.77km.
So with 24AWG wire you could theoretically have your button about 100km away from the Arduino and just about have it still register properly.
But of course that's with no noise, and there will be noise - especially over that kind of distance.
The noise will basically make the voltage seen at the input vary randomly around the theoretical value.  Those wires act like great big antennae, and they pick up all sorts of stray EMI.  The longer the wires the more noise there will be, and consequently the lower the voltage you will need to aim for (or higher voltage if using a pull-down arrangement - just turn the whole thing upside down) to keep the logic level below (or above) the right threshold value.

Q: is their away to boost the signal?

Yes, you can use a higher voltage.  There is nothing to say that you have to interface your button directly with the Arduino.  There are many ways of having your button switch a higher voltage on and off and use that to trigger the Arduino.  The simplest (and also the safest) may be to use an opto-coupler.  Use your button(s) to switch a 12V power supply on and off, and that then passes through a suitable resistor to power the LED in the opto-coupler.  That then switches on the built-in transistor to turn on the IO pin.

Another option may be to use a reliable communication bus with a small microcontroller at each stop-button point (maybe something like RS-485), though that may be overkill for this kind of application.

I agree with Majenko. The noise over any sort of moderate length is likely to swamp the 5V in the wire. However as he suggested you could use an opto-coupler (like MIDI does). The opto-coupler is activated by current not voltage, and whilst mains and other sources may introduce quite high voltages they are unlikely to introduce high currents. The opto-coupler also lets you use a higher voltage, thus overcoming wire resistance. Its third benefit is isolating the input pins from any high voltages that might appear in the wire.

While the galvanic protection may have some advantages, note that you can make what is basically a current-mode input by using a smaller pullup resistor.  Many practical systems also use differential receivers.  There are also transmission line effects like reflections to consider, though a system with a mechanical switch will already need debouncing for that which may deal with the line reflections too, until the distance gets to be huge.

Majenko's answer is probably the safest option. There is, however,
something simpler that you can try:

Use a strong pull-up (or pull-down). Something around 1 kΩ will
make it quite difficult for the noise to pull your signal low, at the
cost of increased current consumption.
Connect each push button to the Arduino using a twisted pair of copper
wires. This will minimize the inductive pickup effect.

PS the increased power consumption is only while the button is being pressed.


text:
Arduino + NRF24L01 mesh network implementation
TL;DR

I want to produce a large self configuring wireless mesh network using Arduinos and NRF24L01s transceivers. These have been chosen because they are capable of achieving the requirement and the application is cost sensitive.

I cannot find any "plug it in and run" system , although the RF24Mesh, RF24, RF24Network libraries produced by  TMRh20 / Avamander have the capabilities to produce such a system.

Information on suitable software is sought.

I'm using Arduino / C++ on a project that requires mesh radio connection of, ideally hundreds of sensors*. If required the network can be partitioned to overcome addressing or traffic capacity issues, but this will probably not be necessary.
I am using NRF24L01 transceivers due to acceptable performance, energy use, range** and cost issues. There will also be one or more cellphone-network gateways per mesh network. I am also investigating the use of LORA in some situations.
I can currently achieve NRF24L01 + Arduino capability over a few nodes.
I could extend this to a semi-indefinite number of nodes but not in a sensible manner
Requirement:

I wish to implement a "many node" wireless mesh network* with automatic inclusion of new nodes, and the ability mainly to transfer data from nodes to a master, but with some master to node traffic. Average data rate per node can be as low as is required to ensure operation with whatever number of nodes happen to be connected. (Nodes do not 'move about' physically, but new nodes may be added and others may occasionally be disabled.)

I am capable, needs must, of wading through what is available and 'learning the hard way' but hope that a reasonably complete solution is available. I have a large amount of experience in software development on microprocessors / microcontrollers over about 45 years, but much of this is 'bare metal' in assembler.
I was hoping that something close to 'it just works' may be available.
I have spent "many hours" internet searching to find what is available, and have been surprised at the extremely small number of sites reporting availability of anything close to this specification. The libraries implemented by TMRh20 / Avamander (RF24Mesh, RF24, RF24Network) as commented on in his blog here seem fully capable of this task but still seem to require me to know rather more than I do - so far :-)
I have not found any posts in this group that address the requirement.
Any sites that I have found propose multiple node networks are useful for small tasks but limited in extensibility and lack mesh addressing automation features.

Example only. This site offers Arduino Wireless Network with Multiple NRF24L01 Modules but requires a very 'manual' network construction process.

This probably comes closest of what I found  - Cheap Arduino mesh using RF24 radio modules. It utilises RF24, RF24Network and RF24Mesh libraries but is also relatively incomplete.

Any advice on how to achieve my aim would be welcome.

*The application is the management of solar lighting, and usage and availability / status reporting for women's toilets in refugee camps. The ability to remotely reconfigure energy use profiles in low sun periods may be useful. Additional features such as alarm provision may be considered.
Information can include lighting operation statistics and current state, energy use and battery state, toilet usage and availability, ... .
**I am aware that some "clone" versions have range issues.

Note:  The NRF24L01 was chosen due to a combination of cost and low current when continuously receiving. The latter removes the need for time-crucial synchronisation and greatly simplifies multi hop mesh implementation. Energy budget is extremely limited and a far easier eg ESP8266 based solution is, at least so far, untenable.


text:
How to reverse BLDC motor using programming arduino?
I bought ESC from here but it rotates motor in one direction only.
Is there any program which will control direction of rotation clockwise or anticlockwise with same wire configuration.

I don't know - that page won't load.  If the ESC has a direction input then you need to control that with an IO pin.  If no, then it's probably not possible.

R/C Hobby ESC's come in unidirectional (for aircraft) and bidirectional (for surface vehicles) versions.  If you have the latter and configure the throttle ranges correctly, part of the PWM range will be reverse.   But you may not be out of luck even with the former, as many ESC's are built in common ways around ATmega or SiLabs chips for which open source replacement firmwares have been published, and these typical have a bidirectional option.

If above link does not work it is the RS695 unit here. With same leads, maybe no. If you use a DPDT relay (double pile changeover) to swap 2 leads it will usually reverse direction.

Manual here - not helpful in this case, alas.

If you mean the FUFEI-12A, a web search shows several hits implying people have put the popular "simonk" firmware on that, and there are versions of that online which have been modified with reversing.  So the goal seems achievable, the question is if it would be more expedient to just buy a small car ESC.  I'd be very hesitant to use a relay, both given the currents involved and that the ESC may really, really dislike having the windings interchanged when it is even slightly active, so careful locking out will be required.


text:
Using an Arduino to switching a grounded load powered by a 12 Volt supply
I wish to use a MOSFET to drive a 12V rated LED strip from an Arduino.
The negative side of the LED strip must be connected to ground, so that means that the driving MOSFET must be between +12V and the LED strip.
This is what I have tried so far.

The load must be between my mosfet and my car battery GND.

In your existing arrangement.
Swap to P Channel FET
Swap drain and source leads (right hand two).
This will work for up to 5V feed to LEDs.
To get 12v operation you will need to add a driver between the FET gate and the Arduino.
see circuit diagram below.

To operate with FET on the HIGH (V+) side when V+ is greater than the rduino's supply voltage, the FET must either

Be P Channel with FET source to +12V and FET drain to load+ or

An N Channel with gate drive above V+.
The gate drive to the FET must go to about +12V to turn it off.
The Arduino will only drive it to +5V.

As you are unlikely to want to provide an extra high side drive the P channel option is preferred. This could be eg:

A "jellybean" bipolar transistor or small FET worth a few cents) and a few resistors, or a small N Channel MOSFET and one resistor

or

An opto isolator.

Transistor driver:
Bipolar transistor NPN (BC337 / BC817 or similar)(ANYTHING NPN will work).
R1 = 10k resistor Arduino out to base.
R2 = 10k FET gate to +12.
If an N Channel MOSFET is used for Q1 then R1 is not needed.
This could be a  5LN01SP IF you can get them - no stock Digikey.These have a very low Vgsth (turn on voltage)
Otherwise you can use a 2n2222, VN2222, BS108 or similar logic-gate N channel MOSFET.
eg VN2222. Many variants of these are widely available and low cost.

simulate this circuit – Schematic created using CircuitLab

won't it drain the 12v battery to have a link beetween +12 and GND throuth R2 ? 2) I have multiple led strips, can i simplify the circuit if i use it multiple times (reuse some components) ?

@hanoo You should be able to work out the current drain answer yourself. Treat all such as a learning exercise and not just blind copying or you will not progress BUT :-) ->  (1) R2 is 10k Ohms (see text). Current in 10k is I=V/R = 12/10k = 1.2 mA. Current in LED strip = Power_Watts/V. Here for say 5 Watts = 5/12 = 0.417A = 417 mA. ie R2 current is about 0.3% of LED current at 5 Watts = trivial. (2) You can place any load that works on 12V at output of M1 - so eg N x 12V LED strips as long as the FET current rating is adequate. ....

.... | If you want to drive multiple FETS at once you can connect FET gates to Q1 collector directly. This works if M1 is MOSFET. If M! is a bipolar transistor you need a resistor between Q1 collector and M1 base in each case.


text:
Adafruit motor shield 1 and Arduino Pro Mini
Can any one tell me how to connect Adafruit motor shield v 1.0 with Arduino Pro Mini 5v 8 Mhz. Motor shield uses which pins as I want to replace my Arduino UNO to Pro Mini and need re-wiring. Tried it using jumper cables but did not work. Please help...

Product page here
Manual here
Larger version of schematic here
Schematic:

Providing links to ALL relevant gear would help. If it did not work "stand alone" with jumpers (eg NO Arduino) then you do not understand the shield pinouts.


text:
Issue with PWM output pin
I'm just starting off with using the Arduino and was learning about PWM
(http://arduino.cc/en/Tutorial/PWM).
Below is what my circuit looks like.

Below is the very simple code.
const int pinNine = 9;    // LED connected to digital pin 9

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
  // set the digital pins as outputs
  pinMode(pinNine,OUTPUT);
}

void loop() {
  analogWrite(pinNine, 0);
}

I was expecting my LED to not be lighted as its a 0% duty cycle. I even change the pinNine outputValue to (64, 127, etc) but for some reason the LED is always lighted. Any ideas?

Loks correct, alas. Try another pin to see if it changes. Try digital write on / off to see that port behaves as expected. Bad port pih possible. What pin is serial on?

Check that the ground (-) rail on the breadboard is definitely going to ground on the Arduino. If it's going to +5v instead, and if your LED is the wrong way round, you could end up with it being lit all the time. (Pin 9 would basically be acting as ground.)

See my updated answer. Your code runs as expected on a Nano. Problem is probably hardware related.

Where does that red wire go to? i.e. Is the other side of the led connected to 5V by any chance? Try running the Fade example sketch (File=>Examples=>01.Basic=>Fade).

Ok, it seems my understanding of the PWM was wrong. I tried the circuit and code from here (http://arduino.cc/en/Tutorial/Fade) and it worked as expected (fade in and out).
Actually when i wrote my original code i was expecting the LED to blink. So, as i got closer to 255 i was expecting it to spend more time being 'lit', as compared to 0 where it should spend less time being 'lit'.

I even change the pinNine outputValue to (64, 127, etc) but for some
  reason the LED is always lighted.

It being lighted makes sense. What i missed out was it being dimmer when the value was lower.
Thanks for all your help..

Added at top:
Your code runs correctly on a $US3 Arduino Nano :-)
It seems extremely likely that you have a hardware problem of some sort.
If you have a voltmeter you can try these easy checks.
I carried these out to be sure that I got what was expected and the results are as you would expect them to me. Use a meter set to DC Volts - typical common meter circuitry averages the PWM well.

Remove LED etc connection to pin 9.
Measure the voltage from the 5V pin to ground. If powered from USB this will usually be slightly below 5V.

Run your code with the analogWrite set to 128 ie
analogWrite(pinNine, 128);

Measure the voltage on pin 9 relative to ground. It should be close tohalf the voltage on the 5V pin in 1. above. This is because the analogWrite value is controlled by PWM with values from 0 to 255. 128/255 ~= 50% so output is 50% of Vref = 5V by default. in a 5V system.

Set analogWrite to
 analogWrite(pinNine, 25);

The voltage on pin9 should be about 10% of the voltage on the 5V pin.

IF you get approximately the voltages shown in 3. and 5. your code is working OK and your hardware is OK.  If not then 'summat aglae'.
Try another analog pin.
Check that the red wire to the LED goes to UNO ground.
The voltmeter is a surer way of checking that the LED is as you can see actual numeric values that result.

OLDER:
It always helps greatly if you show PIN IDs on photos so people can be confident re what you have done.
If you view the whole UNO-R2-R3 connector with numbering it is obvious that the important pinouts are the same.
If however you view part of the connector with no numbering/ pin names shown,  then on the R3 there are additional pins on the ARef end of the connector which make comparisons'more difficult).
You APPEAR to have an Arduino UNO R3
It would help if you gave actual model and weblink in future "just in case it matters". .
You appear to have connected to pin 9  (as you intended to)
Pin 9 has PWM capability, as required.
It seems that your code should work.
Thusly

IF the red wire connects to ground the circuit seems electrically correct.
Does it?
Code LOOKS OK.
Try digital write on / off on pin 9 to see if LED changes and that the port behaves as expected. A bad port pin is possible.
What pin is serial on?
Try another pin with PWM capability to see if it changes.

ARDUINO UNO R3 from UNO home page
The connector pinouts vary widely between models of UNO.

Did they change pinout for UNO between versions? I'm pretty sure he wired it correctly. Edit: You can see from the reset button on his picture that it is Rev.3.

@Allan Look at the page referenced to see the differences. | I imagine that a dyed in the wool Arduino aficionado can tell not only the version but which corner of the vineyard it was grown in and how long it was left in the cask to mature. BUT when asking question and YOU have the information to hand it makes sense all round to tell as much of what you know that is relevant so question answerers can avoid duplicating the 'research'.

I agree completely that it should be noted when possible. OP probably didn't realise this would come in handy (I don't even own an UNO..:) I don't see anywhere in your link that the pinout has changed. They all feature the same chip, having PWM on 3,5,6,9,10,11. My old Duemillanove is the same :)

@AllanNørgaard - loose terminology on my part - I meant the connector pinout or functionality. In his photo you cannot see the module's labelling  - which can be seen on the photos I have added. He has connected it correctly and on my $US3 UNO the code runs as expected. He has some sort of hardware issue. I'm about to update my answer.

@Russell McMahon . Thank you. I will remember to show PIN IDs and actual model next time i post. Maybe a 'top' view of the circuit is most ideal.

Flat side of LED is -. This means that your white wire is on - side and your red wire on + side. Therefore your power rail connection is reversed... and therefore your LED is ON when you send 0 on PWM. By the way, you will set the LED OFF by writing 255 on PWM.
Solution: connect power rails correctly and everything will be back to normal.

Maybe. H did say "... I even change the pinNine outputValue to (64, 127, etc)  ...". So that depends on the range of values of "etc". At 5V you'd expect ~~~~ I=V/R = (5-3)/220 =~ 9 mA and at 2.5V you'd expect close to 0 mA. As he said he's tried PWM level 128 at ~= 2.5V you'd expect the LED to change very substantially. |"Flat side"? - I need to upgrade my (old) eyes :-).

Yes, I saw what he wrote. But it may be difficult to see the intensity change between 50% and 100% as our eyes are not linear, mostly for a bright light dot. He didn't write that he tried 255. Concerning the flat side, this is what I (old eyes too) see on the left of the LED on the picture (not very distinct I must admit).

You might be right. No certainty until he answer questions. I too asked about polarity of feed. | BUT it seems likely he'd notice at full and half voltages, from 0 to 128 the voltage halves but the LED meeds a minimum Vf to operate so brightness will be way down. |An InGaAlP green LED may gave Vf in the 1.7V - low 2.xV range and an InGaN green Led may be 2.7V up. Even at 1.7V and 5V drive I~~~= (5-1.7)/220 =~ 15 mA and at 2.5V ~~~= 4 mA. That's a very low voltage green LED and for higher Vfs the ratio is even larger. When looking for changes anything over 2:1 is extremely noticeable.

@RussellMcMahon. As he is not filtering the output, he will never generate 2.5 V, so the average current should be linear with the code. What is not linear is our perception of brightness. But according to his answer below, the issue was more fundamental and now things are solved.

yes/maybe/no/ ... :-). I build LED lights - that does not make me automatically right :-) but I am experienced therewith. . Arduino PWM is (I read) 490 Hz so yes, minimal filtering with stray capacitance. | Eye and LED responses combined are close enough to linear with these levels of current. At 2:1 most people can distinguish between two sources viewed one at a time. When viewed simultaneously a difference of 1.5:1 is typically visible. For adjacent wall washing > 20% difference can be seen by average user.

I have a few things you could try:

Remove pinMode(pinNine, OUTPUT), this is only used for digitalWrite(), the PWM controller might be affected by this.
Did you select the correct Arduino Chip in the IDE? Arduino maps pin 9 to a hardware pin (PB1 for UNO), which is not consistent between different boards
Try inserting a delay(100) after analogWrite(...). I'm not sure if the analogWrite call restarts the PWM cycle, resulting in very fast switching that might be seen as 'always on'

Other than that, your sketch seems to be correct. I assume the black wire in the breadboard is wired to Ground, correct?


text:
Ping sensor with three or four pins?
I bought a Ping Ultrasonic Range Finder. It has four pins that you connect to the Arduino. I see in Internet that they have three pins. What does represent each pin and where to connect it to? I have an Arduino Uno Starter Kit.

The sticks (they are really called pins) have these little white marks next to them. They're called letters. You read them and they tell you what the pins do.

@Majenko It's so thin I don't think I will read something there.

I said next to not on.

@Majenko Right, you're right. What does it mean "echo", "vcc" and "Trig"?

You have 4 pins.

Vcc: +5V supply voltage (it stands for Collector Voltage)
GND: Ground.
Trig: Causes an ultrasound pulse to be generated (it stands for Trigger)
Echo: Tells you when an echo has been received.

You can see how to wire and use it here: http://www.instructables.com/id/Easy-ultrasonic-4-pin-sensor-monitoring-hc-sr04/

In what do I use the trigger pin?

@PichiWuana That link tells you.


text:
Microcontroller controlled power supply
Can anyone assist me to make a power supply whose output voltage will be controlled by an Arduino, with the latest voltage setting automatically saved in non volatile memory?
I am in an OJT (On the Job Training Scheme). I was given a task to make a Arduino controlled voltage variable power supply whose outputs can be switched between several preset values using pushbutton control.   It's like switching between two different outputs when a designated button is being pushed.
Here is what I have done so far. I made an LM317 based power supply with the output voltage controlled by a potentiometer. I followed this youtube tutorial. It works well but I was ask to upgrade it.
Instead of using a potentiometer to adjust the voltage, I wish to use switching buttons to choose between two or more preset voltage levels. Each switch buttons have their corresponding voltages.
This link may also be relevant.
Code is given below the circuit diagram.
ARDUINO AS A POWER SOURCE ALTERNATOR

I suggest that you make sure that your words mean what you intend. The example (via link) that you gave  switches between two batteries. An "Alternator"  is an "AC Generator" a rotating electromechanical machine used to turn mechanical energy into electrical energy.An Alternator regulator is a device which controls the output voltage (usually) of an alternator. If you wish to swap between two batteries alternately you want a program controlled battery selector with selected-battery stored in memory.

@RussellMcMahon - Yes I need a program that swaps two different power source.

@RussellMcMahon It's a simple adjustable power supply and I've made one. I followed this youtube tutorial [link] (youtube.com/watch?v=F-ahtojVl4M). It works well but I was ask to upgrade it, instead of using a potentiometer in adjusting the voltage, he suggest to have a swicthing buttons which I can swap two or more power sources automatically. Each switch buttons have their corresponding voltages. Can you help me figure out how to apply it maybe by using an arduino?

AC  - I have extensively rewritten your question based on the original plus what you said in comments.I did this because the words you were using gave a wrong impression of what you say that you want to achieve. If you do not like my edits please modify them. I could easily provide an answer BUT it is useful to see what other people say.

@RussellMcMahon Thank you for editing the question. I appreciated what you've done. That was exactly what I am supposed to ask.

@RussellMcMahon Sir, I would gladly wait for your answer. That would be a great help.

An important question: Is this like an assignment or test where you are trying to learn or show what you know or will somebody use the end product for an application ? We can answer either type of question here but the approach taken is different in each case.

If you want to output preset voltage levels in distinct steps, rather than an 'analogue' range from X volts to Y volts, then the answer is in the datasheet for the LM317:

Connect each of the INPUTS through a 1k base resistor to your Arduino pins. Selecting different values for all the resistors will of course allow you to vary Vout by turning each transistor on or off, by themselves or together. You can use any standard transistor: 2N3904, 2N2222, BC548, etc., but I might elect to use a (low power) MOSFET like a BSS138 instead (and omit the base resistor). Of course you can use add more resistor/transistor lines if you want more output options. I recommend using R2 so that Vout is always limited, otherwise - if Vin is quite high - you may damage whatever Vout is powering due to some runaway voltages.
Calculating resitor values is your mathmatical challenge. If you really apply some brainpower you can change Vout in linear steps with minimal Arduino pin usage:
'Input' states            Vout
  A  B  C  D            (/volts)
  0  0  0  0              5.00  [Vmax set by R2]
  0  0  0  1              4.75
  0  0  1  0              4.50
  0  0  1  1              4.25
  0  1  0  0              4.00
   ...  ...                ..
  1  1  1  0              1.75
  1  1  1  1              1.50

This shows that with N Arduino pins you can have (N^2)-1 levels. Using R2 gives your final level whne all INPUTs are off.
If you want to be able to drop Vout down to 1.25V, add transistor/MOSFET that connects R1/ADJ straight to ground. Turning this on will drop Vout to 1.25V, irrespective of the state of the other INPUTS.

I would like to add few extra notes for this interesting approach for digitally control the voltage output. What described in the original datasheet is in fact a very "minimalistic" 4 bit, DAC circuit. For some rationale it would help to study this two docs from AnalogDevices: One and Two.

I am wary about providing a complete answer without knowing what is expected of YOU - is this like an assignment where you are being tested on understanding and what you have learned. The following will be useful to you. You need to give some more details if you want more assistance with these circuits.
Here is an existing stack exchange question. I see that I answered it in 2011 :-).
How does this power supply circuit work? (MCU + LM317)
The circuit and my previous answer should help greatly.
In your case you apply PWM  using analog.Write to R1.
You MUST understand how the circuit works and not just apply it.
The original appears to be here with circuit description, with diagram here

On this page from EDN magazine is a similar circuit. The pot between pins 1 & 5 would not usually be used.

In another stack exchange question there is a very useful caution about the opamp's load limits in a similar circuit.
Problems controlling an LM317 with an op-amp - 2013

You can get many possible ideas here - search = lm317 voltage controlled power supply - this is an immensely powerful way of finding information -  IF a picture is worth a thousand words then this is priceless. Note the terms used.

Bad designs:
There are some bad designs around which can look OK but behave badly.
Despite the detailed writeup,
This poor design uses "open loop control" and the output voltage varies with load and is only "sort of controlled".
I was asked why I think this circuit is "open loop". I could not find a complete circuit diagram on the page but this diagram was shown of the output stage. If this is NOT the actual circuit used it would be "good" to have the complete circuit easily accessible.

IF this is the actual circuit used, then:
Call the transistors Q1 Q2 Q3 Q4 in left to right order.
Call intended output voltage = Vset = Vdac x (R6 + R7)/R7.
Vdac is applied to Q1 base and amplified by Q1 & Q2 to form the desired output voltage, appearing at Q2 collector. A lesser voltage appears as Vout due to the Vbe drop in Q3 & Q4. As load current increases Vout will "droop" thereby increasing the drive to Q4. This in turn increases the load on Q3 and Q3 emitter voltage will droop increasing Q3 drive. The actual Vbe voltages will depend on the beta (current gain) of Q3 and Q4, their temperatures (which depends on heat sinking, load and ambient temperatures) and manufacturing variation. At no or very low loads Vout will be about 1 Volt below Vset. At heavy loads Vbe_Q3 will be in the 0.6-0.8V range and Vbe_Q4 will be 0.8V+. So Vout will be around 1.5+ Volts below Vset and variable with (at least) the factors mentioned above.
This is still a usable design, but Vout could 'easily enough' be made far more stable with load by feedback from Vout to the Q1-Q2 amplifier - essentially forming a comparator that compares Vset and Vout.
Update:
This [reference provided by NilsB] MAY be the actual circuit diagram or close to it. It's an earlier 2005 design which presumably is much the same as the later version.

It appears not to be open loop in the broad sense. The Vout is still decoupled from Vset, with the software feedback allowing him to adjust the Vset to make Vout what he wants on a "nudge it and see" basis. ie Vset is not a fixed ratio wrt Vout so he can never set it and have it "just track". So it does not automatically stabilise for load or temperature changes and there is a variable drp between k x Vset and Vout.
Software is fastish but not as fast as a closed loop in hardware which allows Vout to track Vset within mV in a time delay as short as you provide an error amp loop for.
That's a 2005 circuit diagram so an earlier version than the originally cited V3 - one assumes he has not 'gone backwards' in design concept. It's strange that he does not include the whole circuit diagram or a good discussion of the provided current and voltage feedback. He may have wanted to sell kitsets rather than give away his final design. The link to the kitset sales is now broken so he now manages neither.
I'd consider it preferable to add a simple hardware error amplifier so Vout = k x Vset and THEN measure Vout and Iout with ADCs (as he does). Vout is then essentially "set and forget" with the added ability to check that Vout is what it should be (which allows eg heavy overload to be detected.
Constant current mode operation is still "nudge and see" but 'not too bad'.
Also, Vout includes the Vdrop across the current sense resistors - about 0.5V/A. Measuring with 2 x AD C channels as he does allows this to be compensated for. If the Isense resistors were in the "high side" feed before the regulator this would remove this variation but make current sensing somewhat harder.

What makes you think that this solution: http://tuxgraphics.org/electronics/201005/bench-power-supply-v3.shtml is "open loop control"?

@NilsB Please see my updated answer. I've assumed that the actual circuit is the one shown on the page. If there is a complete circuit diagram anywhere and/or if this is not the actual circuit used I'd be pleased to know. (Both those comments are genuine - I feel I MAY have overlooked some final diagram somewhere but if so I cannot find it.) As it stands I assume that what is shown is what is used and my comments apply.
The developer seems to have attempted to minimise use of ICs use of a comparator in the output stage would improve the result and make the design task easier.

I guess this  http://tuxgraphics.org/common/images2/article379/powersupply.gif is the whole circuit. And as the feedback loop is done in software IMHO it's not "open loop". What do you think?

@NilsB If your guess is correct then it appears not to be open loop in the broad sense. The Vout is still decoupled from Vset, with the software feedback allowing him to adjust the Vset to make Vout what he wants on a "nudge ity an see" basis. ie Vset is not a fixed ratio wrt Vout so he can never set it and have it "just track". ie it does not automatically stabilise for load or temperature changes and there is a variable drp between k x Vset and Vout. ...

...  Software is fastish but not as fast as a closed loop in hardware which allows Vout to track Vset within  mV in a time delay as short as you provide an error amp loop for. || That's a 2005 cct diagram so an earlier version than the originally cited V3 - one assumes he has not 'gone backwards' in design concept. It's strange that he does not include the whole circuit diagram or a good discussion of the provided current and voltage feedback. He may have wanted to sell kitsets rather than give away his final design. The link to the kitset sales is now broken so he now manages neither.

authors: Степан Спирин


text:
Problems with compiling more then one sketch in the Arduino IDE
I found this ESP8266-MQTT program on Github.
How can I compile this thing with the Arduino IDE?
I only can open one sketch at a time. If I try to compile this then parts of the program are missing for AVRDUDE - but they are in the same folder.
Please can you help me?

Looks like it is all one sketch, though there are multiple .ino files... but the project folder name has to be exactly "ESP8266-MQTT-to-Serial-Bridge", that tells the Arduino IDE that the main project file is named "ESP8266-MQTT-to-Serial-Bridge.ino". The other files contain additional supporting code and must be in the same folder.

thanks but it did not work :(      I have tried both ways.

I can open it in Arduino IDE 1.8.13, but can't build on my system due to missing library (ESP8266WiFi.h: No such file or directory). Not really a avrdude issue. Can you update your question to show exactly what error messages you get (Sketch | Verify/Compile, then "Copy error messages")

Thanks for your answers. I get messages that parts are missing. You must make from ESP8266WiFi.h to WiFI.h I have a ESP32 and i am using Ubuntu.

Related: https://arduino.stackexchange.com/questions/35117/fatal-error-esp8266wifi-h-no-such-file-or-directory

Related: https://arduino.stackexchange.com/questions/48669/includeesp8266wifi-h-showing-error-message

Related: https://arduino.stackexchange.com/a/58751/7174

thanks but this are not liberys. This are parts of the sketch.

Related: https://arduino.stackexchange.com/questions/71405/whats-the-relation-between-arduino-standard-library-and-esp8266-library

thanks but i have no libery proplem!!!

"I have a ESP32" and... "ESP8266-MQTT-to-Serial-Bridge" ... see the problem?

ok thanks  But normaly i can use a sketch for both.

I could compile the program fine, when I removed all lines with #include <String.h> (I don't know, why this is included, since the String class in Arduino is available without including something). Just open the ESP8266-MQTT-to-Serial-Bridge, then the Arduino IDE will open with that sketch and the other files (cpp, h, ino) will be in the same window in different tabs.

Though I compiled for the ESP8266. You cannot compile that for the ESP32

That sketch is written for the ESP8266, not the ESP32. The two are very different chips, and the libraries used are very different.
You will have to learn how the sketch works, and how the ESP32 libraries work, and port the sketch to the ESP32 once you have learned how.

thanks Is there some sketch for the ESP32 ?

There are plenty of sketches for the ESP32. One that does that exact same thing? Dunno. Ask Google.


text:
Sending large structs via nrf24l01 leads to cliping of some structs members
I started with building of the wireless temp/hygro/other values probes. I use 2 arduinos, both with nf24l01+ wireless transceivers, library used is rf24.h (https://github.com/maniacbug/RF24). Basically ping/pong test works for me - so each arduino communicates properly via nrf24l01+.
I added dht22 temperature sensor and just for testing I started with sending structure:
typedef struct{
  int A; // just counter to see if receiving new data
  float B; // temperature
} data;

data payload;

I send it from Arduino1 like this:
radio.write( &payload, sizeof(payload) );

Other Arduino2 receives the payload:
radio.read( &payload, sizeof(payload) );

This works perfectly and I am able to print the counter value as well as the temperature value on the oled display o Arduino2. The problem is when I add float C to the struct for sending/receiving hygrometer values. Then Arduino2 does not receive/display any valid hygro value, but there is just value of 0.00.
I think I know where my problem is - nrf24.h has possibility to set payload size for nrf24l01+ - both Arduinos have to use the same payload size (default is 16, min is 8, max is 32). I use 8 - as this looks to be the most reliable value when using larger distances between Arduinos.
When I tried to set payload size to 32 on both Arduinos:
radio.setPayloadSize(32);

Then it works and I can receive and display counter, temp, hygro values.
So it looks the nrf24l01+ sends a payload of either 8 or 32 bytes and when sending struct with INT, FLOAT, FLOAT - 8 bytes is not sufficient and 32 bytes of payload is needed. But when I will use many other values, I can reach also limit of 32 bytes payload.
I do not have much skills in C programming and also I do not fully understand how data packets are being transferred between nrf24l01+ modules- maybe I just need to adapt my send/receive code to handle sending of the larger structures. Maybe somebody could give me a hint.

It seems you have answered your own question: payload size is the key; you cannot transmit packets larger than the payload size. If your packets exceed the max 32 bytes size, then you will have to split them in smaller apckets and transmit them one by one.

I thought the nrf24 will take care and if I am sending more than payload size, it will send it piece by piece until all data is sent. And then the receiving side will receive it piece by piece until complete. So no way? I have to split the data manually into several "pieces" and then send more times?

Ok, clear. Found it explained here as well -http://arduino.stackexchange.com/questions/8185/increasing-payload-size-above-32-bytes-using-nrf24l01

correct, you must split it

Your payload is too big. You will have to split it to smaller pieces.
NOTE: If you'd use a library like RF24Mesh then you'd not have to worry about it.

as stated above, it all has to do with the size of your payload. To clarify things, you need to keep in mind how many bytes a certain data type uses/needs:
char: 1 byte
int: 2 bytes
float 4 bytes
(above is based on the Arduino reference, see https://www.arduino.cc/en/Reference/Float )
Thus, if you set payload size to 8 bytes in the NRF24L01 and then try to send a struct with int, float, float you will have 2 + 4 + 4 = 10 bytes, which does not fit in the payload size.


text:
Arduino and ESP8266 Web server
First things first, if there was an ESP8266 StackExchange, I would post this there.
I am setting up a web server that will programmaticly be controlled from an external Python script, and I am currently able to send this server data using this script, but I don't receive an HTTP response back when I do, so the external script crashes.
I have googled around and not found much on this, so the question is How do I, From the Arduino, using an ESP8266 send an HTML response code?

After countless Trial/error attempts, I was able to put together the proper sequence.
AT+CIPSEND=0,40  \\Set this for your current connection ID and payload length.
HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n
AT+CIPCLOSE=0  \\Set this for your current connection ID

Send these commands with the arduino, and it should exit successfully.  You can also flush out the HTTP line with any other information you would like to include, as defined in the rfc2616 (HTTP/1.1) standard

Altough this works fine, I recommend you to take a look at ditching your arduino and just using your esp8266. The ESP8266 is much more powerfull then the Arduino. Take a look at the Sming Framework for example. It gives you so much more to work with the driving it through AT commands

@larzz11 While, yes the ESP is easier to work with natively, I only had access to the 8 pin version (Then REV number escapes me at the moment) and that didn't give me enough GPIO pins for the project at hand, and it didn't have enough processing time or memory.