text:
I can upload via USB but not FTDI
I have a Adafruit Pro Trinket. I'm having issues getting GPS and and SD card working together. The trinket can be connected via USB but there is no serial connection do debugging my program is hard.

I purchased an FTDI connector from sparkfun, installed the FTDI software and connected to the trinket. My code complies but it won't flash. The error is confusing:
Can anyone please help me figure out how to get it to flash?
Arduino: 1.6.4 (Mac OS X), Board: "Pro Trinket 3V/12MHz (FTDI)"

Sketch uses 19,896 bytes (69%) of program storage space. Maximum is 28,672 bytes.
Global variables use 1,476 bytes of dynamic memory.
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1a21": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Here is the "verbose" version of the error:
Arduino: 1.6.4 (Mac OS X), Board: "Pro Trinket 3V/12MHz (FTDI)"

Using library SPI in folder: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SPI
Using library Adafruit GPS Library in folder: /Users/futurebird/Documents/Arduino/libraries/Adafruit-GPS-Library-master
Using library SoftwareSerial in folder: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial
Using library SdFat in folder: /Users/futurebird/Documents/Arduino/libraries/SdFat (legacy)

/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=12000000L -DARDUINO=10604 -DARDUINO_AVR_PROTRINKET5FTDI -DARDUINO_ARCH_AVR -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/variants/eightanaloginputs -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SPI -I/Users/futurebird/Documents/Arduino/libraries/Adafruit-GPS-Library-master -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial -I/Users/futurebird/Documents/Arduino/libraries/SdFat /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp -o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.o
Using previously compiled file: /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SPI/SPI.cpp.o

(^^repeats many times for different files)

/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc -Wall -Os -Wl,--gc-sections -mmcu=atmega328p -o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SPI/SPI.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/Adafruit GPS Library/Adafruit_GPS.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SoftwareSerial/SoftwareSerial.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/MinimumSerial.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdFatBase.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdFatUtil.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiCard.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiSAM3X.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiSTM32F1.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiTeensy3.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFile.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFileLFN.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFilePrint.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFileSFN.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatVolume.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FmtNumber.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/fstream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/istream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/ostream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/StdioStream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/core.a -L/var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp -lm
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.eep
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy -O ihex -R .eeprom /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.hex

Sketch uses 19,896 bytes (69%) of program storage space. Maximum is 28,672 bytes.
Global variables use 1,476 bytes of dynamic memory.
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbmodem1a21 -b115200 -D -Uflash:w:/var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.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.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/futurebird/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.usbmodem1a21
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1a21": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

avrdude done.  Thank you.

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

UPDATE
I looked in the /dev/ directory and found these which match the menu in Arduino.
cu.Bluetooth-Incoming-Port
cu.Bluetooth-Modem
cu.JabraREVOa400-SPPDev
cu.LightBlue-Bean

The above files are int the dev folder but not cu.usbmodem1a21. How can I get it? Or is it looking for the wrong file?
This is what my board selection looks like. I think the issue is the port?

"can't open device "/dev/cu.usbmodem1a21": No such file or directory"

I made an update after looking for the file.

Have you installed the FTDI driver? The error message means avrdude can't find your trinket.

Things to check:

Does the file exist? check with ls if the file that avrdude tries to open is actually there
Do you have the right to open it? Opening a serial port requires having the appropriate rights, iow you user belongs to the same group that the device belongs to.
On linux this is usually wheel or dialout, depending on the distro. Again, ls -la is your friend.
Is your device identified correctly? Meaning that you are not trying to have avrdude address the device wit the wrong protocol.

The device is identified as Adafruit pro, 3v FTDI. I can flash successfully with Adafruit pro, 3v USB. The file in question is not there. I don't know how to get it ... or ... I suspect another file since the file is the name at the bottom of the compile window.


text:
Reading a photoresistor
I have a wire with a 0-5v current. I want to detect if the current is there or not (HIGH/LOW.)
I'm using an optocoupler to avoid putting too much current into my micro, as it is only a 3.3V micro. I'm nervous about powering this on as one of my other micros stopped working although it's not clear if it could have been the circuit?

I could not find my optocoupler in fritzing. This is it:
http://www.amazon.com/gp/product/B00CGXK1RG?psc=1&redirect=true&ref_=oh_aui_detailpage_o07_s00
This is my plan.

The microcontroller is a spark/particle core 3.3v. It the yellow wire connects to the analog pin A6. The screw terminals connect to the wire with the 5v current that I'm trying to detect.
I based my circuit on this:

But I don't know if it will do the same thing.

What's the optocoupler for again?

The micro is at 3.3v but the signal I'm trying to detect passively is at 5v

I thought you were trying to read a photoresistor.

Not in the TLP621. That model uses a phototransistor.

Thanks my diagram is incorrect here is the relevant datasheet: http://en.f-alpha.net/electronics/optoelectronics/optocoupler/get-started/different-optocoupler/

Do you want to detect a current or a voltage? Why not just use a voltage divider to detect if the voltage is there?

White LED needs about 3V to operate. Here it eats all your breakfast. Short LED, short R4,. Make R2 say 1K. Connect A6 input to R2 to  opto junction. connection.

Based on the revised information given above I present a different answer. Use the opto-coupler as shown here:
Your kettle LED will be in series with the optocoupler (note the polarity, not reversed like in your question).
If the LED is on the transistor in the PC817 will conduct and the Arduino pin will be LOW. If the LED is off the transistor will not conduct and the Arduino pin will be HIGH.

Note: The Arduino pin will be the reverse of the kettle LED.
I'm leaving the other answer there because I think it is a reasonable answer to the question of "detect a voltage".

This works! Thanks for the help. I learned a good deal from both of these answers.

Wouldn't this be simpler?

Note: amended answer increases R1 to 10 k.
The 10 k resistor limits current to 0.17 mA. The 3.3 V zener diode clamps the input voltage to 3.3 V (I measured 2.3 V on mine so that is well within spec). The other end of the zener diode goes to the Arduino ground pin.
I originally had R1 as 1 k however if you had a high voltage input (like 20 V) it didn't quite clamp the pin to 3.3 V (more like 3.8 V). This is a bit high for an input pin, so I tried 10 k instead.
This gives:

For an input voltage of 5 V -> 2.3 V on the Arduino input
For an input voltage of 10 V -> 2.6 V on the Arduino input
For an input voltage of 20 V -> 2.9 V on the Arduino input
For an input voltage of 30 V -> 3.1 V on the Arduino input

This is all within spec for the Arduino.
Now the question is, will 2.3 V on the input pin register as HIGH? The answer is "yes" because high is considered to be 0.6 * VCC.
3.3 * 0.6 = 1.98

Thus any voltage of 1.98 or above is considered HIGH, and it will successfully read 2.3 V as high.

What is the zener diode connected to? If there is a voltage spike what happens?

It's connected to ground (the triangle part).  I tested with higher input voltages, and increased R1 to 10 k (from 1 k in my original answer). That clamped input voltages as high as 30 V to a safe level.

this won't work. it triggers the device to turn on and off. I can't ground the 5v signal except using the ground line associated with it. I tried a voyage divider which is a similar concept and that didn't work.

I'm really unclear about this. How does connecting it via a 10 k resistor "ground the 5 V signal"? Can you describe your set-up more completely? Are you saying the ground from your device, and the ground from the Arduino, need to be separate? What is this device exactly? In your question, your images seems to show an LED (is this the device?) wired backwards in polarity to the opto-coupler you are using.

The device is a kettle. it has a 5v board with the on off buttons and temp display. I have successfully emulated the momentary button presses the turn the kettle on and off with a relay via Internet. but I need to know if it worked. I also need to know if the kettle is in an on state due to a manual button press. these cables are two of five cables that form the the input output for the 5v board. every time my micro reads it triggers the kettle to turn on or  off.

Are you using opto-couplers for the other things (operating the button)? Or are you sharing a common ground?

everything else is separate. the buttons are triggered through a relay shield. it seems any change to the kettle's 5v line can make it change states. I just want to passively read.

source: Stack Exchange

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

sort: votes


text:
One free pin. Need to display output for the user?
I'm working with lightblue bean. I have a device that writes data to an SD card on a long button press and switches what will be written (from a list of 5 items) on short button press.
The output, printed both to the SD card and to serial looks like this:
12:38, 7/15/15, subway
12:55, 7/15/15, subway
12:38, 7/15/15, bus
12:55, 7/15/15, rail

etc. It's basically a time stamp then a vale from this list:
char* modes[]= {"walking", "subway", "bus", "railroad", "other"};

This works perfectly. But the bean has very few pins:

5 SCK  -- connected to SD card.
4 MISO -- connected to SD card.
3 MOSI -- connected to SD card.
2 SS   -- connected to SD card.
1      -- input button, takes long and short presses
0      --
A1 SDA --- connected to real time clock for timestamp
A0 SCL --- connected to RTC (real time clock) for timestamp

I have one free DIGITAL pin. I need to let the user know what they have selected. This could be done with 5 LEDs that light up next to the user's choice, or maybe displayed text? This is a portable item so a servo that points to the user's choice might be too unreliable.
I've done some research into shift registers. They all seem to need 3 digital pins min. If I could do it with 2 I could rework the button...
Ideas?

Have you considered morse code? ;)

Use SPI to send data to a shift register (or several) to drive LEDs, or 7-segment displays, etc. The free pin becomes the latch signal to the shift registers.  SPI is a bus, use it like one.

The 7-segment display board is all very well, but that displays 4 digits. That isn't exactly 5 LEDs. In any case that board has a chip on it, if you are going to buy another chip you may as well get an Attiny and use that. Just have serial input (same as the 7-segment board did).
On the Attiny you have 8 pins, 3 of which will be reserved: Vcc, Gnd, Reset. That leaves you with 5 for the communications and the 5 LEDs. So, use one pin for incoming serial, or two pins for SDA/SCL, and use the remaining 3 pins for the LEDs. You can can use Charliplexing to use 3 pins to light up to 6 LEDs.

For the fun of it, I made up an example using my Uno (it still only uses 3 pins to light 6 LEDs).

There are 3 x 100 Ω resistors as in the schematic. One is completely hidden by the LEDs (leading from the middle yellow wire to the middle pins of the LEDs).
Code:
const byte X1 = bit (2);   // D2 on Uno
const byte X2 = bit (3);   // D3 on Uno
const byte X3 = bit (4);   // D4 on Uno

const byte patterns [7] [2] = {
// PORT DDR
  { 0,   0, }, // all off
  { X1, X1 | X2 }, // LED1: X1 on,  X2 off, X3 HiZ
  { X2, X1 | X2 }, // LED2: X1 off, X2 on,  X3 HiZ
  { X2, X2 | X3 }, // LED3: X2 on,  X3 off, X1 HiZ
  { X3, X2 | X3 }, // LED4: X2 off, X3 on,  X1 HiZ
  { X1, X1 | X3 }, // LED5: X1 on,  X3 off, X2 HiZ
  { X3, X1 | X3 }, // LED6: X3 on,  X1 off, X2 HiZ
};

void setup ()
  {
  }  // end of setup

void loop ()
  {
  for (int i = 0; i < 7; i++)
    {
    DDRD = patterns [i] [1];
    PORTD = patterns [i] [0];
    delay (500);
    }  // end of for loop
  }  // end of loop

The code displays each of the 6 LEDs (plus all off) in a cycle. For each one it configures the DDR (data direction register) plus the PORT (output register) appropriately to light the desired LED.
It works perfectly, except that you may need to work out which LED is which by experimentation.

Seems you have I²C on the board you could possibly use an I²C LCD backpack, like from breakouts if you already have an LCD, this means you can have the RTC and display on the I²C bus and probably more things.
Another option seems you mentioned LEDs, you could still use the I²C bus and use an I/O expander and hook LEDs up to that and address them over the I²C. You can use a PCF8575(16 I/O), as there are Arduino libraries. There are breakouts for it. Or you could make your own from another AVR, like one from the ATTiny line, seems there is 5 LEDs.
A I²C bus example:

(source: ermicro.com)
Seems you want to use the PWM, you can use a dot/bar driver IC, such as the LM3914 it takes an analog value and shows it as a point on the strip of LEDs, example below:

The IC can also work down to 3V.
What you will need to do is add a low pass filter to convert the PWM to a smooth analog value. You will add this in place of the input circuitry(D1 & C1) there:

If there is any confusion on the LM3914, there are quite a few tutorials on google.

l2C takes two pins in addition to power and ground-- both  of the options you mention take as many pins as a shift register. I might just need to redesign....

I'm giving you credit for helping but maybe my question should have been more clear.

@futurebird  I2C uses the same two pins which you are using, it is a bus? You can use both the RTC and a display option together. What's wrong with that?

l2C takes two pins in addition to power and ground - you share the same two pins. Each device on the I2C bus has its own address. That answer was perfectly feasible.

Can it work at 3.3v? The bean is a 3.3v device and the project is battery powered (can't add a power supply.)

@futurebird - Yes, the IC can work from 0 - 3.3V, datasheet

The peak detector on the original '3914 circuit may work fine as a LPF.

@IgnacioVazquez-Abrams - ok good point, +1, keep this  up top

I've found a solution! 7-segment display breakout board.

This works art 3.3v which is critical for a lightblue bean. I think a servo might be the most creative solution.
I'm still convinced there must be some way to use PWM...

It looks like that particular board (can) use async serial, thus the one-wire solution (plus power and ground) will use serial output to drive it.

If you're going to use that board then you may as well use the MCU on it and dump the Bean.

The bean has very nice BLE (bluetooth) I'd rather not drop that feature.

all_licenses: 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/


text:
ESP8266 + DHT11 AWS IOT Thing not updating thing shadow - was working before
I was able to get this working - https://www.youtube.com/watch?v=8hpro1olRK0 - send an SMS and email of temperature and humidity data from AWS IOT using esp8266 + dht11 but all of a sudden it stopped updating the shadow.
Here is the code

#include <ESP8266WiFi.h>
#include <DHT11.h>
#include <AmazonIOTClient.h>
#include <ESP8266AWSImplementations.h>

Esp8266HttpClient httpClient;
Esp8266DateTimeProvider dateTimeProvider;

AmazonIOTClient iotClient;
ActionError actionError;

const char* ssid = "";
const char* password = "";

// Pin 2 will be used to read sensor data
int pin = 2;

// Initializing the sensor
DHT11 dht11(pin);

//Function to convert Celsius to Fahrenheit
double Fahrenheit(double celsius) {
  return ((celsius * 9 / 5) + 32);
}

void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println();

  // Connecting to Wi-Fi
  WiFi.mode(WIFI_STA);
  Serial.println();
  Serial.println();
  Serial.println("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  iotClient.setAWSRegion("us-west-2");
  iotClient.setAWSEndpoint("amazonaws.com");
  iotClient.setAWSDomain("al1x5kb4rzh0x.iot.us-west-2.amazonaws.com");
  iotClient.setAWSPath("$aws/things/esp8266/shadow/update/accepted");
  iotClient.setAWSKeyID("AKIAJJQ6ASLIDIPBE4PQ");
  iotClient.setAWSSecretKey("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");
  iotClient.setHttpClient(&httpClient);
  iotClient.setDateTimeProvider(&dateTimeProvider);
}

void loop() {
  int err;
  float temp, humi;

//Reading the sensor data
  if ((err = dht11.read(humi, temp)) == 0) {
    Serial.print(" temperature:");
    Serial.print(temp);
    Serial.print(" humidity:");
    Serial.print(humi);
    Serial.println();
  } else {
    Serial.println();
    Serial.print(" Error No :");
    Serial.print(err);
    Serial.println();

  }
// Converting the float data to char arrays
  char sTemp[10], sHumi[10];
  dtostrf(humi, 6, 2, sHumi);
  dtostrf(temp, 6, 2, sTemp);

// Creating the thing shadow to be sent to aws iot
  char shadow[100];
  strcpy(shadow, "{\"state\":{\"reported\": {\"Humidity\":");
  strcat(shadow, sHumi);
  strcat(shadow, ", \"Temperature\":");
  strcat(shadow, sTemp);
  strcat(shadow, "}}}");
  Serial.print(shadow);

  char* result = iotClient.update_shadow(shadow, actionError);
  Serial.print(result);

  delay(60000);
}

Output as expected
Connecting to
NETGEAR53
.........
WiFi connected
 temperature:31.00 humidity:32.00
{"state":{"reported": {"Humidity": 32.00, "Temperature": 31.00}}}al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
443
POST $aws/things/esp8266/shadow/update/accepted HTTP/1.1
Content-Type: application/json
Connection: close
Content-Length: 65
Host: al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
x-amz-content-sha256: 923ed1ae613a9e14b45e4d080b092daf5cf61118041dc5225956299d5b0f8d49
x-amz-date: 20180323T034259Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIAJJQ6ASLIDIPBE4PQ/20180323/us-west-2/iotdata/aws4_request,SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date,Signature=a10f0969043e609743412478567c10290b8c000185f2824e4a9cf07bb96cf279

{"state":{"reported": {"Humidity": 32.00, "Temperature": 31.00}}}

#include <ESP8266WiFi.h>
#include <DHT11.h>
#include <AmazonIOTClient.h>
#include <ESP8266AWSImplementations.h>
Esp8266HttpClient httpClient;
Esp8266DateTimeProvider dateTimeProvider;
AmazonIOTClient iotClient;
ActionError actionError;

A small correction on the output, sometimes its perfect but some other times  i get timeout receiving time server data
{"state":{"reported": {"Humidity": 41.00, "Temperature": 31.00}}}al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
443
POST /things/ESP/shadow HTTP/1.1

{"state":{"reported": {"Humidity": 41.00, "Temperature": 31.00}}}timeout receiving timeserver data

I am also facing the same problem and still, I didn't get any answer...current I am also working on that

Anyone get this solved? I have the same issue

I am planning to try cleaning the AWSiot libraries, that worked last time but again only one device works for me as of now. Probably I might try a different set of code. Please share your code guys -- I will try to help. Also I am trying different AWS keys.

Pls post the aws iot libraries you are using. Ot sure what changed but nothing works and thing shadow not getting updated

Just Change the Aws topic :
it should be  $aws/things/esp8266/shadow/update
and you have to add the certificate path also

I was facing a similar problem: trying to update a thing's shadow on AWS IoT with no success. After some research, I found out that I was using an outdated library. In this question they advise to use heskew's aws-sdk-arduino, on iot-get-shadow-and-cleanup branch:
https://github.com/heskew/aws-sdk-arduino/tree/iot-get-shadow-and-cleanup.
Additionally, I think you have a little error on your code. As far as I know, AWSPath, it should look like:
iotClient.setAWSPath("/things/esp8266/shadow");

At least that works for me, and they use it this way on this video.
That's all I can tell... I am learning at this moment as well.
Hope it helps!!

Thank you so much for your response, really appreciate it. My thing name is actually ESP so i have it set as ---iotClient.setAWSPath("/things/ESP/shadow");--- or should it only be esp8266?
i deleted old libraries and used the one above but still my thing shadow is not updating. Please help. The other example video you referred - that also is not working

https://arduino.stackexchange.com/questions/51059/esp8266-dht11-aws-iot-thing-not-updating-thing-shadow-was-working-before

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


text:
Serial parsing strange data
I have a project where I use a software serial connection to read serial data from a barcode scanner.
All is good. However from time to time I have some problems with the data that I'm receiving.

You said : 123456789��?�: @���?���?���?���?���?
You said : 123456789
You said : 123456789123456
You said : 987654321789456123

My code is something similar to the one below

int count = 0;
void parseSerial() {
  char ser[20];
  while (Serial.available() > 0) {
    char c = Serial.read();
    if ( c != '\r' && count <= sizeof(ser)) {
      ser[count] = c;
      count++;
    } else {
      Serial.print("You said : ");
      Serial.println(ser);
      for(int i=0; i < sizeof(ser); i++) {
        ser[i] = '\0';
      }
      count = 0;
    }
  }
}

Any idea on how I can get rid of "��?�: @���?���?���?���?���?"?
Thanks.

The problem is that the buffer is not initialized to start with. When
you call parseSerial(), it contains garbage, which is what you see on
the serial monitor. In order to avoid printing out that garbage, you
have to properly terminate the string, i.e. add a \0 after the last
valid character.
You did that after printing the string (you filled the whole buffer
with \0, which is overkill), but that's too late. The subsequent
printouts are OK though.
The recommended way to handle incoming serial data is to look for a
terminating character (\r seems to be what you expect), and buffer
all the incoming bytes until you see it. Don't forget to save 1 byte of
buffer space for the terminating \0:
void parseSerial() {
    static char buffer[20];
    static int count = 0;

    while (Serial.available()) {
        int c = Serial.read();
        if (c == '\r') {           // received complete line
            buffer[count] = '\0';  // terminate the string
            Serial.print(F("You said: "));
            Serial.println(buffer);
            count = 0;
        }
        else if (count < sizeof buffer - 1) {
            buffer[count++] = c;
        }
    }
}

Notice that the buffer here being static, you can accumulate partial
messages through successive calls to parseSerial(). Only when the
message is complete will it print it back.

Why are you using char array when you can use String. And use Serial.readStringUntil('\r'); instead Serial.read.
Code:

void parseSerial(){
String read = " ";
int count = 0;
if(Serial.available()>0){
while(Serial.available()>0){

if(count != 20){
read = Serial.readStringUntil('\r');
count++;
}
}

}
Serial.println("You said: ");
Serial.print(read);
}


text:
Master Reader/Slave Sender with Distance Sensor
I am currently working on a project and want to transmit the information from a distance sensor from one arduino the another, but what i receive in the master board are not the correct measurements.
Slave Code
#include <Wire.h>

const int trig = 12;
const int echo = 13;

int state = 0;
int count = 0;
int contor = 0;
int set_distance = 5;
long duration, Distanceincm;

void setup()
{
  Wire.begin(4);                // join i2c bus with address #4
  Wire.onReceive(receiveEvent); // register event
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);           // start serial for output
}

void loop()
{
 digitalWrite(trig, HIGH);
  delay(15);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  Distanceincm = (duration / 58);
  if (state == 0 && (Distanceincm < set_distance) ) {
    state = 1;
    count++;
    contor++;
    Serial.print("Distance=");
    Serial.println(Distanceincm);
    Serial.print("Count=");
    Serial.println(count);
    Serial.print("ConuntDay=");
    Serial.println(contor);
  }
  if (Distanceincm > set_distance) {
    state = 0;
  }
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
  while(1 < Wire.available()) // loop through all but the last
  {

  Wire.write(Distanceincm);
  Wire.write(count);
  Wire.write(contor);
}

Master Code
#include <Wire.h>

void setup()
{
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start Serial for output
}

void loop()
{
  Wire.requestFrom(2, 6);    // request 6 bytes from slave device #2
  while(Wire.available())    // slave may send less than requested
  {
    long a = Wire.read();
    Serial.print ("Distance = ");
    Serial.println(a);

    int b = Wire.read();
    Serial.print ("Count = ");
    Serial.println(b);

    int c = Wire.read();
    Serial.print ("CountDay = ");
    Serial.println(c);
  }

  delay(500);
}

What i get on the serial monitor is this :

Your receive event should be reading some data.  If you don't read any data then that while loop becomes an infinite loop.

You should also note that wire.read gets you a byte, not a long or an int.

What I see right away is, that you assign address 4 to the slave, but the master reads from address 2.

You have data coming in over I2C.  Compared to the speed of the processor, that data is coming in really slowly.  When the first byte of the data arrives, wire.available() becomes 1.  Now your code enters that loop.  It tries to read a bunch of stuff from wire, but only the 1 byte has shown up so far.  When you call read and there's nothing available it returns -1 which (as a byte) looks like 255 when it gets stuffed into a byte.  I bet something like that is happening but I don't have time to look at Wire and see how it returns.

@Delta_G Wire.requestFrom() is a blocking call. When it exits the whole I2C message was received. It also returns the number of received bytes, I think.

ok then.  I couldn't open up the library from where I was and I knew that other things inheriting Stream did that.

Your code has some flaws, that I will address here:

The main problem, that you see here, is that you only let the slave write data into the buffer, when it is receiving data. But you never send data to it. So there is never anything in the buffer.
In the slave code you have
void receiveEvent(int howMany)
{
  while(1 < Wire.available()) // loop through all but the last
  {

  Wire.write(Distanceincm);
  Wire.write(count);
  Wire.write(contor);
}

Besides the unbalanced parentheses (which let's me think, that this might not be the actual code, that you are running currently), you are writing to the buffer only inside the receiveEvent(). That only get's called, when the master does a Master-Write transmission (via Wire.beginTransmission() and Wire.endTransmission()). In the master code you are only using Wire.requestFrom(). If you want to send back data on a request, you need to use the onRequest callback of the Wire library. You need to set the appropriate callback function:
Wire.onRequest(onRequestEvent);

And then write data inside that callback function:
void onRequestEvent(){
    Wire.write(...)
}

I will explain how to write the values correctly in a different point below.
In the receiveEvent() function you want to loop through all received bytes but the last. But you are not doing anything with the data. You aren't even reading it. As your code currently stands, this line does not make any sense.
In your master code you are requesting data from the slave with the address 2. Your slave code initiates the Wire library with the address 4. From that point there should never be a successful I2C transmission, unless you have another slave on the bus with the address 2 (another point, where I suspect, that these codes are not exactly the ones used for the test).
In the master code you are using
while(Wire.available())

because the slave might have send less data, than requested. You are testing, that the number of available bytes is not zero. But then you are reading 3 bytes without checking again, which means, when you received 2 byte, you still would try to read 3 bytes, which cannot give good results.
The condition should be Wire.available() >= 3, to check, if at least 3 bytes are in the buffer, because you are reading 3 bytes from it. But also the loop does not make much sense to me. As you have a binary protocol here, how would you treat additional data (meaning excess data, send after the first valid data frame)? You want to receive 3 values per transmission and you are reading 3 values in one iteration of the loop. If there where more data in the buffer, you would be reading the next 3 bytes, throwing away the first 3 bytes. I don't think, that is what you want.
Instead use the return value of Wire.requestFrom(), which is the number of received bytes. Use it to distinguish valid transmissions, from those, which are too short:
uint8_t n = Wire.requestFrom(4, 3);
if(n >= 3){ // at least 3 bytes where received
    uint8_t value1 = Wire.read();
    uint8_t value2 = Wire.read();
    uint8_t value3 = Wire.read();
}

Any transmission, that is too small, will get ignored. Excess data in too long messages will also be ignored. Note, that I used uint8_t, which is an unsigned integer with 8 bits (1 byte) here for simplicity of that points logic. More about your data types and their implications on your code below.
For the to send datatypes on the slave you have int and long. int is a signed integer with 16 bits, long is a signed long integer with 32 bits. (I suspect you don't need a long for the distance, as ultrasonic sensors mostly reach only 3m, but that is up to you). In contrast the argument of Wire.write() is an uint8_t, which has only 8 bits. That call is used to put exactly 1 byte into the buffer, not more. When you are using
Wire.write(Distanceincm);

you are putting the least significant byte of Distanceincm into the buffer. The rest will just be thrown away (this happens at the cast from long to uint8_t). This works as long, as the value is between 0 and 127 (which is the upper part of the int8_t value range). With higher (or lower) values your received data will be garbage. Instead you need to write every byte of your data into the buffer:
Wire.write(Distanceincm  & 0x000000FF);
Wire.write((Distanceincm & 0x0000FF00) >> 8);
Wire.write((Distanceincm & 0x00FF0000) >> 16);
Wire.write((Distanceincm & 0xFF000000) >> 24);

With bitwise ANDing (&) of the hexadecimal value 0x000000FF, we are deleting all bits, beside the least significant byte (analog with 0x0000FF00 for the second least significant byte, and so on). Then we are shifting the corresponding byte to the position of the least significant byte (8 bits for the seconds least significant byte, 16 bits for the third least significant byte, and so on), which then gets used by Wire.write(). To better understand this, read about bitwise operators on the web.
You have to send both integer values in a similar fashion (though they both have only 2 bytes instead of 4).
Now that we are sending more bytes, we also need to receive and read all these bytes correctly. First we need to request the correct number of bytes. 4 bytes for the long value and 2 bytes for both int values --> 8 bytes. So you need to request 8 bytes:
Wire.requestFrom(4, 8);

Then you need to read these bytes into the corresponding variables:
long distance = Wire.read()
                | (Wire.read() << 8)
                | (Wire.read() << 16)
                | (Wire.read() << 24);

We are using the bitwise OR (|) to put the bytes together, shifting every byte to its correct position in the long value. In a similar way you are putting together the 2 int values.


text:
Holding buttons (keyboard)
I made a wireless keyboard, but I just need 4 button for my project: left control, left shift, F1, F2.
The problem: When I hold button - it acts like many key presses and releases, but I need, that when I press & hold button - it also acts like I press & hold it.
Could you please help me?
Here is source code:
Transfer_e5.ino:  https://www.paste.org/108039
Receiver_e5.ino:  https://www.paste.org/108040
Or 1 rar package:
https://easyupload.io/o3c5sp
Thank you
Or I can put them just here, if you wish.
Receiver:
#include <Keyboard.h>
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(8,7); // (ce,cs)
RF24Network network(radio);

const uint16_t this_node = 00;
const uint16_t other_node = 03;

unsigned int laser_state=0;
const unsigned long my_interval = 500;
unsigned long last_sent;
unsigned int income=0;

void setup(void)
{
  Serial.begin(115200);
  pinMode(9,INPUT_PULLUP);

  SPI.begin();
  radio.begin();
  network.begin(90,this_node);

  pinMode(4,OUTPUT);
  digitalWrite(4,LOW);
}

void loop(void){
  digitalWrite(4,LOW);
  network.update();

  if ( network.available() ) {
    RF24NetworkHeader header;
    network.read(header,&income,sizeof(income));

    if(income==10){
      Serial.println("f1");
      Keyboard.press(KEY_F1);
      income=0;
    }

    if(income==11){
      Serial.println("f2");
      Keyboard.press(KEY_F2);
      income=0;
    }

    if(income==12){
      Serial.println("ctrl");
      Keyboard.press(KEY_LEFT_CTRL);
      income=0;
    }

    if(income==13){
      Serial.println("shift");
      Keyboard.press(KEY_LEFT_SHIFT);
      income=0;
    }

    Keyboard.releaseAll();
  }

  unsigned long now = millis();

  if ( now - last_sent >= my_interval  )
  {
//    Serial.print("pin ");
//    Serial.println(digitalRead(9));
    last_sent = now;
    laser_state = digitalRead(9);

    RF24NetworkHeader header(other_node);
    bool ok = network.write(header,&laser_state,sizeof(laser_state));
  }
}

Transfer
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(8,7);
RF24Network network(radio);

const uint16_t this_node = 03;
const uint16_t other_node = 00;

unsigned int laser_state=0;
const unsigned long interval = 5;
unsigned long last_sent;

unsigned int b1=1;
unsigned int b2=1;
unsigned int b3=1;
unsigned int b4=1;

unsigned int d1=10;
unsigned int d2=11;
unsigned int d3=12;
unsigned int d4=13;

//TR1
int btn1 = 3;
int btn2 = 4;
int btn3 = 5;
int btn4 = 6;

void setup(void)
{
//  Serial.begin(9600);
  pinMode(btn1,INPUT_PULLUP);
  pinMode(btn2,INPUT_PULLUP);
  pinMode(btn3,INPUT_PULLUP);
  pinMode(btn4,INPUT_PULLUP);

  SPI.begin();
  radio.begin();
  network.begin(90,this_node);
}

void loop(void){
  network.update();

  unsigned long now = millis();

  if ( now - last_sent >= interval  )
  {
    last_sent = now;

    b1 = digitalRead(btn1);
    b2 = digitalRead(btn2);
    b3 = digitalRead(btn3);
    b4 = digitalRead(btn4);

    if(b1==0){
//      Serial.println("F1");
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,&d1,sizeof(d1));
    }

    if(b2==0){
//      Serial.println("F2");
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,&d2,sizeof(d2));
    }

     if(b3==0){
//      Serial.println("Ctrl");
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,&d3,sizeof(d3));
    }

    if(b4==0){
//      Serial.println("Shift");
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,&d4,sizeof(d4));
    }
  }
}

I am NOT downloading some random RAR file from some random site. Post your code here if you want any help.

your right   , lol

i add codes  to the note  , thanks again

The root problem is that you send each several ms new key event and on receiver each time you get this event, you call Keyboard.press and right away Keyboard.release. So, it behaves as several key press-releases.
At sender side you should send 2 types of events:

Key pressed (and which button)
Key released (and which button)

At receiver side you should

When you receive "press" event, call Keyboard.press, and don't call Keyboard.release
When you receive "release" event, call Keyboard.release

Edit: I've made changes to your source code, please, try it
Transfer
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(8,7);
RF24Network network(radio);

const uint16_t this_node = 03;
const uint16_t other_node = 00;

unsigned int laser_state=0;
const unsigned long interval = 5;
unsigned long last_sent;

unsigned int b1=1;
unsigned int b2=1;
unsigned int b3=1;
unsigned int b4=1;

unsigned int d1=10;
unsigned int d2=11;
unsigned int d3=12;
unsigned int d4=13;

//TR1
int btn1 = 3;
int btn2 = 4;
int btn3 = 5;
int btn4 = 6;

void setup(void)
{
//  Serial.begin(9600);
  pinMode(btn1,INPUT_PULLUP);
  pinMode(btn2,INPUT_PULLUP);
  pinMode(btn3,INPUT_PULLUP);
  pinMode(btn4,INPUT_PULLUP);

  SPI.begin();
  radio.begin();
  network.begin(90,this_node);
}

void loop(void){
  network.update();

  unsigned long now = millis();

  if (now - last_sent >= interval)
  {
    last_sent = now;

    auto newB1 = digitalRead(btn1);
    auto newB2 = digitalRead(btn2);
    auto newB3 = digitalRead(btn3);
    auto newB4 = digitalRead(btn4);

    unsigned int packet[2];

    if(newB1 != b1){
//      Serial.println("F1");
      packet[0] = d1;
      packet[1] = newB1;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

    if(newB2 != b2){
//      Serial.println("F2");
      packet[0] = d2;
      packet[1] = newB2;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

     if(newB3 != b3){
//      Serial.println("Ctrl");
      packet[0] = d3;
      packet[1] = newB3;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

    if(newB4 != b4){
//      Serial.println("Shift");
      packet[0] = d4;
      packet[1] = newB4;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

    b1 = newB1;
    b2 = newB2;
    b3 = newB3;
    b4 = newB4;
  }
}

Receiver
#include <Keyboard.h>
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(8,7); // (ce,cs)
RF24Network network(radio);

const uint16_t this_node = 00;
const uint16_t other_node = 03;

unsigned int laser_state=0;
const unsigned long my_interval = 500;
unsigned long last_sent;

void setup(void)
{
  Serial.begin(115200);
  pinMode(9,INPUT_PULLUP);

  SPI.begin();
  radio.begin();
  network.begin(90,this_node);

  pinMode(4,OUTPUT);
  digitalWrite(4,LOW);
}

void loop(void){
  digitalWrite(4,LOW);
  network.update();

  unsigned int income[2] = {0, 0};

  if ( network.available() ) {
    RF24NetworkHeader header;
    network.read(header,&income,sizeof(income));

    auto keyCode = income[0];
    auto keyPress = !income[1];

    if(keyCode == 10){
      Serial.println("f1");

      if (keyPress) {
        Keyboard.press(KEY_F1);
      } else {
        Keyboard.release(KEY_F1);
      }
    }

    if(keyCode == 11){
      Serial.println("f2");

      if (keyPress) {
        Keyboard.press(KEY_F2);
      } else {
        Keyboard.release(KEY_F2);
      }
    }

    if(keyCode == 12){
      Serial.println("ctrl");

      if (keyPress) {
        Keyboard.press(KEY_LEFT_CTRL);
      } else {
        Keyboard.release(KEY_LEFT_CTRL);
      }
    }

    if(keyCode == 13){
      Serial.println("shift");

      if (keyPress) {
        Keyboard.press(KEY_LEFT_SHIFT);
      } else {
        Keyboard.release(KEY_LEFT_SHIFT);
      }
    }

    keyCode = 0;
  }

  unsigned long now = millis();

  if ( now - last_sent >= my_interval  )
  {
//    Serial.print("pin ");
//    Serial.println(digitalRead(9));
    last_sent = now;
    laser_state = digitalRead(9);

    RF24NetworkHeader header(other_node);
    bool ok = network.write(header,&laser_state,sizeof(laser_state));
  }
}

thanks for answering my question  ,  what i want from this keyboard is while i am holding 3 button together  ( left control +  left shift + F1 ) then i will push F2 button   ,,,    it should work like that   ( i know i sounds stupid   but  i need that ) ,,, i will be greatful  if you could fix the codes  and send them for me  , thanks again

@AminAbbasi done

thanks again and again  , i am in  travel and it takes 2 days ,,  i will check the codes and device  at sunday and report it to you immediately ,   thanks again  and   how can i compensate   ,,, i owe you one

@AminAbbasi glad to help you, hope it will work :) If not - write again and we will try to find out what's wrong!


text:
How do I stop 5v on the I2C port of a pro mini so I can use 3.3v devices?
The theory is that you can use 3.3v I2C devices from a 5v device as long as the pull ups are only to the 3.3v. I have a 5v pro mini connected to a bmp180 board which has a 3.3v regulator but no level shifters. It is working and giving me data but I am hoping I can get better quality measurements. One observation is the power rail on the BMP board after the 3.3v regulator is being pulled towards 5v. On the scope this looks to happen between i2c messages. I am using the "Adafruit-BMP085-Library" which is in turn using "Wire". In the wire library there is a comment that says that the writedigital() of 1 to the port is setting the pull ups.
Does anyone have any general advice on this issue?
What does the comment about setting the pull-ups mean? How is that function setting the pull ups?
When does the I2C switch back to being an GPIO? Are the lines being pulled high between messages because it is reverting to an GPIO?

This page explains the problem and offers some solutions. http://www.varesano.net/blog/fabio/how-disable-internal-arduino-atmega-pullups-sda-and-scl-i2c-bus

Your question is unclear. What is a bmp180 (I could google, but you should include a link). I²C is open drain and requires pullups. The Arduino does not have these, and they are often on the  I²C board. If these are to 3.3V OK, otherwise you have to remove, and install pullup to 3.3V. You could disable any internal pullups, which are useless, but if you use 1.8kΩ they would swamp any internal pullups.

Whoever decided it would be a good idea to default to using the Arduino internal pull-up resistors on I2C needs taking out back and giving a good kicking. It is so wrong on so many levels.
Yes, if you disable the internal pull-up resistors you can safely use 3.3v devices. The simplest way to do this is to turn them off again as soon as you have done Wire.begin(); by writing 0 to the pins with digitalWrite().

I think it has been done this way so you can just connect chips to it without having to bother with any pull-ups. But it is kind of lazy and if you want it to work in the real world then it does need to be done properly. The AdaFruit module has level shifters on it. Overkill if everything is set up OK. There is still a 5v spike. Not sure if this will cause a reliability problem later. But looks a lot better on the scope now.

@BillyBag2 Not only is it kind of lazy, but it teaches new users that you don't need pullups on an I2C bus, so they get into all sorts of trouble when they transition to a better system.


text:
Change Digispark clock speed, run at low voltage?
I have a low voltage (3.2v) application. I was hoping to use the Digispark. I have a solution using a separate Tiny85, but want to use the Digispark USB programming.
To run at lower voltage I think you need the lower clock rate. I have done this using the standalone Tiny85. I could hook up the Digispark to the programmer direct and change the frequency fuses, however...
I assume reducing the clock rate by programming the fuses would break the Digispark boot loader as it would have the wrong timing. Correct?
Can I dynamically switch the clock frequency in my code after the bootloader or is it fuse controlled only?
Is the bootloader available and could I change it to a lower frequency? Would there be a lot of work changing the code to a different freq? Would it be powerful enough to run the USB bootloader?

You can set the clock prescaler at run time. For example:
#include <avr/power.h>

void setup()
{
    clock_prescale_set(clock_div_8);
    // etc...
}

More details in the documentation from
avr-libc.
Note that with this method your Digispark will still be overclocked when
booting, so it might not be 100% reliable. But it will be overclocked
only for a very short time.

I was kind of hoping it would hobble through the boot loader over clocked as I do not need it to actually connect to usb at the low voltage.

@BillyBag2: I would expect it to work. See the answers to this related question: Arduino 16 MHz with only 3.3V?.

Thanks Edgar, This was useful for me for a Digispark ATTiny85 (china clone) that is talking I2C to an ESP8266 NodseMCU v3 Lolin. I have divided by 4 and still works. The ATTiny´s own current consumption has lowered from 11.2mA @16Mhz to 5.6ma. The ATTiny is powered 3.3v from the NodeMCU's regulator 3.3v output to it's 78L05 (output).
I have disabled both LEDs with two, almost invisible, small cuts in the PCB, i could re-solder if necessary.
I am using Rambo's TiniwireS library for I2C. Thanks again.

The digispark uses the micronucleus bootloader.
You can flash that directly onto an Tiny85 without needing the digispark module. So your existing Tiny85 solution could acquire the USB bootloader if you can spare the 2k program space for the bootloader.
I realize this is not a direct answer to your question, but you did note that you have a Tiny85 solution and wanted USB bootloader support on it.

Maximum safe frequency at 3.2V is around 12.7Mhz. See figure 20-2 in the datasheet.
This is indeed lower than the 16MHz the digispark is running at.


text:
Using Arduino Yún to send data through Ethernet
I'm still new to Arduino Yún and I can't find any tutorials or examples on making the Yún send data through Ethernet, which will then be showed on a web server.
I've seen other tutorials but they use Uno with an Ethernet shield.  Is it the same with the Yún too?
How can I send data through Ethernet using Yún?

There are three bits of information you need to know:

The Ethernet port is connected to a tiny Linux computer
On Linux you can do HTTP POST and HTTP GET using a program called cURL
The AVR chip can tell the Linux computer what to do using the Process library.

Putting all those together: You need to use the Process library to tell Linux to run curl with the right parameters.
Just like the tutorials show you:

https://www.arduino.cc/en/Tutorial/Process


text:
Use distance sensor to trigger LED strip and stay on while the person is in range
I'm trying to use a distance sensor to trigger an LED light, as you can see below. However, I also want the LED to stay on/white when a person is within the 38 inches range. How should I do that?
//Tell the Arduino IDE to include the FastLED library
#include <FastLED.h>

//Setup the variables for the HC-SR04
const int trigPin = 9;
const int echoPin = 6;
//Setup the variables for the NeoPixel Strip
#define NUM_LEDS 60 // How many leds in your strip?
#define DATA_PIN 4 // What pin is the NeoPixel's data line connected to?
CRGB leds[NUM_LEDS]; // Define the array of leds

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}

void loop() {
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(2);
  digitalWrite(trigPin, LOW);

  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  if (inches <= 38)  {
    for ( int colorStep = 0; colorStep < 256; colorStep++ ) {
      int r = 255 - colorStep;
      // Redness starts at zero and goes up to full
      int b = 255 - colorStep;
      // Blue starts at full and goes down to zero
      int g = 255 - colorStep;
      // No green needed to go from blue to red
      // Now loop though each of the LEDs and set each one to the current color
      for (int x = 0; x < NUM_LEDS; x++) {
        leds[x] = CRGB(r, g, b);
      }
      // Display the colors we just set on the actual LEDs
      FastLED.show();
      delay(10);
    }
  } else if (inches > 38) {
    fill_solid( &(leds[0]), NUM_LEDS /*number of leds*/, CRGB::Black);
    FastLED.show();
  }
  delay(1000);
}

long microsecondsToInches(long microseconds) {
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second). This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

Your code appears to be doing just that. Could you explain what the current code is doing, that you want different?

You could set the pinmodes in the setup, for improved performance, but other than that, your code looks sane. As Gerben said, what is the actual problem here? Try uncommenting the "fill solid white" function in your if? En commenting the colorwheel thingy


text:
MATLAB and Arduino communication
I have to send from MATLAB to Arduino a char line 'S' to start the Arduino program and send back values from a sensor.
This is my MATLAB code

clear;
delete(instrfind);
s = serial('/dev/cu.usbmodem1411','BaudRate',9600, 'Terminator','CR/LF');
fopen(s);
fprintf(s,'%s\n','S');

t = 0;
valor=zeros(1,100);
tiempo=zeros(1,100);
fid=fopen('resultats.txt','w');
for i=1:100
    a = fscanf(s,'%d');
    wd = 0.0189*a - 14.499;
    valor(i)=wd;
    tiempo(i)=t;
    fprintf(fid,'%3d %6d\n', wd,t);
    t = t+200;
end
plot(tiempo,valor);
fclose(fid);
fclose(s);

and my Arduino code is this
int outValue = 0;
unsigned long time;
void setup() {
  Serial.begin(9600);
  while (Serial.available() <= 0 || Serial.read() != 'S') {
    Serial.println("Send 'S' to start");
    delay(200); }
  Serial.println("Starting measurement");
}
void loop() {
  outValue = analogRead(A0);
  Serial.println(outValue);
  delay(200);
}

the problem is that when I use the MATLAB code it send an 'S' and it makes Arduino start sending values back, but Arduino does not do that and just sending the while loop again and again.
Is the problem in the MATLAB code when it send the char 'S'?

Could you try delaying for a couple of seconds between fopen(s); and fprintf(s,'%s\n','S');?


text:
Arduino nano clone problem with interrupt on falling edge on pin 2
I've s 1Hz square wave coming from a DS1307 SQW/OUT pin going into pin2 on the Nano that is set up as input with internal pullup enabled.
I've set up the interrupt on falling edge but I can't get the ISR to execute every second (it's not executing at all). If I wire up a button normally open to ground pin2 and I press and hold it down I can get the ISR to execute.
Where's the problem:

Is the DS1307 not grounding fast enough for the falling edge logic to
pick it up ?
Is the internal pullup resistance on pin2 too high for the square
wave to be picked up (tension on pin2 is never high enough to trigger
a falling/rising edge event) ?
Is 1Hz too fast for the internal falling/rising edge logic to trigger the
event ?
Have I done something else wrong ?
Is it a problem on the clone only ?

This is a snippet of the code to get an idea of what I'm trying to do:

    void rtc_setCG(byte val);
    const byte rtc_id = 0x68; //DS1307 i2c id: 0x68h, 104 dec, 150 octal, 1101000b
    pinMode(2, INPUT_PULLUP);
    attachInterrupt (digitalPinToInterrupt(2), rtcout_int, FALLING);
void rtcout_int ()
{ char buf[5] = "    ";
  time_t now;
  struct tm *ts;

  wdt_reset();
  noInterrupts();
  epoque++; //this is a global volatile unsigned long variable that holds the number of seconds since the arduino epoque
  interrupts();
}
void rtc_setCG(byte val)
{ Wire.beginTransmission(rtc_id);
  Wire.write((byte)0x07);
  Wire.write(val);
  Wire.endTransmission();
}
ISR (TIMER1_COMPA_vect)
{ byte nsecond;
  nsecond=(byte)((millis()/1000) % 60);
  if ( nsecond != second )
  { second=nsecond;
    epoque++;
    minute=(byte)((epoque / 60) % 60);
    hour=(byte)(((epoque / 3600) + timezone) % 24);
  }
}
rtc_setCG(0x10); //this is how I set up the ds1307 to do 1hz on the SQW/OUT

I've put a speaker on the SQW/OUT and I can hear it click so the DS1307 is set up right for what I'm trying to do but I can't get the ISR to execute on the falling edge. I tried plying with rising edge or change but made no difference.

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

The full code and or snippets  is not possible because I've since then worked around the problem by using the 1Hz from the RTC to do other stuff.


text:
Arduino SIM5320e HTTP GET request to 000webhost.com
Im having trouble getting a successful HTTP GET request to a domain under 000webhost.com
I am trying to do a GET request which sends data to a php file on my domain and save it to MySQL database. I also did this first on my browser and it works fine so I don't think there are problem in my php file.
MY DOMAIN: wastedb.000webhostapp.com
But if I try to send a request to dweet.io, it works as expected.
I am using a modified version of Adafruit_FONA library and will post the code snippet and response from serial monitor below.
Here are the parameters that I used for the WORKING GET request:
Host Address: www.dweet.io
Host: dweet.io
Response from Serial monitor for dweet.io (working):
---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="www.dweet.io",80,1
<--- OK
---> AT+CHTTPSSEND=64
<--- >
---> GET /dweet/for/gearhead?hello=world HTTP/1.1
Host: dweet.io

<--- OK
---> AT+CHTTPSSEND
<--- OK
<--- +CHTTPSSEND: 0
---> AT+CHTTPSRECV?
<--- +CHTTPSRECV: LEN,361
---> AT+CHTTPSRECV=361
<--- OK
+CHTTPSRECV: DATA,361
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Date: Wed, 30 Jan 2019 00:16:43 GMT
Connection: keep-alive
Content-Length: 196

{"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing
---> AT+CHTTPSCLSE
<--- OK
---> AT+CHTTPSSTOP
<--- OK

As we can see, the Arduino received a JSON response from the website.
Here are the parameters that I used for the NOT WORKING GET request:
Host Address: wastedb.000webhostapp.com
Host: wastedb.000webhostapp.com
Response from Serial monitor for wastedb.000webhostapp.com (NOT WORKING):
---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="wastedb.000webhostapp.com",80,1
<--- OK
---> AT+CHTTPSSEND=113
<--- >
---> GET /wastedb/get_location.php?lat=14.640155&lon=120.974920&stat=LOW HTTP/1.1
Host: wastedb.000webhostapp.com

<--- OK
---> AT+CHTTPSSEND
<--- ERROR

Am I missing something here? Seems like the shield cannot find the Host Server I provided for my website.
EDIT: It is working now. The only solution that worked for me is to find another hosting site.

Please consider answering your own question with the information in your "edit". After a day or two, you can accept your answer as the solution.

It is working now. The only solution that worked for me is to find another hosting site.

Try just using IP address for the Host line instead. I did the same thing for POST and it works fine for me.
Example:
Host: 13.xxx.xx.xx


text:
Multiple non-blocking countdown timers?
I'm building a control system for three sump pumps using a single Arduino and a set of relays.  I have float sensors for each one, and need the Arduino to trigger the relays when the float sensors are triggered.  Sensor 1 triggers pump 1, sensor 2 triggers pump 2, etc.
Simple enough, but I also need each pump to remain on for 30 seconds after its float sensor returns to normal.  This throws me for a loop since I need the other pumps and sensors to function during this delay time.  I quickly found that the blocking delay() function is no longer feasible.
How can I trigger the relays, keep them on for 30 seconds after the sensors return to normal, but all the while still monitor and control the other sensors/relays?  Would a non-blocking timer solution work?  Would I have to delve into interrupts?

The "blink-without-delay"-pattern shows how this can be solved but with several time periods and logic this becomes complex. Some abstraction is needed. The Timemark library provides a solution. Belows is the logic for a single sensor-relay pair with a state trace to serial:
#include <Timemark.h>

const uint32_t TURN_OFF_TIMEOUT = 30000L;
Timemark turnOff(TURN_OFF_TIMEOUT);
const int sensorPin = 2;
const int relayPin = 3;

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

  pinMode(sensorPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);

  trace.start();
}

void loop()
{
  if (trace.expired()) {
    Serial.print(millis());
    Serial.print(F(":sensor="));
    Serial.print(digitalRead(sensorPin));
    Serial.print(F(", relay="));
    Serial.println(digitalRead(relayPin));
  }

  if (digitalRead(sensorPin) == LOW) {
    digitalWrite(relayPin, HIGH);
    turnOff.start();
  }
  else if (turnOff.expired()) {
    digitalWrite(relayPin, LOW);
  }
}

Expanding to three sensor-relays becomes:
#include <Timemark.h>

const uint32_t TURN_OFF_TIMEOUT = 30000L;
const int CONTROL_MAX = 3;
Timemark turnOff[CONTROL_MAX];
const int sensorPin[CONTROL_MAX] = { 2, 4, 6 };
const int relayPin[CONTROL_MAX] = { 3, 5, 7 };

void setup()
{
  for (int i = 0; i < CONTROL_MAX; i++) {
    turnOff[i].limitMillis(TURN_OFF_TIMEOUT);
    pinMode(sensorPin[i], INPUT_PULLUP);
    pinMode(relayPin[i], OUTPUT);
    digitalWrite(relayPin[i], LOW);
  }
}

void loop()
{
  for (int i = 0; i < CONTROL_MAX; i++) {
    if (digitalRead(sensorPin[i]) == LOW) {
      digitalWrite(relayPin[i], HIGH);
      turnOff[i].start();
    }
    else if (turnOff[i].expired()) {
      digitalWrite(relayPin[i], LOW);
    }
  }
}

An alternative solution is to use the Scheduler library. Below is a rewrite using template functions and a controller task per sensor-relay pair.
#include <Scheduler.h>

const uint32_t TURN_OFF_TIMEOUT = 30000L;
const uint32_t DEBOUNCE_TIMEOUT = 40L;

template<const int sensorPin, const int relayPin> void setupController()
{
  pinMode(sensorPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);
}

template<const int sensorPin, const int relayPin> void loopController()
{
  if (digitalRead(sensorPin) == LOW) {
    digitalWrite(relayPin, HIGH);
    while (digitalRead(sensorPin) == LOW) delay(DEBOUNCE_TIMEOUT);
    delay(TURN_OFF_TIMEOUT);
    digitalWrite(relayPin, LOW);
  }
  yield();
}

void setup()
{
  Scheduler.start(setupController<2,3>, loopController<2,3>);
  Scheduler.start(setupController<4,5>, loopController<4,5>);
  Scheduler.start(setupController<6,7>, loopController<6,7>);
}

void loop()
{
  yield();
}

Please note that the Scheduler requires yield() or delay() to switch between the tasks.
Cheers!

Would a non-blocking timer solution work?

Yes.  Your "timer" doesn't have to be anything more than a start time from millis() and a flag.  Then your loop just compares the start time to the current millis() value, and if it's more than the interval you wanted, do the "thing".  In code:
uint32_t startTime;
bool waiting = false;
const uint32_t PUMP_DURATION = 30000UL;

void setup()
{
  // start the "timer"
  startTime = millis();
  waiting = true;
}

void loop()
{
  if (waiting && (millis() - startTime >= PUMP_DURATION)) {
    waiting = false;
    // do something now!
    foo();
  }

The flag keeps it from checking when the pump isn't running.
If you have multiple timed things, just make another set of variables (i.e., startTime2 and waiting2).  Give 'em better names, eh?
There are also Arduino libraries that encapsulate this common design pattern.  TimeMark is one.
Here's some sample code on the Arduino forum.

30 seconds after the program starts the condition (millis() - startTime >= PUMP_DURATION) will always be true.

Yes... and?  This is a technique for (re)starting the timer and detecting the expiration.  It should be casual to the most obvious observer that this is the minimal demonstration of the technique.  Different intervals, different starts, restarting, multiple timers, etc., are left as an exercise for the reader.  -_-

Using info from every suggestion, I've so far come up with the following.  I may not need to touch this code again for years and years (or a new house owner may need to look at it should I move out), so I tried to comment it as much as possible.
I don't like that I've repeated so much code in the readFloatSensor functions, but this is where I am so far.  How can I eliminate the code duplication?  I believe I could use arrays and for loops but now I've entered another grey area for my knowledge level.
// PumpController.ino

// ----CONSTANTS
// ----Edit these if you need to change the pin layout or pump duration

#define RELAY_ON 0                     // The pump relays are active-LOW; on when LOW (0)
#define RELAY_OFF 1                    // and off when HIGH (1). These #defines just help keep track.

const int pumpRelayPin1 =  12;         // Pin numbers for the pump relays
const int pumpRelayPin2 =  11;
const int pumpRelayPin3 =  10;

const int floatSensorPin1 = 7;         // Pin numbers for the float sensors
const int floatSensorPin2 = 8;
const int floatSensorPin3 = 9;

const int pumpDuration = 500;          // Number of millisecs that the pumps run
                                       // after the float sensors no longer detect water

// ----VARIABLES

byte pumpState1 = RELAY_OFF;           // Used to record whether the pumps are on or off
byte pumpState2 = RELAY_OFF;           // (default to HIGH/OFF)
byte pumpState3 = RELAY_OFF;

unsigned long currentMillis = 0;       // Stores the value of millis() in each iteration of loop()

unsigned long pumpTimerMillis1 = 0;    // Stores the times when the float sensors were last triggered
unsigned long pumpTimerMillis2 = 0;
unsigned long pumpTimerMillis3 = 0;

// ----SETUP (Sets up the pins at startup/reset)

void setup()
{

    // Debug
    Serial.begin(9600);
    Serial.println("Starting PumpController.ino");

    // Pump relays are active-LOW. Initialize pump
    // pins HIGH so the relays are inactive at startup/reset
    digitalWrite(pumpRelayPin1, RELAY_OFF);
    digitalWrite(pumpRelayPin2, RELAY_OFF);
    digitalWrite(pumpRelayPin3, RELAY_OFF);

    // THEN set the pins as outputs
    pinMode(pumpRelayPin1, OUTPUT);
    pinMode(pumpRelayPin2, OUTPUT);
    pinMode(pumpRelayPin3, OUTPUT);

    // Set the float sensor pins as inputs and use the built-in pullup resistors
    pinMode(floatSensorPin1, INPUT_PULLUP);
    pinMode(floatSensorPin2, INPUT_PULLUP);
    pinMode(floatSensorPin3, INPUT_PULLUP);

}

// ----MAIN LOOP

void loop()
{
    // Get the current clock count

    currentMillis = millis() + pumpDuration;       // We add the countdown timer duration to
                                                   // the clock to prevent the pumps from
                                                   // running at boot time, while the clock
                                                   // counter is still below the timer value

    // Call the functions that do the work

    readFloatSensor1();             // check each float sensor and decide whether
    readFloatSensor2();             // to start the pump and countdown timer
    readFloatSensor3();
    triggerPumps();                 // Actually toggles the relay pins based on
}                                   // the data from the above functions.

// ----WORKER FUNCTIONS

void readFloatSensor1()
{
    if (digitalRead(floatSensorPin1) == LOW)   // If the float sensor is tripped (pulled low)
    {
        pumpState1 = RELAY_ON;                 // then trigger the pump relay pin
        pumpTimerMillis1 = currentMillis;      // and set the pump countdown timer to the current clock time
    }

    if (currentMillis - pumpTimerMillis1 >= pumpDuration)   // If the countdown timer has expired,
    {
        pumpState1 = RELAY_OFF;                             // then turn off the pump relay pin
        pumpTimerMillis1 = 0;                               // and reset the timer to 0 for the next trigger
    }
}

//========

void readFloatSensor2()
{
    if (digitalRead(floatSensorPin2) == LOW)   // If the float sensor is tripped (pulled low)
    {
        pumpState2 = RELAY_ON;                 // then trigger the pump relay pin
        pumpTimerMillis2 = currentMillis;      // and set the pump countdown timer to the current clock time
    }

    if (currentMillis - pumpTimerMillis2 >= pumpDuration)   // If the countdown timer has expired,
    {
        pumpState2 = RELAY_OFF;                             // then turn off the pump relay pin
        pumpTimerMillis2 = 0;                               // and reset the timer to 0 for the next trigger
    }
}

//========

void readFloatSensor3()
{
    if (digitalRead(floatSensorPin3) == LOW)   // If the float sensor is tripped (pulled low)
    {
        pumpState3 = RELAY_ON;                 // then trigger the pump relay pin
        pumpTimerMillis3 = currentMillis;      // and set the pump countdown timer to the current clock time
    }

    if (currentMillis - pumpTimerMillis3 >= pumpDuration)   // If the countdown timer has expired,
    {
        pumpState3 = RELAY_OFF;                             // then turn off the pump relay pin
        pumpTimerMillis3 = 0;                               // and reset the timer to 0 for the next trigger
    }
}

//========

void triggerPumps()
{
    // Toggle the pump relay pins on and off based on
    // pumpState from the readFloatSensor functions

    digitalWrite(pumpRelayPin1, pumpState1);
    digitalWrite(pumpRelayPin2, pumpState2);
    digitalWrite(pumpRelayPin3, pumpState3);
}

//=====END

With your regard to the concern about duplication, you can make a generic sensor function and pass it the pins for the sensor of interest - see for example how so many peripheral libraries are instantiated with pin assignments in their constructor.  Or you could put all of each pumps information in a struct, or go a step further and define a pump object you instantiate three of.  Then you put those in an array and call the appropriate methods in turn...

You might use something like this:
#define AMOUNT_OF_TIMERS 10
unsigned int timer[AMOUNT_OF_TIMERS];
unsigned int sensors[AMOUNT_OF_TIMERS];
unsigned int pumps[AMOUNT_OF_TIMERS];
void setup()
{
  sensors[0] = 1;
  sensors[1] = 2;
  sensors[2...
  ......s[9] = 12;
  pumps[0] = 13;
  pumps[1....
  ....s[9] = 22;
  for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
    PinMode(sensors[i],INPUT);
    PinMode(pumps[i],OUTPUT);
  }
}

void loop()
{
  checkPins();
  decreaseTimers();
  delay(1000);
}

void checkPins(){
  for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
    if(digitalRead(sensors[i])
    pump[i] = 30;
  }
}

void decreaseTimers(){
  for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
    if(timer[i]>0)
    timer--;
  }
}

Personally, I think, handling the timing events in an interrupt is way better. Which might also be for the sensor inputs.
It's not the neatest thing, but it will do.
Using interrupts should make it even more efficient.

You should use interrupts.
You might use unsigned chars to preserve extra RAM.
You should adjust the timers/delay. (set timer to 300, and delay to 100ms) for better result.


text:
Problem with receiving data from Arduino via HC05 sent by Java
I want to both send some sensor data via Bluetooth (HC05) and Arduino to Java and I also want to send some command data via the same Bluetooth and serial port to Arduino.
I've managed to do the first part (arduino to java) successfully with this code:
hc05SerialEx.printf("^%d,%7.3f,%d,%7.3f,%d,%7.3f\n", s1, ss1, s2, ss2, s3, ss3);

^ is the character I devised in my simple protocol and it means the starting point of data.
@ means starting point of command packet.
The problem is whenever I want to write a char packet via the same HC05 connection to arduino, it sometimes works. In fact, whenever I click the button firing the write method, I see the packet received correctly but when I click the button again or click it rapidly, it sometimes outputs garbage in arduino side.
I do have delay in my main loop in arduino side and I'm using it to control the sampling rate of sensors. I've timed arduino side's calculation time (except delay of course) and it takes about 52 milliseconds.
I suspect whenever I fire the write method while arduino is busy in main loop, the received data becomes gibberish. So here are the questions:
1- What is the cause of this problem?
2- How can I achieve the goal I mentioned?
Here is java-side code sending the command packet:
String message = String.format("@%5.3f,%5.3f,%5.3f\n", rmR1, rmR2, rmR3);
System.out.println(message);
rightHC05Port.write(message);

Here is arduino-side code receiving and mirroring the received packet in arduino's own serial port (for me to see):
void loop() {
  serialEventHC05();
  //fetching sensor data and some math operations...
  hc05SerialEx.printf("^%d,%7.3f,%d,%7.3f,%d,%7.3f\n", s1, ss1, s2, ss2, s3, ss3);
  delay(loopTime);

int numOfReceivedBytes = 0;

void serialEventHC05() {
  while (hc05Serial.available() > 0) {
    numOfReceivedBytes = hc05Serial.available();
    String s = hc05Serial.readStringUntil('\n');
    arduinoSerialEx.println(numOfReceivedBytes);
    if (s.charAt(0) == '@') {
      arduinoSerialEx.println(s);
    }
  }
}

For example, here is the string I'm sending from Java via HC05 to Arduino:
@10.000,10.000,10.000

And here is the result of Arduino's behavior caused by me sending the same packet multiple times:

Any help is appreciated.

could you please provide the complete code of your project, so I can check in detail?
(Both java code and arduino code)

Thanks for reply. It seems the problem was with SoftwareSerial since when I used the 0,1 RXTX the code works flawlessly. Even with AltSoftSerial the code still works.... I wonder what are the other undocumented limitations of SoftwareSerial...

Unfortunately I know nothing about undocumented limitations of SoftwareSerial. But I found an example that send command from java side to Arduino that may help you.link
But I also have problem when implementing such an issue. I can successfully receive data in arduino from java side, but I got stuck when receiving data from Arduino in java for a week of try. I would really appreciate that if you can share your experience or your code with me.

@Tony I've asked this very question here : http://forum.arduino.cc/index.php?topic=451673.0   The things I know as of yet is that SoftwareSerial can't handle "receive" in baudrates higher  than 9600. You can use AltSoftSerial but RXTX pin is fixed for each Arduino. The relevant code for communication between Arduino/Java side is exactly as I mentioned above in my post, nothing more.


text:
Problem with using multi-node nRF24l01+ with Arduinos
I have 3 nodes in my system. One centralNode and two sensor nodes (right and left).
Sensor nodes transmit data to the centralNode and receive from it.
centralNode may transmit to both nodes and receive from them.
I'm using an Arduino nano for central node and Uno and Mega for sensor nodes. I'm using nRF24's base module (with regulators and caps and all) but one node does not have base module (Although I've given it a descent 3.3 V and bypass caps).
Here is my problem:
1- It seems the centralNode can't detect which nodes data it is receiving. I can sometimes get it to work using different delays for sensorNodes but again, on reset it messes up the data.
How can I detect which data's reading the centralNode is receiving?
2- How can I use radio.available(??)
I've put 0, 1 , 2 and pipe addresses in ?? but it does not work (prints garbage data)
radio.available's API
Here are the codes:
centralNode:
/*
   Testing multi-node functionality of nRF24l01+
   This is centralNode code

   BOM
   1 Arduino Nano centralNode
   1 Ardiuno Uno rightSensorNode
   1 Arduino Mega leftSensorNode
   3 nRF24l01+
*/

#include <SPI.h>
#include "RF24.h"
#include <printf.h>

#define CEpin 6
#define CSpin 7

RF24 radio(CEpin, CSpin);
byte addresses [][6] = {"1Node", "2Node", "3Node"};

int rightNodeCount = 0;
int leftNodeCount = 0;
void setup() {
  Serial.begin(115200);
  Serial.println(F("This is the central node"));
  printf_begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);

  radio.openWritingPipe(addresses[0]);
  radio.openReadingPipe(1, addresses[1]);
  radio.openReadingPipe(2, addresses[2]);
  radio.startListening();
  radio.printDetails();
}

void loop() {
  if (radio.available()) {
    radio.read(&rightNodeCount, sizeof(rightNodeCount));
    radio.read(&leftNodeCount, sizeof(leftNodeCount));
  }
  //  if (radio.available(1)) {
  //    radio.read(&leftNodeCount, sizeof(leftNodeCount));
  //  }
  Serial.println("centralNode is reporting:");
  Serial.print("centralNode address : ");
  Serial.println((char *)addresses[0]);

  Serial.print("rightNode address : ");
  Serial.println((char *)addresses[1]);
  Serial.print("rightNodeCount = ");
  Serial.println(rightNodeCount);

  Serial.print("leftNode address : ");
  Serial.println((char *)addresses[2]);
  Serial.print("leftNodeCount = ");
  Serial.println(leftNodeCount);

  Serial.println("---END OF REPORT---\n\n\n\n");
  delay(500);
}

rightSensorNode:
/*
   Testing multi-node functionality of nRF24l01+
   This is rightSensorNode code

   BOM
   1 Arduino Nano centralNode
   1 Ardiuno Uno rightSensorNode
   1 Arduino Mega leftSensorNode
   3 nRF24l01+
*/

#include <SPI.h>
#include "RF24.h"
#include <printf.h>

#define CEpin 7
#define CSpin 8

RF24 radio(CEpin, CSpin);
byte addresses [][6] = {"1Node", "2Node", "3Node"};

int rightNodeCount = 0;
void setup() {
  Serial.begin(115200);
  Serial.println(F("This is the right node"));
  printf_begin();

  radio.begin();
  radio.setPALevel(RF24_PA_MAX);

  radio.openWritingPipe(addresses[1])

  radio.printDetails();

}

void loop() {
  rightNodeCount++;
  Serial.println("Sending data to centralNode");
  Serial.print("rightNode address : ");
  Serial.println((char *)addresses[1]);
  Serial.print("rightNodeCount = ");
  Serial.println(rightNodeCount);
  radio.write(&rightNodeCount, sizeof(rightNodeCount));

  Serial.println("---END OF REPORT---\n\n\n\n");
  delay(1000);
}

leftSensorNode:
/*
   Testing multi-node functionality of nRF24l01+
   This is leftSensorNode code

   BOM
   1 Arduino Nano centralNode
   1 Ardiuno Uno rightSensorNode
   1 Arduino Mega leftSensorNode
   3 nRF24l01+
*/

#include <SPI.h>
#include "RF24.h"
#include <printf.h>

#define CEpin 7
#define CSpin 8

RF24 radio(CEpin, CSpin);

byte addresses [][6] = {"1Node", "2Node", "3Node"};

int leftNodeCount = 0;
void setup() {
  Serial.begin(115200);
  Serial.println(F("This is the left node"));
  printf_begin();

  radio.begin();
  radio.setPALevel(RF24_PA_MAX);

  radio.openWritingPipe(addresses[2]);

  radio.printDetails();

}

void loop() {
  leftNodeCount++;
  Serial.println("Sending data to centralNode");
  Serial.print("leftNode address : ");
  Serial.println((char *)addresses[2]);
  Serial.print("leftNodeCount = ");
  Serial.println(leftNodeCount);
  radio.write(&leftNodeCount, sizeof(leftNodeCount));

  Serial.println("---END OF REPORT---\n\n\n\n");
  delay(1000);
}

@Andyaka 1- Good idea but I have already 32 byte limitation in packet transmission. 2- I think nRF24 does have default CRC checksum.

@Andyaka I guess TMRH's RF24 library's available() method does take this issue into account. I don't know how to use it.  http://tmrh20.github.io/RF24/classRF24.html#ace7dd139fabc16b77cb8325faa07620f

You could use the pipe addresses as the ID for a small number of nodes by using a different one for each.

Each sensor point should send its address to the central point and this is how the central point knows the source of the message. Then after the central point receives a message, after if (radio.available()) command receive the data just once (not twice) and then use another if statement to determine which sensor has sent a message (by reading the sent address) and then print.
pseudo code:
if (radio.available())
{
    radio.read(&RXbuffer, sizeof(RXbuffer));
    if(RXbuffer.address == sensor1_address)
    {
        print "this is sensor 1"
        print RXbuffer.address;
        print RXbuffer.data;
    }
    else if(RXbuffer.address == sensor2_address)
    {
        print "this is sensor 2"
        print RXbuffer.address;
        print RXbuffer.data;
    }
}

In your code (inside if (radio.available())) you are trying to receive rightNodeCount and lefteNodeCount eventhough at that time just one of them was received.
EDIT:
It seems that RF24 uses dedicated pipes to know the source of the information. The following code should work:
pseudo code:
unsigned char pipe_num;

if (radio.available(&pipe_num))
{
    radio.read(&data, sizeof(data));

    if(pipe_num == 1)
    {
        print "this is sensor 1";
        print data;
    }
    else if (pipe_num == 2)
    {
        print "this is sensor 2";
        print data;
    }
}

Thanks but in this method, you are sending an struct I guess? As I said, nRF has 32 Byte limitation in each packet so it would be wasteful use of bandwidth. I'm suspecting that this issue can be solved using radio.available(&pipeNum) method but I don't know how...http://tmrh20.github.io/RF24/classRF24.html#ace7dd139fabc16b77cb8325faa07620f

Here I have used a structure as an example (pseudo code). You can create a union data type to be able to use a structure and an array interchangeably. Or you can use just a simple array. It depends totally on your application.

I have edited my answer to use pipes. It should work. If not feel free to share and inform us of your progress.

It seems finally I got it. Actually it seems the client should not pass the desired pipeNum to the available(&pipeNum) method. You first declare a uint8_t pipeNum; then the available method fills the pipe number it is listening to into the pipeNum variable. Do you also confirm this?

@Zeta.Investigator Oops it seems that pipeNum is filled automatically. It is loaded by the number of the pipe that has received the message. So you are right. Look at the code above.


text:
Function to control servos
I'm trying to control 6 servos while writing a lean code. I think the function call isn't correctly yet and I think that the variables (pos_n, open_n, servo_1) in the for loop do not get inserted, but instead the string just gets inserted.
I think I have come a long way to not make this a bulky code.
What changes makes this function working, so that the call openValve(1) and openValve(2); work for both servos?
#include <Servo.h>
const int buttonPin = 2;
int buttonState = 0;

Servo servo_1;
const int pos_1 = 0;
const int open_1 = 105;
const int clos_1 = 10;
//Servo servo_2;
//const int pos_2 = 0;
//const int open_2 = 104;
//const int clos_2 = 9;

String servo_n, pos, pos_n, servo, openServo, open_n;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  servo_1.attach(11);
}

void loop() {
  openValve(1); // call the function
  while (true);
}

void openValve(n) {
  int n = 3;
  pos = "pos_";
  pos_n = (pos + n);
  Serial.println(pos_n);

  servo = "servo_";
  servo_n = servo + n;
  Serial.println(servo_n);

  openServo = "open_";
  open_n = openServo + n;
  Serial.println(open_n);

  // DONT USE STRING BUT THE VARIABLE CONTENTS ??
  for (pos_n = pos_n; pos_n <= open_n; pos_n += 1) {
    servo_n.write(open_n);
    delay(10);
  }
}

If you are trying to write "lean" code, then using the String object is not going to make it "lean". The second thing I noticed, was that the code doesn't compile. The first error is "error: 'n' was not declared in this scope. I don't think this is the correct syntax: "void openValve(n) {". HINT: The "n" is an issue. Please fix the syntax errors then edit your question to show us some code that does compile.

variables in the loop do not get inserted into what?

@VE7JRO could you give me a hint what I then should use instead of the String object?

@Ludo: Plain C strings, i.e. arrays of char.

I think you are totally misunderstanding, about variables and types and how using multiple servos with 1 function can work, and that this is your real question and not the thing with inserting variables (whatever you mean by that).
You are trying to put together a string and use it as variable name. That does not work. A string is only a variable/instance of type/class String. It cannot have methods of the Servo class. Also function parameters each have their own type. You cannot provide a value of a different type to this parameter. Servo.write() takes an integer value. It cannot use a String value. Thus the code inside the for loop is nonsense and won't compile. I would suggest doing some C++ tutorials from the web, that explain, how variables work in C++.
Instead you have to use multiple variables of the type Servo, one for each servo motor, that you are using. These variables are instances of the Servo class, which implements all the servo related functions (like write) Each motor gets it's own pin on the Arduino. You can put these Servo objects into an array, so that they can be indexed by an integer number. For example you can define the following variable in the global scope:
#define N_SERVOS 6
Servo servos[N_SERVOS];

This creates an array of type Servo with 6 elements. Each element is one independent servo object. (Note, that I used a define to easily change the number of attached servos when changing the code). You can reach an individual servo object by indexing it:
servos[3].write(pos);

This would write a new position to servo 4 (4 because array indices are starting from 0). Now we need to attach each Servo object to one pin of the Arduino. I would create an extra array, which contains the corresponding pin numbers - also at global scope:
int servo_pin[N_SERVOS] = {6, 7, 8, 9, 10, 11};

Here I used pins 6 to 11, but you can change them, as you like. Then in the setup() function we loop over our servo elements and corresponding pin numbers and attach the servo objects to the pins:
for(int i=0;i<N_SERVOS;i++){
    servo[i].attach(servo_pin[i]);
}

And now you can rewrite your openValve() function corresponding to that. I don't understand, what you wanted the servo to do in the for loop, so I will leave this to you. First you need to correct the syntax at the function declaration. You didn't specify the type of the parameter n. It has to look like:
void openValve(int n){

And then you shouldn't declare a new variable with the same name, so delete the line int n=3;. Then you can delete all the weird string concatiation. Then you need to fix the for loop (as I wrote I will leave that to you, since you didn't explain, what the servo should actually do there). And finally you need to rewrite the servo write line like described above:
servo[n].write(new_pos);

Note, that new_pos is just a placeholder here, for whatever values you need to write to the servo (as already said, I don't understand, what exactly you want the servo to do).

what I then should use instead of the String object?

The String class from the Arduino framework can get you into memory trouble (to be exactly memory fragmentation). You can read Majenko's blog post about Arduino Strings for further explanations.
Instead you should use char arrays aka C-Strings. You create a buffer with a fixed length, that is big enough to hold the biggest chunk of data, that you need to process. Let's say you need at max 30 characters. Every C-String is terminated by a zero ('\0'). This zero also needs space in the buffer. So the actual buffer size is 31.
char string_buffer[31];

You can even directly initialize it with a string value:
char string_buffer[31]="Teststring";

You can use sprintf() to put a formatted string into the buffer. For example a string with a number:
sprintf(string_buffer, "Number: %d", 50);

will put the string "Number: 50" to the buffer and will terminate it with a zero.

I am a bit stuck in thinking like PHP code with inserting 'variables' :p Thanks for your elaborate answer!

@Ludo If you think, that my answer is correct, you can mark is as correct. Then others can see, that this actually solved your problem.


text:
programming arduino in pure c
I'm trying to flash pure c-code to arduino Mega2560 board from linux using avr-gcc & avrdude. Compilation is done , now trying to flash using avr-dude, getting error as "avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00"
I used below command to produce hex file
avr-gcc -mmcu=atmega2560 -DF_CPU=16000000UL led.c -o led.elf

In file included from led.c:3:0:
/usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler optimizations disabled; functions from  won't work as designed" [-Wcpp]
 # warning "Compiler optimizations disabled; functions from  won't work as designed"
And then
avr-objcopy -j .text -O ihex led.elf led.hex

finally for flashing
avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

FYI: port is correct & RX pin is blinking i.e connection is perfect between computer & board

One note: -DF_CPU=1000000UL is 1MHz. I'm pretty sure Arduino Mega2560 runs on 16MHz. Anyway, you can try to use PlatformIO CLI (I'm using it on Linux machine and it works fine with several different Arduinos)

@KIIV , even @ 16Mhz , same probelm. any idea how to do without PlatformIO CLI?

Try prefixing your avrdude command with stty -F /dev/ttyACM3 hupcl &&

In file included from led.c:3:0:
  /usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler
  optimizations disabled; functions from won't work as designed"

You should start by fixing this. Simply add -Os to the compiler
command line. This means “optimize for size”, and is the standard
optimization option used with Arduinos.

avr-objcopy -j .text -O ihex led.elf led.hex

If your copy of avrdude was compiled with libelf (like the one supplied
with Ubuntu is), you don't need this: you can hand your elf file
directly to avrdude.

avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

-F tells avrdude to not verify the device signature. -V tells it
to not verify the upload. I wouldn't use any of these options unless
I had a very good reason to do so. -c arduino is wrong: it selects the
upload protocol used by optiboot (used, e.g., in the Uno). The
Mega 2560 uses a different bootloader based on the “wiring”
protocol. I would also add the -D option (disable auto erase) because
I saw the Arduino IDE using it, and because without this option I get
the error:
avrdude: erasing chip
avrdude: stk500v2_command(): command failed

In the end, the upload command ends up being something like:
avrdude -p atmega2560 -c wiring -P /dev/ttyACM3 -b 115200 -D -U led.elf

thanks ! it is working. your explanation is clear. I'm new to avr, can you please direct me where to learn all those? @Edgar Bonet

@sankar: I don't have a good reference handy for that. I learned it the hard way, by looking at how the Arduino IDE and Sudar Muthu's Makefile do it, and by reading the man page of avrdude.


text:
HC-05 Bluetooth module doesn't read data correctly from my Android phone
I have made a home automation project where am using an Arduino Uno and HC-05 Bluetooth module and an Android app. I did everything properly but when I send commands from my Android app it works sometimes and sometimes it doesn't work.
I checked these commands on the serial monitor and found that data command I recieve at serial monitor did not match the commands which I send from my Android app. For example my Android app send command "ON1" but on serial monitor it shows "OL1?". I thought it might be a problem with the HC-05 so I changed it and used a new HC-05 module, but the problem is still there.
This time I checked the commands from another Android app (Bluetooth Terminal HC-05) and there was the same problem. Sometimes it read the command correctly app and sometimes it read something else.
I am so confused weather the problem is in my hardware side or software side.I tried a lot but didn't get any solution about my problem anywhere. Can anybody help me please?
This is the Arduino code of my project:

#include <SoftwareSerial.h>
SoftwareSerial Genotronex(2, 3); //TX, RX  pins of arduino respetively
String command;
void setup() {
  Genotronex.begin(9600);
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
}

void loop() {
  while (Genotronex.available()) {
  //Check if there is an available byte
    to read
    delay(10); //Delay added to make thing stable
    char c = Genotronex.read(); //Conduct a serial read
    command += c; //build the string.
  }
  if (command.length() > 0) {
    Serial.print(command);
    if (command == "ON1") {}
    //this command will be given as an input to switch on light1
    digitalWrite(9, HIGH);
  } else if (command == "OFF1") {
    //this command will be given as an input to switch off light1 simillarly other commands work
    digitalWrite(9, LOW);
  } else if (command == "ON2") {
    digitalWrite (10, HIGH);
  } else if ( command == "OFF2") {
    digitalWrite (10, LOW);
  } else if (command == "ON3") {
    digitalWrite (11, HIGH);
  } else if (command == "OFF3") {
    digitalWrite (11, LOW);
  } else if (command == "ON4") {
    digitalWrite (12, HIGH);
  } else if (command == "OFF4") {
    digitalWrite (12, LOW);
  } else if (command == "ON5") {
    digitalWrite (13, HIGH);
  } else if (command == "OFF5") {
    digitalWrite (13, LOW);
  } else if (command == "all on") {
    //using this command you can switch on all devices
    digitalWrite (9, HIGH);
    digitalWrite (10, HIGH);
    digitalWrite (11, HIGH);
    digitalWrite (12, HIGH);
    digitalWrite (13, HIGH);
  } else if (command == "off") {
    //using this command you can switch off all devices
    digitalWrite (9, LOW);
    digitalWrite (10, LOW);
    digitalWrite (11, LOW);
    digitalWrite (12, LOW);
    digitalWrite (13, LOW);
  }
  command = "";
} //Reset the variable

Could you re-read your question please, and check it says what you want? Edit any fixes into the question, rather than posting them here. I  am confused about how the system is set up -- for example, you say the Android app sending the data didn't receive the right commands. Do you mean the Arduino didn't receive the right commands? What commands did it receive? Your method of reading until there is nothing left is dangerous, but let's find out what the problem really is before guessing solutions.

I have edit it as u mention. Thanks for ur guidness. plz let me know is that ok now ?

I suggest to have a look at this answer:
Change the baud rate of HC-05
In many case and especially when you send data from Android and receive bad data on Arduino, it's because the speed is not set correctly.
On the other side (getting data from the Arduino), it's a bit more complicated. You have to build your own "time out" system on Android as the Bluetooth library don't have such a feature.