text:
Arduino Micro + Max4466 - Noise on A0
I've got an Arduino Micro, and a MAX4466 ECM / AMP breakout board (https://www.adafruit.com/product/1063). I'm powering the Arduino Micro from the USB port.
On the MAX4466 (to the Arduino), I've wired VCC to 3.3v, GND to GND, and OUT to A0. I've also wired 3.3v to AREF.
Using the following code, I'm noticing significant noise spikes on the output, as shown in the graph below.
I'm not entirely sure what I've done wrong here, and would appreciate any input / criticism that could lead to getting a clean signal.

void setup()
{
   Serial.begin(9600);
   analogReference(EXTERNAL);
}

void loop()
{
   Serial.println(analogRead(0));
}

And if you sample at exactly 50Hz or a multiple thereof?

@IgnacioVazquez-Abrams I've just taken another sample, both with the above code, and with the above code, with addition of a call to delay by 20ms per sample. This screenshot shows the result: http://s21.postimg.org/4fplz8g8n/Screenshot_from_2015_06_27_06_00_54.png. As you can see, the noise is much lower now, and I'm not seeing such massive peaks any more..although there are still some peaks, at a much lower amplitude.

You could average the samples to get a lower noise. But it kind of depends on what you are trying to achieve. As you notice the noise only produces values lower than expected, not higher. So if you want to e.g. detect a clap, this kind of noise doesn't really affect your program, as you'd measure peaks. (PS try increasing the baudrate of the serial connection and see what that does.)

You could try adding a resistor between 3.3v and AREF or even better an inductor.

@Gerben thanks for the comments. I've actually got a sketch with 4 frame averaging ready, just haven't had a minute to test it yet :) RE the resistor, I've read the same about between A0 and GND. I'll see if I can pick up a few different resistors later and give them a try :) Will report back

Try this: Aim is to isolate mic module from any Arduino or supply noise. | Measure module current with a milliammeter. Data sheet here for 4466 - likey current uncertain but seems likely to be < 1 mA. Maybe not. Add a series R that drops about 0.3V (Vcc min = 2.4V) R max = 0.3V/mA_drawn. eg if I = 1 mA the Rn=max = 0.3/.001 = 300 Ohms - > use 270 Ohms or less. Add a largish capacitor at module from Vcc to ground and feed Vcc via Ras above. C = 100 uF probably OK. Higher does not hurt.

Thanks @RussellMcMahon for your input. I wasn't able to get anything from my local Maplins as they were closed, but I'll drop in either tomorrow or Monday. I'll also update this question with a photo of my (surely dreadful) layout. I don't have a millammeter available to me, but I'll see if I can acquire one. This was meant to be a simple little audio recorder experiment, so if the cost of the equipment is going to be relatively high, I'm not sure I can warrant it right now..we'll see. I'll be back!

@Seidr   "milliammeter" can be almost any modern DMM (digital multi-meter) -  essentially any of these can measure up to 200 mA and cost can be modest and they are utterly invaluable when doing anything with electronics. | Aim overall is to feed clean power to module and to get clean signal back. Ground paths should be direct and if a number of things are powered use "star" grounds - all grounds radiate from a single point - no loops formed.

Pulled out my ollllld multi meter, and it's reading a current of 2mA. I'll try going shopping for parts again tomorrow. Thanks :)

My thanks for all your input. I believe I've discovered the cause of the noise - the serial port. The higher the baud rate goes, the higher the frequency of the noise. I've also tried the same setup on a friends Arduino Uno, and could not detect any noise. I'm going to try this with a stand alone power supply tomorrow, and see if that resolves the noise issues or not. Using a small capacitor to ground did help slightly also :)

Ok - so I suspected that it was the Arduino at fault.. Turns out it's a cheap Chinese clone. After purchasing an official Micro, and wiring up the same component, I'm getting a nice clean signal (bar a small amount of acceptable noise), which is reflecting input tones accurately. Thanks again for all the input!

Interesting plot. Gives me the impression that your reference is sagging, consider adding some local storage (tant/ceramic capacitors) across the cpu's power in pins and across the cpu's Reference pin. Would also be interesting to know if adding more delay between measurements would improve performance. Thanks for sharing you issue.


text:
avrdude flash issues
I want to burn a hex file to a custom ATmega2560 board. I use this USBasp programmer for flashing (firmware version 1.01) on my Mac OS X 10.12.6 system. All hex files are compiled with avr-gcc (GCC) 4.9.2.
I use this command to burn fuses (without bootloader):
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega2560 -cusbasp -Pusb -U lfuse:w:0xff:m -U hfuse:w:0xd9:m -U efuse:w:0xfd:m -s -F

What is working fine: I can flash smaller (43,266 bytes) programs and they work straight away without bootloader. If I flash bigger programs (99,986 bytes) they do not run. I can verify if the program runs because they spit out data via TTL. The smaller program does work but the bigger one does not produce anything.
I turned on "Code verify" and I can see for smaller programs:
avrdude: 43264 bytes of flash verified

big programs:
avrdude: verification error, first mismatch at byte 0x0001
         0x90 != 0x94
avrdude: verification error; content mismatch

Any hints on this side?
Secondly: after deleting the whole flash, when I flash a custom bootloader (from Atmel Studio - fuses are Ext. 0xFD, High: 0xD2, Low: 0xFF), command:
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega2560 -cusbasp -Pusb -U flash:w:ATmega_Example.hex:i

and afterwards read the flash, the bootloader ended up in several blocks within the flash.
From the readout hexfile (data blocks):
Line 1
>:20000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00

All the flash is 0xFF until Line 1921

:20F0000077C000009BC0000099C0000097C0000095C0000093C0000091C000008FC0000066

Some more data until Line 1995.

:20F940000895F894FFCF65300000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF31

All the flash is 0xFF until Line 3970.

:20F0000077C000009BC0000099C0000097C0000095C0000093C0000091C000008FC0000066

Some more data until Line 4044.

:20F940000895F894FFCF65300000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF31

And so on... I can find similar data 4 times in the file.
Is this a problem with the flashing or with reading the data from the chip?
Let me know if you need more information to help me here.

any change if using -D flag?

no change when I flash with the "-D" option

Define "smaller" and "bigger" wrt the code size.

small: 43.266 bytes
big: 99.986 bytes

I added verification information. On bigger problems it fails:
avrdude: verification error, first mismatch at byte 0x0001
0x90 != 0x94
avrdude: verification error; content mismatch

Could the size limit be 65,536 bytes? IIRC, there was an issue with addresses longer that 16 bits requiring a special extension of the normal upload protocol. But I don't remember whether the size limit was 2^16 bytes or 2^16 16-bit words.

I'm not certain that it's going to fix your problem, but few years ago I had similar issue. I was trying to upload program to ATTiny13A using cheap e-bay USPasp and got verification errors. One step of my solution was changing programmer id from "-c usbasp" to "-c usbasp-clone"
More here: https://www.nongnu.org/avrdude/user-manual/avrdude_4.html

Personally I use AVRDUDESS for uploading sketch on atmega328p and attiny85. Try to use it and run detect.
I answer this because AVRDUDESS is very easy to use and it can help you to show more info of your error.
I think you maybe have a bad wiring or a defect cable.

I am familiar with that issue. I don't have an USBasp but an USBtinyISP but I think the problem is the same.
The USBtinyISP cannot read or write past 64kiB. Since AVR are 8-bit machines with 16-bit addressing they cannot address past 64kiB on their own. A special addressing schema is used on runtime and also during flash. (I think it was larger page sizes during flash.)
I could manage to get around the issue by using an original Atmel AVRISP mkII.

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:
Communicating with Arduino Mega 2560 Serial ports through x2 RS232
I am trying to drive a stepper motor using an Arduino Mega 2560. There will ideally be two RS232 signals being read into / written from the Arduino, each using male USB 3.0 connectors; one of these is for configuring and controlling the driver of the motor and the other is simply getting an output torque measurement from a torque meter connected to the motor's shaft.
I am simply wondering if Arduino would be able to handle these two functions, and how I might go about connecting each of the two streams of data. I have looked into this question through Arduino documentation, tutorials, and forums for hours, and finally figured I would contribute to the posts on my own.
Thank you!

a confused college student

You have 4 serial ports. The obvious option would be to use Serial1 and Serial2, while keeping Serial for debugging output. I can't quite see where you see a problem.

More information please!  The part you have chosen should be more then fast enough to do what you want. A big portion of the interface will be the sensors and their capabilities as you have indicated. The serial channels on the Mega are buffered so you have some time. The driver, are you controlling each phase or just command a module on what to do? Where does the serial channels come into play, there are a lot of sensors that do not need them. Posting links to "technical" information on each of the hardware items will help a lot as would a simple annotated schematic or block diagram.

Your main problem seems to be confused by all the information. I will give you some more.
The Arduino speaks UART (Universal Asynchronous Receiver Transmitter) with it's Serial interfaces (there are 4 of these on the Mega). This is partly the same protocol as RS232, but it uses TTL logic levels (in this case the levels 5V and 0V), while RS232 has different voltage levels and more lines (like control lines). When you connect your Arduino to a PC, the PC is not directly talking to the Arduinos chip (here the Atmega2560). Instead every Arduino with a USB port has an extra chip. It will handle the (very complex) USB communication, so that you can see an emulated COM port on your PC. The data, that the PC sends to that COM port, get's transmitted over USB to that extra chip, which in turn will convert it to UART signals and send them to the Atmega2560.
All Arduinos, that I know of, have only 1 USB-to-UART chip. But you can add your own USB-to-UART chip to one of the other Serial interfaces. You can use a FTDI chip, an Atmega16U2 or (if you don't want to program an extra chip) simply an USB-to-UART converter cable/module, which you can buy and use directly by just connecting their pins to the Arduinos Serial pins.

By the way, it doesn't really matter here, if you use USB3.0 ports, since chips this small cannot work with speeds that high. All these chips use USB2, more is not necessary, they aren't fast enough.

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


text:
How to fill a triangle using the LCD5110 Graph library?
Good day! I'm currently trying to create a small 3D engine using C++, an Arduino UNO as well as a Nokia 5110 display with a library. Now I have successfully drawn a cube using triangles, but I want to fill the triangles to add proper lighting. My method for drawing triangles is the following:
LCD5110 lcd(8,9,10,12,11);

void DrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
 lcd.drawLine(x1, y1, x2, y2);
 lcd.drawLine(x2, y2, x3, y3);
 lcd.drawLine(x3, y3, x1, y1);
}

My library hasn't got a triangle draw or fill method unfortunately. I have no idea how I could fill a triangle so I hope for help.
Thanks in advance...
NOTE:
Please keep it simple.
NOTE NR.2: I have already asked this question at StackOverflow but I haven't got a good answer so I will try it again.

It looks like nobody is answering...

That is most likely because there is no good answer. If your library doesn't provide a draw filled polygon method you have to draw it yourself. Ok, this is a standard algorithm in computer graphics but it's not easy to explain. E.g. have not enough time to think about how to explain it in a few words. But I can point you to an easy to understand algorithm that is called the "flood fill" algorithm. If I recall correctly there is a C++ implementation called FloodSpill.

I will take a look at FloodSpill.

As I said in the comments of you answer: If the given solution works for you and performance doesn't matter, your solution is much better than my proposal. But don't forget to add the } to the code below. As it might confuse other that want to use your solution.

After tinkering around for hours I have finally found a great way to fill triangles! Here we go:
for(int x = x1; x<=x2; x++) {
    for(int y = y1; y<=y2; y++) {
     lcd.drawLine(x3, y3, x, y);
    }
}

Great!

If you add the missing } it will work. But it's not very efficient. If performance doesn't matter, you are right: It's simple and it works.


text:
How to make VOLTE/LTE or LTE calls using Arduino?
I want to make VOLTE/LTE calls using Arduino. I searched everywhere in Google. At last I found a website LTE Cellular Shield for Arduino with Voice!.
But I cannot find SIM7500 Shield in online shops. So U want to use SIM7000. But I can't find code for it. Can you share any?

have you seen this? ... https://github.com/botletics/SIM7500-LTE-Shield?files=1

See but I can't understand anything

I want the code what I give

I connect SIM7500 to Arduino Uno. and connect speaker mic etc.Okk. Then I have to give a code to Arduino by arduino ide, right. I want this code which I give

now i understand ... you want the code that you load into the Arduino ... the link in my comment above has example code ... you can find it in the README.md

Code is not available on README.md

yes it is ...click on step-by-step wiki ... your internet search skills need some sharpening ... lol


text:
Arduino MKR 10100 control DC Motor
Thank you for reading my post. I have been stuck on this for several weeks now! I am trying to turn ON/OFF a DC motor from Arduino IOT Cloud. I have set up the cloud and added the switch. Everything works well with an LED: it lights on and off as needed, but the motor does not turn on or off. Below is the circuit I have set up.

My circuit specs are as follows:

I'm not using a UNO as the image illustrates, rather I'm using an Arduino MKR WiFi 1010, but the connections of the pins are exactly the same: LED at PIN 3 and Motor at 7.
The diode I am using is 1N4001.
The transistor I'm using is TIP120.
The motor I'm using is 5V DC Motor.
270 Ohm resistor on the transistor circuit and 220 Ohm on the LED circuit.

The Arduino code I made is as follows:
#include "thingProperties.h"

#define LED_PIN 3
#define MOTOR_PIN 7

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(MOTOR_PIN, OUTPUT);

  setDebugMessageLevel(2); // For debugging of cloud integration
  Serial.begin(9600);
  delay(1500);

  initProperties(); // initialize cloud properties
  ArduinoCloud.begin(ArduinoIoTPreferredConnection); // Connect to cloud
}

void loop() {
  ArduinoCloud.update(); // Update cloud background services
}

void onMotorChange() {
  if (motor) {
    // Motor & LED ON
    digitalWrite(LED_PIN, HIGH);
    digitalWrite(MOTOR_PIN, HIGH);
  } else {
    // Motor & LED OFF
    digitalWrite(LED_PIN, LOW);
    digitalWrite(MOTOR_PIN, LOW);
  }
}

All my setup seems to be be correct, but it just is not working. I have researched a lot but to no avail. I have tested with a different motor just to be sure, but it also does not work. I'm not sure where I have made a mistake.
Please help me. Thank you very much.

never use an arduino as a power supply ... there is a good chance that the arduino will become an expensive fuse

Thank you for the tip, i do not have an external power supply that's why i resorted to the 5V pin. in regards to my question do you see why am facing this issue?

Okay i managed to solve it, the issue was actually my circuit wiring. Below is an image with the correct setup for the transistor or MOSFET.

I have changed the TIP120 to RFP30N06LE as VE7JRO suggested:

The TIP120 is a poor choice because of the approximate 10% - 14% voltage drop across it. Try the circuit with a logic level, low Rds MOSFET.

but that with the circuit in question does not work. I have not tested the circuit attached with this answer using a TIP120 but i suspect it would work as well.
Finally i added a 9V battery as jsotola suggested:

never use an arduino as a power supply ... there is a good chance that the arduino will become an expensive fuse

but i have not tested using the 5V Arduino pin again i suspect it would work as well.
Bonus:
If anyone was wondering how i made these images i used TinkerCAD
Thank you all
Hope this Helps!

The TIP120 is a poor choice because of the approximate 10% - 14% voltage drop across it. Try the circuit with a logic level, low Rds MOSFET.
For a more in-depth answer, please see this answer: https://electronics.stackexchange.com/a/388468/165322

Comments are not for extended discussion; this conversation has been moved to chat.

Hello VE7RO, hope you have been great! thank you for your input from before, i got everything working.
Now am working on making a PCB of it but i couldnt been to find an SMT version/replacement for the RFP30N06LE, i was wondering if this would work https://assets.nexperia.com/documents/data-sheet/PMV15UNEA.pdf since my aplication does not really reach the limit of 60 V or 30 A, while this provides good Rds, Thanks!


text:
LED blinking count with LDR sensor
How to count +1 all the time if LED blinks with LDR sensor
Image:

If i turn on led it must count into serial monitor 1 and if i turn off led and turn on again then it counts 2.
To turn on led I must put my hand into LDR sensor.
It also looping text in serial monitor "First LDR sensor is Dark".
int ledPin1 = 7;
int ledPin2 = 8;
int ledPin3 = 9;
int ldrPin1 = A0;
int ldrPin2 = A1;
int ledTest = 200;
int ldrStatus1 = 0;
int ldrStatus2 = 0;
int ledCheck1 = 0;
int ledCheck2 = 0;
int Count = 0;

void setup() {

  Serial.begin(9600);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);

  pinMode(ldrPin1, INPUT);
  pinMode(ldrPin2, INPUT);
}

void loop() {

  ldrStatus1 = analogRead(ldrPin1);
  ldrStatus2 = analogRead(ldrPin2);

   if (ldrStatus1 <= ledTest) {
    digitalWrite(ledPin1, HIGH);
    Serial.println("First LDR is Dark");
    ledCheck1 = 1;
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin1, LOW);
    ledCheck1 = 0;
   }

   if (ldrStatus2 <= ledTest) {
    digitalWrite(ledPin3, HIGH);
    Serial.println("Second LDR is Dark");
    ledCheck2 = 1;
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin3, LOW);
    ledCheck2 = 0;
   }

   if ((ledCheck1 == 1) && (ledCheck2 == 1)) {
    digitalWrite(ledPin2, HIGH);
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin2, LOW);
   }

}

At the moment it counts when it is turned on, like seconds..
How to fix or make it work correctly?

I really don't know what you want to ask... what means +1 all the time? Should it count the number of transitions (of one or both leds?), maybe you have short values which are incorrect (cheap LDRs) and you have to remove short 'spikes' / false postives.

@MichelKeijzers When I put my hand on LDR sensor it must turn light on and tell in serial monitor 1 time turned on and then if i take my hand off led is turned off. and if I repeat it count to 2 and again then 3...

Did you check what values you get when you put your hand over it? And analyzed them? Print out every number (can be many) and check if your program behaves the way you expect when using the values you received. You might have to filter some, or use an average or other way to remove some values that you didn't expect (but the sensor still sends).

@MichelKeijzers Sensor printing "First LDR is Dark" and looping it. How I can make it no loop and counts +1 ?

That means that  if (ldrStatus1 <= ledTest) is always true ... check the value to see if it is what you expect.

Please edit your question to make it clear what you're asking.

@per1234 edited my question.

Use state change detection and hysteresis for counting pulses in an analog signal.
const int lowerThreshold = 150;
const int upperThreshold = 200;

const uint8_t analogPin = A0;
const uint8_t ledPin = LED_BUILTIN;

void setup() {
  Serial.begin(115200);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  static bool state = LOW;
  static unsigned int counter = 0;

  int analogValue = analogRead(analogPin);
  if (state == HIGH) {
    if (analogValue < lowerThreshold) {
      state = LOW;
      counter++;
      Serial.println(counter);
      digitalWrite(ledPin, LOW);
    }
  } else { // state == LOW
    if (analogValue > upperThreshold) {
      state = HIGH;
      digitalWrite(ledPin, HIGH);
    }
  }
}

This sketch basically applies a software Schmitt trigger to the analog input signal, and increments the counter on each falling edge. (Rising edge of light intensity, because your LDR configuration inverts the signal.)

The red waveform is the analog input from the LDR. The gray rectangular wave is the state (and the state of the LED). The counter is incremented at each black, vertical dashed line.

LED is always ON..

Then change the thresholds. Do you understand how it works? That's the first step.

I changed low treshold to 0 and led still turned ON. Changed ledPin to 7 where is my led and still led turned on.

That's to be expected, if you set the low threshold to 0, it is impossible to turn off the LED. Go through the sketch, try to understand the logic. Try it with a potentiometer first (left terminal to ground, center terminal to A0, right terminal to 5V) and set the low threshold to 256, and the high threshold to 767. Turn the potentiometer and see what happens to the LED. Then use the analogReadSerial example to see what values you get from the LDR. Adjust the thresholds accordingly.

Edited my question.

@JoeDavid: Have you tried the suggestions in my previous comment?

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


text:
Why the serial connection only work when Tx and Rx are shorted?
I have a Arduino Pro Mini 3.3V connected to a sim800l chip using a serial connection of 9600bps. When I connect the Arduino to the device, it seems I don't receive anything on the Arduino Rx pin.
I then connected a FTDI that listen the sim800l Tx pin:

The FTDI is able to receive data so this means the sim800l is working well by receiving data from the Arduino and responding accordingly.
So normal logic would say that the Arduino Rx pin is not working but when I connect the Arduino Rx and Tx pin together:

I'm able to receive what I send on Tx on the Rx pin.
Why would that be?
I tried with AltSoftSerial and SoftwareSerial. The Arduino is powered by a FTDI connected to my computer via USB. The sim800l is powered by a second FTDI that is also powered by my computer USB. So all component uses the same ground and I verified that with my multi-meter.
Here is the code I use:

AltSoftSerial sim800Serial(8,9); // RX, TX

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

while(1)
{
  if(sim800Serial.available())
  {
    Serial.write(sim800Serial.read());
  }

  if(Serial.available())
  {
    sim800Serial.write(Serial.read());
  }
}

Please complete the circuit with VCC and GND so we understand the complete connection.

As well as the code you wrote to receive data from the device

connected to some device Y  - what device? Part number? Datasheet?

Mikael Patel is right - if you didn't connect the grounds the device may well not work. However the Pro Mini can talk to itself because the grounds are connected internally.

I added more details to my question that answer yours. Let me know if I need more clarifications.

Are those grounds all physically connected in your circuit or are you relying on the grounds provided by the various USB modules being linked via your computer's ground?

with power off, I measured all ground and they are shorted and have a very little resistance

I also tried putting all devices on the exact same ground without success.


text:
avrdude/stk500 protocol error
I'm running into a bizarre problem. I've got a custom board using an Atmega328P, running off the internal oscillator. From Atmel studio, I've successfully uploaded the standard optiboot bootloader (optiboot_atmega328.hex) and burned the appropriate fuses (hfuse = 0xDE, lfuse = 0xE2, extended_fuse = 0x05). As per an arduino forum post, I added the following entry to boards.txt:

    atmega328_384_8.name=ATmega328 Optiboot @ 38,400baud w/ 8MHz Int. RC Osc.
atmega328_384_8.upload.protocol=arduino
atmega328_384_8.upload.maximum_size=30720
atmega328_384_8.upload.speed=57600
atmega328_384_8.upload.tool=avrdude

atmega328_384_8.bootloader.low_fuses=0xE2
atmega328_384_8.bootloader.high_fuses=0xDE
atmega328_384_8.bootloader.extended_fuses=0x05
atmega328_384_8.bootloader.path=optiboot
atmega328_384_8.bootloader.file=optiboot_atmega328.hex
atmega328_384_8.bootloader.unlock_bits=0x3F
atmega328_384_8.bootloader.lock_bits=0x0F

atmega328_384_8.build.mcu=atmega328p
atmega328_384_8.build.f_cpu=8000000L
atmega328_384_8.build.core=arduino
atmega328_384_8.build.variant=standard

Note here, I've modified the upload speed to 57600 baud to "fool" it into the right upload speed given an 8MHz oscillator.
I can now successfully upload sketches from the Arduino IDE (1.6.3) on the lab windows machine, but when I try from my Mac (various IDE versions have been tried), I get the following protocol error:
avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0
Here's the full trace:
/Applications/Arduino-1.6.8.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino-1.6.8.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbserial-AH02F0KI -b57600 -D -Uflash:w:/var/folders/db/hw2v9r6j7qj_w9gh3qkhh_580000gr/T/build53eb1895270295360d41549eaf6e0624.tmp/sketch_apr19a.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Applications/Arduino-1.6.8.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/npisenti/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.usbserial-AH02F0KI
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00
         Hardware Version: -1538883332
         Firmware Version: 6291456.-1538883332

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0
         Vtarget         : 322122165.6 V
         Varef           : 275608114.4 V
         Oscillator      : 0.001 Hz
         SCK period      : 368336.6 us

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00
avrdude: stk500_initialize(): (a) protocol error, expect=0x14, resp=0xe0
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0xe0

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

On Windows, the "successful" full trace from avrdude is:
Sketch uses 1,974 bytes (6%) of program storage space. Maximum is 30,720 bytes.
Global variables use 192 bytes of dynamic memory.
C:\arduino-1.6.3\hardware\tools\avr/bin/avrdude -CC:\arduino-1.6.3\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM10 -b57600 -D -Uflash:w:C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex:i

avrdude: Version 6.0.1, compiled on Mar 30 2015 at 14:56:06
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\arduino-1.6.3\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM10
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex"
avrdude: writing flash (1974 bytes):

Writing | ################################################## | 100% 0.77s

avrdude: 1974 bytes of flash written
avrdude: verifying flash memory against C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex:
avrdude: load data flash data from input file C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex:
avrdude: input file C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex contains 1974 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.86s

avrdude: verifying ...
avrdude: 1974 bytes of flash verified

avrdude done.  Thank you.

In both cases, I'm using the FTDI friend from Adafruit; at first I figured it must be a driver issue, but I've installed the latest FTDI drivers and doesn't seem to help. Besides, I can successfully get text dumped from the ucontroller onto the serial port from a sketch previously uploaded on the windows machine.
Any help would be greatly appreciated!

I managed to figure this out after hours of searching. I wanted to flash the new Nano bootloader to my Nano, but it would fail with the same error as you.
For some reason, after Arduino 1.8.5, AVR boards with "Arduino as ISP" were changed so that they no longer work for me.
The solution for me was to revert programmers.txt to what it was on 1.8.5, i.e. change the arduinoasisp lines to:
arduinoasisp.protocol=stk500v1
arduinoasisp.speed=19200
arduinoasisp.program.protocol=stk500v1

This uses the stk500v1 protocol instead of the arduino protocol (you can see the -carduino option in your command line) and makes everything work for me.


text:
Web Page doesn't load when data is being received from Xbee
I have an Arduino Mega I am using as a simple web server. Right now the web page is two simple lines of text. There is an XBee radio attached to the unit to receive data from another unit. However, when the server unit is receiving data the web page will not start up. There's a switch on the shield to switch it into Micro for the radio, or USB. If I reset, or power on, the server unit with the switch in USB mode it loads fine; then once the web page loads I can flip it on Micro and it will refresh fine even while receiving data. However, if I try to power on the unit, or reset the unit, with the switch on Micro it will not load the web page. Any ideas on why this is happening?
Schematic:
Server Unit: Ethernet shield with HanRun HR911105A 13/15 ethernet jac placed on Mega ADK. There is a Wireless Proto Shield with XBee Pro 538 radio placed on the ethernet shield.
Remote Unit: There is a Wireless Proto Shield with XBee Pro 538 radio placed on the Mega ADK.
setup():

void setup() {
    // Open serial communications and wait for port to open:
    Serial.begin(9600);

    // start the Ethernet connection and the server:
    Ethernet.begin(mac, ip);//, gateway, mask);
    server.begin();
}

loop():
void loop() {
    // Listen for incoming clients
    client = server.available();
    if (client) {
        boolean currentLineIsBlank = true;
        while (client.connected()) {
        if (client.available()) {
            char c = client.read();

            // 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: 5");  // refresh the page automatically every 5 sec
                client.println();
                client.println("<!DOCTYPE HTML>");
                client.println("");

                client.println("
");
                client.println("");
                client.println("");
                client.println("My WebPage");
                client.println("
");
                client.println("Web Server and Radio Receiver ");
                client.println("
");
                client.println("version November 30, 2016");
                client.println("
");
                client.println("");
                client.println("");
                client.println("");

                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();
}

Could you provide the schematic and both setup() and loop() functions that will manage both Micro and 'USB` links ?

@J.Piquard I just posted my Arduino set up, as well as the code.

In your source code, close to the example WebServer.ino, you have assigned in loop() the client = server.available(); with certainly EthernetClient client declared before setup() meaning that another client has been created before. Try to declare EthernetClient client = server.available(); inside the loop().

@J.Piquard I tried your suggestion but it unfortunately didn't solve the problem

@J.Piquard I tried moving Serial.begin(9600) to be the last line of setup() and now the web page loads when reset while receiving data, but it still won't load while receiving data when first powered on


text:
Serial.print / sprintf causes program crash
The following code
  int i;
  char msg[16]; // Serial data.

  Serial.println();
  Serial.println("===============");

  sprintf(msg, "Sequence:  %4d", runNum);
  Serial.println(msg);

  Serial.print("LED colour: ");
  Serial.println(colours[colour]);

  Serial.print("Max mA:      ");
  Serial.println(mAmax);

  Serial.println("  mA    mV");
  for (i = 1; i <= mAmax; i++) {
    sprintf(msg, "%4d", i);          // <--- Line 1.
    Serial.print(msg);               // <--- Line 2.
    sprintf(msg, "%6d", i * 3);
    Serial.println(msg);
    delay(50);
  }

crashes after the first pass as shown below:
===============
Sequence:     1
LED colour: red
Max mA:      30
  mA    mV
   1     3

If I comment out "Line 1" and "Line 2" the loop runs correctly.
I suspect that something odd happens with either the two sprintf calls or the Serial.print / Serial.println calls in quick succession.
Can anyone spot an error or know of an issue that I've missed?
Development environment: create.arduino.cc

Not from that snippet, no. You need to show your full code, or a version of the code that at least compiles and demonstrates the problem. As it stands we cannot know what is happening because we don't know what your code is doing. What are your variable types? What values do they contain? What else is going on with your code that could have a bearing on it?

Please add the declaration of msg. The string buffer might be too small.

I forgot about the declaration. I've added that. I've also stripped down my code to the snippet above plus the setup, etc., and it works. Darn! More digging. I'll update later when I have more info.

%4d does not limit the maximum size. When the number is 20000 the whole 20000 is printed and your buffer will overflow. You assume that the loop runs correctly when those two lines are commented out. I doubt that. Data on stack that is overwritten or ram problems or heap overflow is not always detected. We still need a full working sketch that shows the problem.

avr-libc does have snprintf(), or you could check the value for limits before sprintfing it.

Where does runNum come from?

Please show your full code. See How to create a Minimal, Complete, and Verifiable example

Hold off for a bit, thanks, guys. I've got the code working now but I'm struggling to find what the original problem was. The stripped down version ran fine. More later and I'll post my findings.


text:
ATtiny85 giving multiple wake from IDLE if INT0 held low
Desired behaviour:

Go to IDLE sleep mode.
When PB2 (blue trace) goes low wake up and give a 10 ms HIGH on PB1 pulling a pull-up low (yellow trace on Figure 1).
Go to 1.

What I get:

Figure 1. (1) The input triggers, (2) the CPU wakes from sleep, (3) the CPU goes back to sleep and wakes up repeatedly until (9) the input goes high again.
I want one 10 ms low pulse and then go back to sleep until the next negative going edge on PB2 regardless of how long PB2 is held low.
Even though I set MCUCR to falling edge of INT0 the device seems to wake repeatedly when PB2 is held low. My code below attempts to solve this by switching to rising edge interrupt if the input is low and falling edge interrupt if the input is high. The result is shown in Figure 1.
void setup(){
  ADCSRA &= ~_BV(ADEN);               // ADC off. ADC not used.
  pinMode(reedPin, INPUT);
}

void loop(){
  system_sleep();                     // Go straigth to sleep.
  // ---- System woken up by interrupt. ---------
  if (!digitalRead(reedPin)) {        // Check that input is low.
    pinMode(outPin, OUTPUT);          // Enable output.
    digitalWrite(outPin, HIGH);       // Pull motor sensor input low by MOSFET.
    delay(pulseTime);                 // Pulse time.
    digitalWrite(outPin, LOW);        // Pulse off.
  }
}

// From http://interface.khm.de/index.php/lab/experiments/sleep_watchdog_battery/
void system_sleep() {
  MCUCR |= _BV(ISC01);                    // Required for both rising and falling edge interrupt.
  if(digitalRead(reedPin)) {              // Input is high so set interrupt for detecting low.
    MCUCR &= ~_BV(ISC00);                 // Clear MCUCR bit 0 for falling edge interrupt.
  } else {                                // Input is low so set interrupt for detecting high.
    MCUCR |= _BV(ISC00);                  // Set MCUCR bit 0 for rising edge interrupt.
  }
  GIMSK |= _BV(INT0);                     // Enable Pin Change Interrupts
  set_sleep_mode(SLEEP_MODE_IDLE);        // Leaves the clock running for elapsedMillis.
  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep
  // ZZZZZZZZZZZzzzzzzzzzzz .......
  // ------- CPU is now asleep and awaiting interrupt. ----------------------
  cli();                                  // Disable interrupts on wake up.
  sleep_disable();                        // Clear SE bit.
}

ISR(INT0_vect){                           // Wake up.
  GIMSK = 0;                              // Disable external interrupts. (Only need one to wake up.)
}

Can anyone guide me through this?
Many thanks.

@jsotola, no joy. Still the same.

here is some sleep code you could try ... no idea if it actually works (i have no way to test) ... https://github.com/DaveCalaway/ATtiny/blob/master/Examples/AT85_sleep_interrupt/AT85_sleep_interrupt.ino

The library in that code simplifies things a lot. I've got it now triggering on falling edge and again on rising. I'll keep digging. Thanks.

section 9.2 may help (page 49) ... https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf

The Arduino core configures a timer to deliver a periodic interrupt.
This interrupt is used to implement millis(), delay(), etc. Your
code assumes the external interrupt is the only one the microcontroller
can receive. I guess the timer interrupts may be the cause of the
observed behavior.
I suggest configuring the interrupt for falling edges and leaving it
always on. The ISR can take care of starting the pulse, and setting a
flag to let the main loop know the pulse is active. The main loop can
then stop the pulse when it has been on for long enough:
volatile bool pulse_active;     // whether the pulse is on
volatile uint32_t pulse_start;  // time when it started

ISR(INT0_vect) {
    // Start the pulse.
    digitalWrite(outPin, HIGH);
    pulse_active = true;
    pulse_start = millis();
}

void loop() {
    // End the pulse if it's time to do so.
    if (pulse_active && millis() - pulse_start >= pulseTime) {
        digitalWrite(outPin, LOW);
        pulse_active = false;
    }

    // Take a little nap.
    sleep_mode();
}

Note that the little nap in the code above can be interrupted by either
the external interrupt or the timer interrupt.


text:
Negative voltage: How do I scale a 0 to 5 V signal to -10 V to +10 V?
To control my robot, I need to generate negative and positive voltage in a single line, because the motor I try to control is an industrial one.
Do you have any suggestion for it? How can I produce a negative voltage using an Arduino board and simple electrical elements?

wire a positive voltage in reverse?

It would help if you could be specific about the motor that you want to control.

The servo-pack takes the voltage in single line from -10v to +10v. Usually motors have two pins to control the direction and velocity. But, in our servo-pack, one pin is ground and the other one takes a voltage in the interval of [-10,+10].
I want to control this motor using an Arduino Uno.

@BrettAM I need to change the direction of motor with my control circuit and I just have the positive output of Arduino. Where should I put this single output line to inverse the direction?

Can you provide a link to a datasheet for the motor? How does the +/-10V relate to how the motor works?

Can't you use an H-bridge for this?

[link] https://www.yaskawa.com/pycprd/lookup/getdocument/jvgyvE5ZTUY_5CC1znzBoe-iyvC0118s_1GfGe382go7iz9ltcbQkMVMhVN8L5K3hXb6Zpv5R6zVrH-_NQ6U3hPPUoT2-nMfM5mD23cQKH7xVWeJTen95A
this is a link to the catalogue. You can find the information in p160 for torque control for instance.
It's impossible to use H-bridge for this servo-pack. Because one of the pins is ground. In H-bridge, we have access to two pins in motor to control the direction. Here we have just one pin.

@Gerben, no he can't. He's driving a servo amplifier, not a motor. He needs to generate a control voltage ranging from -10 V to +10 V. See my answer.

Your question should read:

How do I scale a 0 to 5 V signal to -10 V to +10 V?

First write the conversion formula:
Vout = 4 * Vin - 10

Testing the formula gives the following:

Vin = 0.0 V ==> Vout = -10 V
Vin = 2.5 V ==> Vout = 0 V
Vin = 5.0 V ==> Vout = +10 V

You will need an op-amp circuit to create this function. In addition you will need a +12 and -12 V supply.

simulate this circuit – Schematic created using CircuitLab
How it works:

OA1 is an op-amp wired in an inverting summing amplifier configuration. We'll address the inversion later but for now all the answers will be "upside-down". The gain is set by -R2/R1 = -40k/10k = -4. If we feed 1 V in from the ADC we will get -4 V out.
R3 provides a negative input. The gain will be set by -R2/R3 = -40k/48k = -5/6. Since it's connected to -12 it will contribute +10 V to the output.
The actual output will be the sum of the two: in our example, +10 - 4 = 6 V.
C1 and C2 provide noise filtering for the op-amp. Place them close to the chip.

Now, what to do about the inversion? We have three choices:

Fix it in the micro controller code. Set +5 V as maximum reverse speed / torque. Set 0 V as maximum forward speed / torque.
Fix it in the servo amplifier and tell it to reverse its command signal.
Fix it in the electronics. By adding another inverting op-amp we can turn the signal the right way up.

The TL082 opamp suggested has two op-amps in the one 8-pin package.
Ref: Inverting Summing Amplifier.

Servo Enable

simulate this circuit
Delay the servo enable until the micro controller has initialised and all other functions are ready. See manual Section 3.2.3, page 73.
Note that this is a simplified relay drive schematic. You need a transistor drive and a snubbing / flyback diode around the relay so one of the small 5V relay boards would be a good solution as they are already built in. An opto-isolator would be simpler.
Ensure that safety circuits (guarding and e-stops) are correctly wired using safety-rated components (and not only, for example, the micro).

Thank you so much for your complete answer. I am going to make the circuit and may ask more questions when I finish making it. One more time, thank you for the detailed answer.

This circuit seems to have an issue. When the Arduino is not fired yet, if the motor is turned on, it will rotate with the maximum torque in negative direction. Which may damage our system.
One solution comes to my mind to solve this. We can use a 74HC4052 to scale the voltage to [-5,+5] and then use an op amp to gain this value. Am I right?

You should already be using Servo Enable to inhibit the drive until the controller is ready. See update.

I'm back after so long :).
Actually the circuit works but not well. There is an offset in output. After lots of searches, I found that there are other solution for this problem. For instance, it is possible to use an IC which is called Digital to Analog converter. Do you know how can I handle the problem using that IC? Because the output of abovementioned circuit is not precise and reliable.

P.S.: my system has high band width and accepts pure analog voltage as input. That's why I came into the idea of using DAC.

The Arduion PWM output is a form a DAC. It is precise and reliable. You need to figure out why it's not working. Post a schematic of your system. There's a schematic button on the editor toolbar.

PWM output of Arduino has the strict frequency of 490 hz while my motor's bandwidth is 1.6 khz. Consequently, when I run the motor using the Arduino PWM it rattles.
My circuit's problem is the voltage offset of the op-amps. Even when I simulate the circuit, it works well, but in practice, there is an offset voltage on the output pin of the op-amp.

(1) What offset voltage do you get? (Measurement, please.) (2) What is the -12 V actual voltage? (3) What are the measured values of R1, R2 and R3?

The PWM signal alternates between +5 V and 0 V. Did you forget that you'd need to low-pass filter it? Start with an RC filter with a cut-off of half the PWM frequency. What is your last comment about? If it's a link it's broken.

Sorry about my late reply. When I wanted to measure the required information, I realized that, mysteriously, my circuit, which had .3v offset, now works fine (with .03v offset). Actually the circuit I have implemented is different than yours. I used a 74HC4052 to make a bipolar differential line (similar to controlling a dc motor with an H-bridge). Then I used differential amplifier configuration for my op-amp. The output of the IC is two line and using differential amplifier, I combined them together. But, even if this problem has been solved, the frequency problem is still remained unsolved.

The current frequency of PWM (490hz) is unacceptable for my system. If I add a low pass filter to it, it will add a delay to it too. I should find a way to increase the frequency of PWMs.

What kind of motor and load are you actually driving that needs a 250 Hz response?

I want to control the tension in a cable (actually in a cable-driven robot) and the band-width of the motor is more than 1Khz. But, at least I must reach to 1Khz.

"transistor" has walked you through what is necessary. Just an additional point of note: if you don't have a +/- power supply, you can easily generate the negative voltage using eg ICL7660 or even using a 555: https://www.ikalogic.com/555-based-voltage-inverter-schematic/
Just because I'm curious, could you add a link to the servo datasheet?

you can find the link in the 7th comment of the first post.


text:
Configure HC-05
I am trying to send/receive data from Android to my Arduino (via a HC-05) and later from Arduino to Android. I have configured my HC-05 as slave, and the UART=9600,0,0.... To send data from Android to Arduino I don´t have problem but to send data Arduino to Android I can not...
This is my sketch:
char data;
int a=1;
int v=1;
#include SoftwareSerial connection(10,11);//RX|TX
void setup()
{
 pinMode(7,OUTPUT);
 connection.begin(9600);
 digitalWrite(7,LOW);
}

void loop()
{
 if(connection.available()>0)
 {
  data=connection.read();
   if(data=='1')
   {
    digitalWrite(7,HIGH);
    connection.write(data);
    delay(200);
   }
   //connection.write(data);
  }
 }

MY HANDLER IN THE MAIN:
       mhandler=new Handler()        {
        public void handleMessage(android.os.Message msg)            {
            switch (msg.what)
            {
                case MENSSAGESEND:
                    msg = new DriveData((BluetoothSocket)msg.obj);    //DriveData msg = new DriveData((BluetoothSocket)msg.obj);
                    break;
                case MESSAGEREADING:
                    byte[] bufferget = (byte[])msg.obj;
                    String men = new String(bufferget,0,msg.arg1);
                    sb.append(men);
                    int endline=sb.indexOf("\n");
                    if(endline>0)
                    {
                        String print=sb.substring(0,endline);
                        sb.delete(0, sb.length());
                        Toast.makeText(getApplicationContext(),"menssage"+" "+print,Toast.LENGTH_LONG).show();
                        txtData.setText(print);
                    }
                    break;

            }
        };
    };

MY METHOD FOR RECEIVER AND SEND DATA
  public void run()
    {
        byte[] wait=new byte[1024];
        int bytesReceived;
        while (true) {
            try {
                 bytesReceived=entrydata.read(wait);//entrydata is my inputstream
                mhandler.obtainMessage(MESSAGEREADING,bytesReceived,-1,wait).sendToTarget();
            }catch (IOException e){
                break;
            }
        }
    }

sorry but.. what is the line #include SoftwareSerial conexion(10,11);//RX|TX?

what is HC-05 ?

@alcor Bluetooth module. I'd add more details to the question but the Android app is annoying to use.

HC-05 is model from bluetooth for my connection                                                #include SoftwareSerial is the library for use pin´s as RX and TX on arduino UNO, "conexion" is the name from my connection is as variable

Are you sure it's not a simple hardware problem - like the TX pin being disconnected?  You are handling the HC-05 at 3.3 volts right?

No, i have Volt to 5v from arduino, my bluetooth can be using with 3.3v or 5v

@FidelPinedaSantos Just a friendly tip. Code in English, that way it's times easier to read for others.

@avamander I have already changed my codec to english, sorry

@FidelPinedaSantos Have you tried using some of the examples available on the web for communication with this combination of hardware?

I can receive data from android, but i can not yet send data from arduino to android

You are missing the line termination
you must send '\n' after your data in order to receive the data
or use
conexion.println(entrada)
rather then
conexion.write(entrada)

I already did these, but not work, only i can send data from android to arduino


text:
A question about including libraries
I'm a beginner in creating my own libraries so the following might contain some stupid stuff.
Anyways, I'm using NRF24L01+ modules for wireless communication and I've been utilizing the magnificent RF24 library (https://github.com/TMRh20/RF24) to operate these modules using Arduino. I wanted to clean up my code and decided to write my own library that uses the R24 library. My own library would contain all the subroutines that handle TX and RX functions.
Problem is that the RF24 library is initialized using e.g.
/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(7,8);

To begin using the NRF24L01+ one would the use the RF24 library like for example:
byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate.
Serial.begin(57600);
printf_begin();
radio.begin();

radio.setPALevel(RF24_PA_HIGH);
radio.setCRCLength(RF24_CRC_16);

radio.setRetries(2,15);
radio.setChannel(RFChannel);
if(radioNumber){
radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses
radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1
}else{
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1,addresses[1]);
}

if(radioNumber == 1){
radio.startListening(); // Start listening
}
radio.printDetails();

Well, now I would like to make a library that would allow me just to call setup to handle all of the above. My library would be called RadioComm so I would call in my main code:
RadioComm rComm();

setup() {
rComm.setup();
}

The problem is that how do I use the RF24 library and all its functions in my library? To initialize the RF24 library in my own library I would have to call somehow this
RF24 radio(7,8);

and use all the radio. commands. How do I tell my own library that everything starting with "radio." is related to RF24 library because right now I'm getting this:
RadioComm.cpp: In member function 'void RadioComm::setup()':
RadioComm.cpp:20:18: error: 'radio' was not declared in this scope
radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

Below are my .h .cpp and .ino files
Lib_test.ino
#include <RadioComm.h>
#include <RF24.h>
#include <SPI.h>

RadioComm rComm;

void setup() {

rComm.setup();

}

void loop() {

}

RadioComm.h
#ifndef RadioComm_h
#define RadioComm_h

#include "Arduino.h"
#include <RF24.h>

struct dataStruct{
unsigned long id;
float value1;
float value2;
float value3;
float value4;
};

class RadioComm
{

public:

RadioComm();
void setup(void);

private:
int pin1;
int pin2;

};

#endif

RadioComm.cpp
#include "Arduino.h"
#include "RadioComm.h"
#include <RF24.h>
#include "printf.h"

RadioComm::RadioComm(void)
{}

void RadioComm::setup()
{
byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate.
radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 & 10
Serial.begin(57600);
printf_begin();
radio.begin();
radio.setPALevel(RF24_PA_HIGH);
radio.setCRCLength(RF24_CRC_16);

radio.setRetries(2,15);
radio.setChannel(RFChannel);
if(radioNumber){
radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses
radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1
}else{
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1,addresses[1]);
}

if(radioNumber == 1){
radio.startListening(); // Start listening
}
radio.printDetails();
}

Any help is appreciated.
Thanks.

Firstly, to address your compilation error:
RadioComm rComm();

That is not a constructor, that is a function prototype. When you have no parameters to a constructor you must not include the brackets or it confuses the poor little compiler.
RadioComm rComm;

Now - to address your main question.  Well, there's many ways of doing it, but the way I always tackle this is to have your sketch define the RF24 object and pass it to the library for later use.
In the class definition, in the private section, add:
RF24 *radio;

Then change the constructor to have:
RadioComm(RF24 &r);

The constructor itself would then read:
RadioComm::RadioComm(RF24 &r) {
    radio = &r;
}

Now throughout your library, instead of working with radio.whatever you need to work with radio->whatever since you are now using a pointer to an object not the object itself.
Then in your sketch you need to adjust your constructor to be:
RF24 myRadio(7, 8);
RadioComm rComm(myRadio);

The beauty of this is it decouples the configuration of the RF24 class from the RadioComm class, so you can use the same library in a different situation on a different board with different pins without having to change the library - just change the RF24 constructor in your sketch.
It also gives you direct access to the RF24 class in your sketch so you can do any advanced manual tweaks outside the library should you wish to.


text:
Wakeup Pin ESP8266
Is there a way to put an ESP8266 into a sort of "sleep" mode where it draws less power than usual, and then wakes up on a pin going high? I've tried doing this with delay, which still draws 20 mA, and with the deepsleep function that comes with the esp library, which can't sleep for short periods of time to watch for the pin going high. I'm building a watch, and power draw is of great concern to me. Is there possibly a way I could build or code this differently to make it more power efficient?
Basically it works like this, but the full code (at it's current state) can be found here.
void loop() {
    delay(1);
    // check for power signal stuff
    if(digitalRead(0)) {
        // execute data fetching 'n stuff
    }
}

With this many code level attempts you have, it would be nice to see, what is your current efforts on code sample level. In short: show yer codez.

Just connect the RST pin to the button, to "wake" up the ESP8266. You need to connect the other side of the button to Vcc.

In that case @Gerben how much power does it take to call WiFi.begin('stuff')

Added a link to a gist @mico

@CarrotM that's totally unrelated to your question. Create a new question for it, or better, try it out yourself and measure it.

GPIO16 is the only hardware interrupt pin available in deep sleep, and your MCU will reboot when it's triggered.

Without seeing the code and optimizing it I can tell you the following:
ESP8266 has three ways to save power:

Modem sleep - only wlan modem shutdown, connection kept open
Light sleep - less cpu usage, fast recovery
Deep sleep - suspend all, close wifi too, slow recovery

http://bbs.espressif.com/viewtopic.php?t=133

ESP8266 does have deep sleep mode. The link to http://bbs.espressif.com/viewtopic.php?t=133 posted earlier sums it up pretty well, despite being old.
However, a few things that are different from Arduino or should be considered if you're building a battery-operated device:

when the MCU wakes up from deep sleep, the entire application is restarted. Yes, beginning from the setup() function - just as if it was reset. You cannot put it to the deep sleep and then resume from the same place keeping all variables etc. You can only detect that the device was woken up from the sleep by reading a flag in the setup() function.
check your board. If you're not using bare ESP8266, but some development board such as NodeMCU or WittyCloud, it usually has number of other circuits powered on even when the MCU is sleeping. Particularly, USB-UART bridge and maybe power LED.
check your power source. Again, if you're using a development board, very likely it has an inefficient LDO voltage regulator. Even when MCU is powered down, the LDO can still use a few mA just to power itself (quiescent current). There are special low quiescent current regulators exist, very useful for battery-operated application.
finally, I see your code refers some OLED display. Just to be sure - is it powered down or excluded from the measurement? OLED doesn't need a lot of energy, but will drain a battery in a few days.

Personally, I do have experience creating a battery-operated device on ESP8266, which wakes up every few minutes, connects to wifi and sends some data. An old 700mAh Lithium battery is enough to run it for approximately a month. And I managed to get the sleep power to about 40 microAmps. Still a few times more than the chip itself needs, but good enough for me.

Only a month? I roughly estimate for your case 250 mAs per wake-up, plus the 40 uA standby. To use 250 mAs per wake-up I guess you are using DHCP? static IP reduce the connection time to about 250 ms (multiplied by 200 mA is 50 mAs) and should extend the battery a lot (or... your battery is way lower than 600 mA I assumed).

I use static IP, so it's not a problem. But there is also a sensor that needs to be initialized and used. Also establishing the network connecting and sending data takes some time. So the awake time for each wake up is 2-3 seconds (every 5 minutes). It probably doesn't use full 250mA all that time, but twice less on average, which, over 5 minutes, gives average consumption of 0.9mA. Or 650mAh in 30 days. Seems pretty accurate.

authors: Никита Носов


text:
NodeMCU (ESP8266) board controlled over shared hosting database
I have a NodeMCU (ESP8266) board that I want to control over the internet. I am trying to find a solution where I don't have to set up any configurations on my router like port forwarding. I came up with the following solution:

I have a website where the user changes the device status (with status I mean for example GPIO5 pin value HIGH or LOW) which is then saved to a database on a shared hosting server. The NodeMCU sends periodically (for example every 5 seconds) a HTTP GET request to the database. According to the value that is received from the database the NodeMCU board changes the pin value to HIGH or LOW. If NodeMCU changes it's status (for example a pin value from HIGH to LOW) the new device status is sent to the database with a HTTP POST request. The device also sends a HTTP POST request periodically (for example every 60 seconds) so the user can monitor the device status on the website.
There are a few problems with this configuration:

There is no real-time connection between NodeMCU and the user (there
is always a delay in the device response)
The device sends thousand of queries every day that are a load to
the shared hosting server. For example if the GET request is sent
every 5 seconds, that gives 17280 queries per day for one device.

So my question is how practical is this configuration on shared hosting or any kind of hosting, what are the alternatives or improvements to this configuration and how to establish a connection with the NodeMCU so that the device sends a GET request to the database only when the device status is changed in the database by the user.

a HTTP request can wait until the server has something to send as a response

@Juraj please check out my question at stackoverflow https://stackoverflow.com/questions/55932766/postpone-http-get-response-until-the-user-changes-the-value-in-the-database

you can check if the client is still connected and if not, send the request again. but I don't know how to handle the php side

just use websockets; a 2-way always-connected low-overhead protocol supported by webserver platforms and ESPs. You could also use server-sent events, which almost any php box can support, and for which you can semi-easily mod the existing ESP libs to handle.

@dandavis can I use websockets without the need to configure my router (for example setting port forwarding)

websockets works without adjusting any router settings.

@dandavis I tried to use websockets but I had some difficulties on finding an example (how to install a websocket server on a shared hosting server) on the internet. Do you know where I can find an example where the websocket server is on a shared hosting server and the websocket client is an ESP8266

you probably can't do it on a shared server, you would have to use SSE, a light modification of normal HTTP.

Use MQTT.
You need:

The PubSubClient.h library
An MQTT server

For MQTT there are some free ones around on the internet (ask Google). Or if you have a Linux server available for use (e.g., a cheap VPS server from one of many many providers online) then you can run your own with mosquitto.
MQTT works kind of how you describe, but it's not making constant GET requests - it opens a single connection to the MQTT server and realtime requests are sent down it to the client, and back from the client to the server.
Near realtime communication.


text:
Why Smart Plugs don't require setting port forwarding on router and how to accomplish this with NodeMCU (ESP8266)
I have a NodeMCU (ESP8266) board that I use to control some devices over the internet. To be able to access it I have to enable port forwarding on my router and set the port manually like in the image below:

But with Smart Plugs (that use a cloud based app) I don't have to set up anything on my router. I am only required to type my Wi-Fi password. So my question is how Smart Plugs are accessed over the router (why they don't need manual port forwarding setting), and how to apply this to my NodeMCU so I don't have to set port forwarding manually.

Port forwarding is required to allow a device outside your router to access a device inside a router that performs NAT (Network Address Translation).
When a NodeMCU is acting as a simple server to respond to requests, it is inside your network, and so the port-forwarding is required so that your phone or computer on the Outside can access it.
However, for the cloud-based "smart" devices, it is different. The smart device opens a connection from itself to a server (the cloud) outside your network. In this case, the router understands that a new two-way connection is created between the cloud server and your smart device.
The only communication to your smart device is from the cloud server to the smart device. If you have an app on your mobile device or computer, that app or website only accesses the cloud server, when then passes the instruction on to your smart device. Reverse direction for status info from the smart device to your app, etc.
These smart devices rely on the infrastructure of their creators to continue to work. There are no LAN-to-LAN connections from the client to the device. Everything goes through the Internet to the remote cloud server, and back.
Many home routers support a protocol called uPNP, that allows a device inside the network to request port forwarding to itself. Some routers require this to be explicitly enabled, because it's a security risk to allow any device to be able to open holes in your firewall/router.
To have your NodeMCU device do this, look for libraries for ESP8266 that implement uPNP. I did a quick search and found https://github.com/ofekp/TinyUPnP though I cannot vouch for it's effectiveness or safety.

Great answer, thanks for the quick response.

MQTT is another protocol worth looking at. It's commonly used in IoT devices (and supported cloud platforms such as the Amazon/Azure IoT offerings) to solve the same problem.

Another question, To avoid port forwarding I made a website where the user sets the device status to ON and OFF. The device status is then stored in a MySQL database. The devices then makes a GET request to the database and retrieves the device status and sets the device ON or OFF. The database is queried every 10 seconds for one device. In your opinion is this approach practically and how many devices can work on one database. Sorry for bothering you.

Whether it's practical is up to the available resources: Your database and server, the bandwidth required, etc.


text:
Problem: char string not working with SoftwareSerial.h
I am creating a program to display text on an OLED display and then have it sent to a thermal printer.
The issue is my second char string: word_buffer
When I try to use word_buffer for any reason it crashes the program and nothing will work (the OLED display will not refresh upon uploading the sketch and typing on the keyboard will not update the display).
The program works fine when you omit the code needed for the thermal printer (Adafruit_Thermal.h, SoftwareSerial.h, and other setup).
The sample code is below, I've commented out the section where I try and utilize word_buffer.
If I remove the thermal printer setup code and uncomment that section, the program will run just fine.
Let me know what you think, I've been stuck on this for a while now :/
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include <Adafruit_Thermal.h>
#include <PS2Keyboard.h>
#include <MemoryFree.h>

#include <SPI.h>
#include <Wire.h>

#define LED_PIN 13

// OLED display
#define OLED_MOSI  A4
#define OLED_CLK   A3
#define OLED_DC    A2
#define OLED_CS    A0
#define OLED_RESET A1
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

// printer
#include "SoftwareSerial.h"
#define GND_PIN 7
Adafruit_Thermal printer(&Serial, 4);

// keyboard
const int DataPin = 8;
const int IRQpin =  3;
PS2Keyboard keyboard;

#define HIDDEN_BUF 21
#define VIS_BUF 168
#define WRD_BUF 32

char line_buffer[HIDDEN_BUF + VIS_BUF + 1];
int line_start = HIDDEN_BUF;
int line_len = 0;
int word_len = 0;
char word_buffer[WRD_BUF + 1];

void setup() {
  keyboard.begin(DataPin, IRQpin);

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

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

  for (int i = 0; i < HIDDEN_BUF + VIS_BUF; i++)
    line_buffer[i] = ' ';

  line_buffer[HIDDEN_BUF + VIS_BUF] = 0;

  for (int i = 0; i < WRD_BUF; i++)
    word_buffer[i] = ' ';

  word_buffer[WRD_BUF] = 0;

  display.begin(SSD1306_SWITCHCAPVCC);
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.println(line_buffer + HIDDEN_BUF);
  display.display();

  Serial.begin(9600);
  printer.begin();
}

void loop() {

  if (!keyboard.available()) return;

  char c = keyboard.read();

  boolean newline = false;

 if (c == PS2_DELETE) {
    if (line_len > 0) {
      line_len--;
      line_buffer[line_start + line_len] = ' ';
      if (word_len > 0)
      word_len--;
    }
  }

//  if (word_len > 0)
//  line_buffer[188] = word_buffer[1];

  if (c >= 33 && c <= 126) {
    word_len++;
    line_buffer[line_start + line_len] = c;
    word_buffer[word_len] = c;
    line_len++;
     }

  if (c == 32) {
    line_buffer[line_start + line_len] = c;
    line_len++;
    for (int i = 0; i <= 32; i++)
      word_buffer[i] = ' ';
    word_len = 0;
  }

  display.clearDisplay();
  display.setCursor(0, 0);
  display.println(line_buffer + HIDDEN_BUF);
  display.display();
}

char word_buffer[WRD_BUF + 1] = {' '}; will init the array with spaces

Thanks Juraj, that makes sense and would save some code but I'm still not sure how to get the code to run with word_buffer

My guess is you are running out of memory and can't allocate the oled display buffer.

Thanks @Majenko do you have any suggestions? Note that using multiple char arrays works fine without the thermal printer code, so I'm not sure why that affects it so much?


text:
Why am I getting "expected primary-expression before '.' token"?
I know this is a common question but the truth is every code is different. Sometimes it's hard to apply the concept to your code, it does not work. So please help me. What is wrong with this code? I got it from GitHub. I'm trying to compile it first before I can do a little modification, it sends temp and humidity data to ThingSpeak cloud servers.
#include <DHT.h>  // Including library for dht
#include <ESP8266WiFi.h>

String api_key = "YOUR API KEY"; // Enter your Write API key from ThingSpeak
const char *ssid = "YOUR WIFI SSID"; // replace with your wifi ssid and wpa2 key
const char *pass = "YOUR WIFI PASSWORD";
const char* server = "api.thingspeak.com";

#define DHTPIN 1 // pin where the dht11 is connected
DHT dht;

WiFiClient client;

void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);
  Serial.println("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
}

void loop() {
  int chk = DHT.read(DHTPIN);
  float hum = DHT.humidity;
  float temp = DHT.temperature;
  if (isnan(hum) || isnan(temp)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  if (client.connect(server, 80)) {
    // "184.106.153.149" or api.thingspeak.com
    String data_to_send = api_key;
    data_to_send += "&field1=";
    data_to_send += hum;
    data_to_send += "&field2=";
    data_to_send += temp;
    data_to_send += "\r\n\r\n";
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + api_key + "\n");
    client.print("Content-Type: application/x-www-form-
    urlencoded\n");
    client.print("Content-Length: ");
    client.print(data_to_send.length());
    client.print("\n\n");
    client.print(data_to_send);
    delay(1000);
    Serial.print("Temperature: ");
    Serial.print(temp);
    Serial.print(" degrees Celcius, Humidity: ");
    Serial.print(hum);
    Serial.println("%. Send to Thingspeak.");
  }
  client.stop();
  Serial.println("Waiting...");
  // ThingSpeak needs minimum 15 sec delay between updates, I've set it to 30 seconds
  delay(10000);
}

When I compile I get this error,
  Arduino: 1.8.10 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E
  Module), 80 MHz, Flash,
  Legacy (new can return nullptr), All SSL ciphers (most
  compatible),
 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"

    C:\Users\Agent 96\Desktop\thingspeak\thingspeak.ino: In function 'void loop()':

   thingspeak:37:20: error: expected primary-expression before '.' token

  int chk = DHT.read(DHTPIN);

                ^

  thingspeak:38:22: error: expected primary-expression before '.' token

  float hum = DHT.humidity;

                  ^

  thingspeak:39:23: error: expected primary-expression before '.' token

  float temp = DHT.temperature;

                   ^

  Multiple libraries were found for "DHT.h"
  Used: C:\Users\Agent
  Not used: C:\Users\Agent
  Multiple libraries were found for "ESP8266WiFi.h"
  Used: C:\Users\Agent
  exit status 1
  expected primary-expression before '.' token

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

Please help, I'm kind of a beginner.

Change three lines right after loop() to these:
  int chk = dht.read(DHTPIN);
  float hum = dht.humidity;
  float temp = dht.temperature;

Change 'DHT' into lower case letters. DHT is the class and dht is the object of the DHT class.
Also you have multiple copy of these libraries: DHT.h and Esp8266WiFi.h. Check your cuurent directory where your Arduino code is and also Documents->Arduino->Libraries directory. These libraries should be in the  Documents->Arduino->Libraries directory.

You defined DHT as dht. So you'll have to replace those DHT with dht and you'll be good to go.


text:
Sending a string from Arduino to ESP8266 works on UNO but not on Pro Mini

I have a project where I am getting sensor data and sending it over to an ESP8266-01 to send to ThingSpeak. After some work I got it to work. So like a real smart person I decided to replace the Arduino UNO I was using (that worked) with an Arduino Pro Mini. Using the same code and connections the String isn't sent to the ESP and then not to ThingSpeak.
Here is a reduced version of the sending code that I used on the UNO and the Pro.
#include <FS.h>
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>
//#include <SoftwareSerial.h>

//SoftwareSerial espSerial(A0, D1); // RX | TX
//stuff to bring in string
const byte numChars = 32;
char receivedChars[numChars];
char tempChars[numChars]; // temporary array for use when parsing
// variables to hold the parsed data
char messageFromPC[numChars] = {0};
float floatFromPC = 0;
float floatFromPC2 = 0;
boolean newData = false;
//end stuff ti bring in string
String f;
String start = "start";
//NEW STUFF START
char Password[36] = "";
char apiKey[16] = "";
WiFiClient client;
//eeprom new end
char defaultHost[100] = "";
//Thing Speak IP address (sometime the web address causes issues with ESP :/
long itt = 500;
long itt2 = 500;
const byte wifiResetPin = 13;
int interruptPinDebounce = 0;
long debouncing_time = 1000;
volatile unsigned long wifiResetLastMillis = 0;
bool shouldSaveConfig = false;

void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

void handleWifiReset() {
  if (millis() < wifiResetLastMillis) {
    wifiResetLastMillis = millis();
  }
  if ((millis() - wifiResetLastMillis) >= debouncing_time) {
    Serial.println("Clearing WiFi data resetting");
    WiFiManager wifiManager;
    wifiManager.resetSettings();
    SPIFFS.format();
    ESP.reset();
    delay(1000);
  }
  wifiResetLastMillis = millis();
}
int addr = 0;
void setup() {
  //EEPROM.begin(512); //Initialize EEPROM
  WiFiManager wifiManager;
  Serial.begin(9600);
  //espSerial.begin(115200);
  pinMode(wifiResetPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(wifiResetPin), handleWifiReset, FALLING);
  WiFiManagerParameter customAPIKey("apiKey", "ThingSpeakWriteAPI", apiKey, 16);
  //END NEW STUFF
  //WiFiManager
  //Local initialization. Once its business is done, there is no need to keep it around
  //WiFiManager wifiManager;
  //NEW STUFF START
  //wifiManager.setSaveConfigCallback(saveConfigCallback);
  wifiManager.addParameter(&customAPIKey);
  //END NEW STUFF
  //reset saved settings
  //wifiManager.resetSettings();
  //set custom ip for portal
  //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
  //fetches ssid and pass from eeprom and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  wifiManager.autoConnect("AutoConnectAP");
  Serial.println("Connected");
  //NEW STUFF START
  strcpy(apiKey, customAPIKey.getValue());
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["defaultHost"] = defaultHost;
    json["apiKey"] = apiKey;
    Serial.println("API");
    Serial.print(apiKey);
    String apiKey2 = String(apiKey);
    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }
    json.printTo(configFile);
    json.printTo(Serial);
    delay(1000);
    configFile.close();
    //end save
  }
  Serial.println("local ip");
  Serial.println(WiFi.localIP());
  //END NEW STUFF
  //or use this for auto generated name ESP + ChipID
  //wifiManager.autoConnect();
  //Serial.println("WriteApi");
  //Serial.println(apiKey);
  //if you get here you have connected to the WiFi
  //Serial.println("K)");
  //save the custom parameters to FS
  strcpy(apiKey, customAPIKey.getValue());
  EEPROM.begin(512); //Initialize EEPROM
  // write appropriate byte of the EEPROM.
  // these values will remain there when the board is
  // turned off.
  EEPROM.write(addr, 'A'); //Write character A
  addr++; //Increment address
  EEPROM.write(addr, 'B'); //Write character A
  addr++; //Increment address
  EEPROM.write(addr, 'C'); //Write character A
  //Write string to eeprom
  String www = apiKey;
  for (int i = 0; i < www.length(); i++) {
    //loop upto string lenght www.length() returns length of string
    EEPROM.write(0x0F + i, www[i]); //Write one by one with starting address of 0x0F
  }
  EEPROM.commit(); //Store data to EEPROM
  //Read string from eeprom
}

//callback notifying us of the need to save config
void loop() {
  //new stuff string
  recvWithStartEndMarkers();
  if (newData == true) {
    strcpy(tempChars, receivedChars);
    // this temporary copy is necessary to protect the original data
    //   because strtok() used in parseData() replaces the commas with \0
    parseData();
    showParsedData();
    newData = false;
  }
  //new stuff string end
  WiFiManager wifiManager;
  if (WiFi.status() == WL_DISCONNECTED) {
    wifiManager.autoConnect("AutoConnectAP");
  }
  delay(1000);
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("Connected");
    delay(1000);
    WiFiClient client;
    long itt = 50;
    long itt2 = 200;
    char defaultHost[100] = "api.thingspeak.com";
    EEPROM.begin(512);
    Serial.println(""); //Goto next line, as ESP sends some garbage when you reset it
    Serial.print(char(EEPROM.read(addr))); //Read from address 0x00
    addr++; //Increment address
    Serial.print(char(EEPROM.read(addr))); //Read from address 0x01
    addr++; //Increment address
    Serial.println(char(EEPROM.read(addr))); //Read from address 0x02
    //Read string from eeprom
    String www;
    //Here we dont know how many bytes to read it is better practice to use some terminating character
    //Lets do it manually www.circuits4you.com  total length is 20 characters
    for (int i = 0; i < 16; i++) {
      www = www + char(EEPROM.read(0x0F + i)); //Read one by one with starting address of 0x0F
    }
    Serial.print(www); //Print the text on serial monitor
    if (client.connect(defaultHost, 80)) { // "184.106.153.149" or api.thingspeak.com
      itt++; //Replace with a sensor reading or something useful
      String postStr = www;
      postStr += "&field1=";
      postStr += String(floatFromPC);
      postStr += "&field2=";
      postStr += String(floatFromPC2);
      postStr += "\r\n\r\n\r\n";
      client.print("POST /update HTTP/1.1\n");
      client.print("Host: api.thingspeak.com\n");
      client.print("Connection: close\n");
      client.print("X-THINGSPEAKAPIKEY: " + String (www) + "\n");
      client.print("Content-Type: application/x-www-form-urlencoded\n");
      client.print("Content-Length: ");
      client.print(postStr.length());
      client.print("\n\n\n");
      client.print(postStr);
      Serial.println("% send to Thingspeak");
    }
    client.stop();
    Serial.println("Waiting…");
  }
  delay(5000);
}

//more new stuff for string
void recvWithStartEndMarkers() {
  static boolean recvInProgress = false;
  static byte ndx = 0;
  char startMarker = '<';
  char endMarker = '>';
  char rc;
  while (Serial.available() > 0 && newData == false) {
    rc = Serial.read();
    if (recvInProgress == true) {
      if (rc != endMarker) {
        receivedChars[ndx] = rc;
        ndx++;
        if (ndx >= numChars) {
          ndx = numChars - 1;
        }
      } else {
        receivedChars[ndx] = '\0'; // terminate the string
        recvInProgress = false;
        ndx = 0;
        newData = true;
      }
    } else if (rc == startMarker) {
      recvInProgress = true;
    }
  }
}

void parseData() { // split the data into its parts
  char * strtokIndx; // this is used by strtok() as an index
  strtokIndx = strtok(tempChars, ","); // get the first part - the string
  strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC
  strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
  floatFromPC = atoi(strtokIndx); // convert this part to an integer
  strtokIndx = strtok(NULL, ",");
  floatFromPC2 = atoi(strtokIndx); // convert this part to a float
}

void showParsedData() {
  Serial.print("Message ");
  Serial.println(messageFromPC);
  Serial.print("Float ");
  Serial.println(floatFromPC);
  Serial.print("Float ");
  Serial.println(floatFromPC2);
}
//end new stuff string

Sorry for the length but... I don't know if I need to modify how I send the string or I have to turn on the TX and RX pins in the Pro Mini. I have tried connecting the RX Arduino to TX ESP and TX Arduino to RX ESP and RX to RX and TX to TX with no results. I know the pins work because I have programmed the ESP and the PRO numerous times with the TX and RX pins.
Can anyone help me with this? It is driving me crazy.

Are you using the same connections between the ESP and either Arduino? Cross-connecting RX/TX is correct. The Uno is a 5v device; the ESP is a 3.3v device. The Pro-mini could be either. Did you use level shifters or equivalent with the UNO? Does the Pro-mini both need & use them (5v Pro-mini) or not need and not use them (3.3v Pro-mini)?

So I tried some experiments.  I had an adapter module attached to the ESP so I removed it and wired directly to the ESP.  I went from the Pro's board pins both RX to TX and TX to Rx and the other way around with no upload, no flashing tx led on board I also tried from the header pins at the end of the board both T

sorry hit return here is the end of the previous comment  TX to RX and RX to TX and visa versa.  But with no better results.  I usually use level shifters but didn't for the experiment on the Arduino Uno and the Arduino Pro Mini.  Without the shifter it worked with the UNO and not the Pro Mini.  So I don't think it is the pin connections.

Something about you Pro-min is different from you Uno. (Operating voltage? Frequency? Baud-rate selection?) We don't have enough information (yet) to know what it is, but that's the direction you'll need to take.

So the ESP is running off a separate voltage regulator 3.3v.  I have tried all kinds of baud rates on both Pro and ESP.  The ESP is supposed to run at 115200 and when I try to reset it it says that the 115200 baud rate is overridden with 115200 but what ever rate I put in the code to override I have to set the serial monitor to that rate to have it read correctly.  The Pro says its normal rate is 57600 but I have tried to reset it and nothing seems to help.  I need a definitive answer.  Is the TXO on the Pro board go to the RX on the ESP and RXI to TX.  this is how I have it set up.

Here is a print out of the upload form computer to Pro Mini               Using Port                    : /dev/cu.usbserial-00000000                          Using Programmer              : arduino                                                          Overriding Baud Rate          : 57600                                                               AVR Part                      : ATmega328P

You have the Tx->Rx and Rx->Tx connections correct (called "cross-connected"). "Overriding baud rate...etc" is correct during upload. The boot-loader sets a known baud-rate for uploading, and avrdude on your PC sets the PC's baud-rate to that same value. The word "overriding" is confusing here but just means that during upload, it won't be using the last rates you left them at. ...

... Still wondering though, how your Uno and Pro-mini are different. Is each of them a 5v device? Is/was the Arduino & ESP grounds connected to each other? Is/was the ESP being powered by the Arduino's 3.3v power pin (it shouldn't be)? Is the Arduino Tx -> ESP RX connected via either a voltage divider or a level converter (it must be, but the reverse connection, ETx -> ARx, is OK without). Is Arduino using the UART on pins [1,2] or SoftwareSerial (If SS, you'll need to keep your baud rates down to 9600)? A schematic of your power & communication connections would help.

UNO and Pro are both 5v.  the UNO and the ESP both have common ground and when originally hooked up the UNO is powered by a battery source that has booster to 9v put into Vin pin.  The ESP is powered by the 9v going through a 3.3 v regulator.  On the Pro it is powered by by the 9v booster going to a 5v regulator then into 5v vcc pin to power the board the ESP is powered by going thru 3.3v regulator.  relay is turned on for a brief time to power the ESP with the 3.3v on both so as to save power.  9v going into UNO I think is regulated down to 5v.  I can't think of anything else. both are 16 htz

If I re-read your post correctly, the connection, Arduino Tx -> ESP Rx, is direct-wired. But the Arduino's 5v is too high for the ESP and may have damaged its Rx pin driver. Does Uno still work? All I can do more is repeat that you or we need schematics of the working- and non-working systems and a more detailed problem description than "... it works great on the Arduino UNO but not on the Arduino Pro Mini". Tough problems need taking a step back and applying a rigorous, complete, and step-by-step analysis. Pls upd your ques with schematics, & clear description of how they behave differently.

Each time I changed baud rate I reprogrammed ESP using RX-TX so they are working fine. I have read that over long exposure it could fry them but for short periods it is ok. One I have this figured out I will put them in. The PRO I am using is a knock off so that could be it. I have ordered a genuine one from SparkFun and will swap it out when it gets in. I am uploading two wiring diagrams

The one difference I see between your two schematics is that the Uno uses its on-board 5v regulator and your external 5v regulator seems to have no function. The Pro uses your external 5v regulator. Why the difference? Have you tried supplying the Pro's Vin/Raw input with 9v as you do the Uno? I have no idea why this should be problematic; it's just a difference I see, that I would rule-out. I'd also make the reverse experiment and compare either MCU board being supplied at its Vin from your external regulator.

I will try that. The raw input on the PRO voltage regulates to 5v so I didn’t think there should be a difference. Is there a way to program the ESP8266 using the Arduino PRO MINI like I do the UNO. that way I would know if the RX TX on PRO board is working.

You should be able to do anything with the Pro that you can with the Uno. But didn't you say you were able to do that (2nd to last sentence of your posting)?

I program the ESP with the UNO then switch it over to the Pro. I am on the road right now but will try it when I get home. Can’t see why the change in voltage input should make a difference

I tried hooking up the 9vdc to the raw and disconnecting the 5vdc to the VCC. The PRO shows it has power by the red led but the pins don’t seem to work. At least the #2 pin doesn’t come on when it is supposed to. If I disconnect the 5v and plug in the header power the #2 pin doesn’t respond like it should. I think the board is messed up. I will attempt to remover and replace it. Any suggestions on removal.

Today I installed a new Arduino Pro Mini and programmed it. The hookup now is the same as with the Arduino UNO shown above. 9v goes to raw input. When connected to the battery everything works as it should except the sensor numbers are NOT transmitted from the Pro to the ESP. I am going to try connecting TX-TX and RX-RX. but I don’t think that will work. Could it be that when I send the numbers from the Pro to the esp, the esp starts broadcasting before it receives the sensor numbers?  Should I have it run longer to see if it gets the numbers for the 2nd broadcast? Still no TX leds in Pro.

I finally got this to work by repeating the Serial.print (f); and then delay(1000); multiple times.  I changed my original post to reflect this.  Somehow this gets the string over to the ESP so it can parse it and upload it.  Now all I want to do is add a temperature sensor and maybe add an IFTTT to the whole thing so if the low end gets too low or the high end too high (of the water level I can get a notification to check out the whole system.
Thanks JRobert for the help I got the power I needed to the board.