text:
High Frequency Sine Wave Generation
I'm new to the world of Arduino and I'm working on a wireless charging project that needs a 5.7MHz sine wave. I've tried using a Due and changing the PWM and DAC, but I can't get a clean sine wave at that frequency using anything I've found online. My signal is either way too low, or too high and horribly distorted.
Any help would be appreciated. I have access to a Mega, Due, Uno, and Mini.

That's much too fast for any Arduino. Have you considered an external DDS like AD9850?

Would the http://electronics.stackexchange.com/ be a better place for this question?

To generate a square wave, you only need to update the output at a rate of two points per cycle. (Technically, when the Arduino's PWM output is configured for 50% duty cycle, that's a square wave at some frequency.)
But to generate a clean sine wave (without a lot of distortion), you need to update a lot more frequenclly than two points per cycle. Personally I wouldn't want to go much below 20 points per cycle.
Imagine the sine wave is generated by a wheel that spins at some rate. Viewed from the edge, a point on the edge of the wheel traces out a sine wave. Viewed from the axle, you see the point going around in a circle.
Now instead of spinning the wheel continuously, suppose the wheel moves in steps of 30 degrees, 12 steps for a complete turn. Instead of a continuous sine wave, you get discrete steps of 0, 0.5, 0.866, 1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5, 0, 0.5, ...   Although this sequence approximates an ideal sine wave, it's pretty coarse because the steps are so large.
Now try 15 degrees per step (24 steps per cycle). Now you get 0, 0.259, 0.5, 0.707, 0.866, 0.965, 1, ... Much smoother, although the steps are still fairly noticeable.
So there will be less phase error, the more steps there are per cycle of the signal. That's not the only source of distortion however. There is also round-off error due to the limited resolution of the Digital-to-Analog Converter (DAC). For example, the value 0.866 I mentioned above should actually be an irrational value, half the square root of 3. Since it's an irrational number, there's no way for a real DAC to get this value exactly right. DAC output step values are ideally based on powers of two (1/2, 1/4, 3/4, 1/8, 3/8, 5/8, 7/8, etc.). And furthermore a real DAC can have offset error, gain error, non-linearity, as well as uncertainty about precisely when the new programmed value is reached.
There's also frequency error when the system's highest-frequency master clock is divided by an integer. If the Arduino UNO's master clock frequency is 16MHz, and the SPI setup function setClockDivider() is used to divide the master clock by 2, that's 8MHz. Divide by 3 and you get 5.333MHz. Divide by 4, that's 4MHz. Divide by 5, that's 3.2MHz. There's no way to get a clock frequency that's between these discrete steps. For small divisors, there's a big jump between steps. So if you needed to be able to smoothly adjust the frequency, you'd need a much higher master clock frequency. And, if you needed to configure the 16MHz Arduino UNO to an SPI clock frequency of exactly 5.7MHz, that's just not possible -- setClockDivider(2) is too fast, setClockDivider(3) is too slow, and setClockDivider(2.807017543859649) isn't supported by the hardware.
If your system could write to a DAC at an update rate of 12MHz, then 12 points per cycle gives a 1MHz output, and 24 points per cycle gives a 500kHz output. Or taking it the other way round, if you need to generate a 5.7MHz output waveform, then the DAC update rate needs to be somewhere around 100MHz to get a clean, low-distortion waveform. This is probably beyond the limit of what you can directly synthesize in software using something like an Arduino or a Raspberry Pi. A 16MHz Arduino UNO could maybe synthesize a few 100kHz using software synthesis, but at 1MHz there's going to be significant distortion.
Software-controlledDirect Digital Synthesis is very sensitive to timing, so the actual DAC update would need to be implemented in an interrupt service routine, run by a periodic timer. ( See https://electronics.stackexchange.com/questions/26363/how-do-i-create-a-timer-interrupt-with-arduino )  If you just used a while loop with a delay statement, then whenever the code needs to do something else, the waveform would just freeze up. This is more of a problem if the Arduino is trying to manage several other tasks at the same time as it is synthesizing the waveform.
Hardware Direct Digital Synthesis (DDS) is possible. Same principles. There needs to be a phase accumulator, which is just a counter that keeps track of the phase angle of the "wheel" that's generating the sine wave. (The phase accumulator needs to be modulus 360 degrees or 2 pi radians, but there's no requirement to count in 1 degree steps. Better to divide the circle into 2^N slices so that 360 degress maps to the natural counter overflow value.) And there also needs to be a lookup table with the sine value for each of those steps. This lookup table only needs to cover 90 degrees of the sinewave, because the waveform is symmetrical -- the other three quadrants can be found by 2's complementing the values and indexing from the other end of the table. Or, the sine can be approximated by a polynomial calculation. More steps x more DAC resolution requires a deeper, wider lookup table. There are integrated circuits available that perform the timing-critical actions, all the software needs to do is send some initial configuration to set it up. Changing the frequency only requires configuring a new frequency divisor value into the DDS chip, so the Arduino can manage other things without causing distortion.
If the original problem only needs one fixed frequency under 200MHz, and doesn't need any adjustment to that frequency, then the hardware gets a whole lot simpler. The crystal oscillator circuits that we use to generate the timing for digital circuits, are in fact analog to begin with. You can contact a crystal vendor and request a custom AT cut crystal; google custom quartz crystal frequency for quartz crystal vendors. Construction requires a careful printed circuit board layout; the white solderless breadboard commonly used in Arduino projects just doesn't work well above 10MHz. Granted, this fixed-frequency solution doesn't involve Arduino in any way, but if it solves the problem, that's what's important.

I wonder for which purpose you would use a micro controller at all.
If you need a fixed frequency circuit, you could design just that.
If you need a generator with variable frequency, that would justify the Arduino, but in this case I would use the Arduino to control the frequency indirectly.
Ex: create a VCO and use the Arduino to adjust the voltage, through a DAC

One problem (for me) is to know how much time lines of (C) code take to execute on a (16) MHz Arduino. This and the coding you use would set an upper limit to the sinewave frequency you could synthesise at a given quality.
You probably can't beat assembly language when time is tight.


text:
Issue with usbserial for arduino clone
I have attached photo of the clone Uno board recently acquired, and I am working on a Mac OS X 10.7.5
I have sourced the solution from
http://javacolors.blogspot.com/2014/08/dccduino-usb-drivers-ch340-ch341-chipset.html
Which suggests to install 340/341CH drivers and run a sudo code. When I plug in the Uno board, the Arduino IDE still does not show under port selection, the "dev.tty.usbserial"
and as such I cannot contact or upload any command to the Uno board. Been trying for a whole day.. please help if you know a possible solution
This is the board:

I bought the board from this site:
http://www.aliexpress.com/item/UNO-KIT-Upgraded-version-of-the-For-Starter-Kit-the-RFID-learn-Suite-Stepper-Motor-ULN2003/1207142899.html
screenshot from the IDE does now show any usbserial

It looks like the device node for a ch340 on a Mac should be of the form tty.wchusbserial### - at least that is what the screenshot is showing at http://www.codenuke.net/2015/01/nodemcu-install-ch340-usb-to-serial-for-yosemite.html

You will need to allow the use of unverified drivers for this version of the Arduino. Unlike the genuine Arduino this board needs the ch340 and ch341 drivers and because they are not verified you will need to run the following command in order for them to work:
sudo nvram boot-args="kext-dev-mode=1"
I just got a handful of these clones (so cheap) and once I installed the drivers and then set the nvram kernel extensions to dev mode all was OK.

This may be better asked on http://apple.stackexchange.com
At the terminal run ioreg -p IOUSB then plug in the Arduino and see what changed.
On my Mac the setting is serial.port=/dev/tty.usbmodemfa131

A genuine UNO with an ATmega16u2 implement USB CDC will have a device node of that form, yes.  But that is not what the poster is connecting.  They are using something based on a ch340 chip instead.

@ChrisStratton and if the OP posted the ouyput of ioreg -p IOUSB we would know which chip.

source: Stack Exchange

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

sort: votes


text:
What is the rise time of an output pin of atmega328 changing its state?
I've already searched a lot and didn't found the answer. Also, I don't have an o'scope. Anyone can help me?

Should be in the ns range. Also depends on the load, obviously.

Do you have the load impedance and capacitance, and the input thresholds?

I just measured on my Uno with a pocket scope and a cheap 1× probe. I got something around 40 ns, but it was at the bandwidth limit of this basic scope, and I believe this probe has quite high capacitive load. A faster scope and a better probe would probably give a shorter rise time.
Update: I tried again with a better scope (an Hameg HM-305) and a decent 10× probe, the observed rise time was somewhere in the 10 ns range, which is about the rise time of the internal amplifier of the scope. Then the higher boundary would be about 10 ns.

Last time I measured on a circuit (it was an i2c network master and with a 2560), it was about 0.3us, so that gives you a high value for that. Also, I believe it cannot be faster than one/half of a CPU cycle which takes: 1/(16E6)=62.5ns/2 = 31.25ns, so here's the lower boundary.
And there you got a possible range.
Then the rise time will definitely depend on the configuration of the circuit. It might be less or more depending on pull ups, capacitance attached at the pin out exit. It might also depend on the configuration of the pin (PWM? Internal Pull-up?…)
Finally, I believe there should some nominal values given in the datasheet.
Edit: Useful knowledge from the datasheet, but there's no definitive answer for any pin:
P311: 29.4.3 External Clock Drive
| Symbol | Parameter | Min | Max   | Min | Max   | Min | Max   |
| ------ | --------- | --- | ----- | --- | ---   | --- | ----- |
| tCLCH  | Rise Time |     | 2.0µs |     | 1.6µs |     | 0.5µs |

P313: 29.6 SPI Timing Characteristics
| Description    | Mode      | Min | Typ   | Max    |
| -------------- | --------- | --- | ----- | ------ |
| Rise/Fall time | Master    |     | 3.6ns |        |
| Rise/Fall time | Slave     |     |       | 1600ns |

P315: 29.7 Two-wire Serial Interface Characteristics
| Symbol | Parameter                      | Condition | Min        | Max   |
| ------ | ------------------------------ | --------- | ---------- | ----- |
| tr     | Rise Time for both SDA and SCL |           | 20 + 0.1Cb | 300ns |

HTH

The cycle time is 62.5 ns, and of course the rise time can be shorter than that.

The rise time of a GPIO on all embedded systems is not connected to the CPU speed.

I got 8 ns on both the rising and falling edges. If using the PORT instruction to set and clear bits instead of the much slower digitalWrite() instruction, the highest frequency I got by toggling a pin high and low was 2.666 Mhz. This is slowed down by the excessive time the arduino takes to pass execution back to the top of the Loop() marker. The duty cycle of the pulse output at 2.666 Mhz was somewhere in the region of 15%.

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:
HC-05 and cheap Nano clone not powering on
I have a HC-05 module which works absolutely fine with an Arduino Uno. Because I need to reduce the size of it, I tried using an Arduino Nano.
After correctly wiring it up to the Nano, sometimes the LED doesn`t turn on, or sometimes it does not appear in the devices listing of my smartphone. It also resets randomly the Arduino. I have tested it and it fully works without any problems with the Uno.
I think it is a power issue, but not from my computer or any other computer because I tried on all my computers.

Are you powering it from 3.3V or 5V?

the regulator on the nano may not be able to supply enough current for the HC-05. See if you can find a part number on the regulator and look up its specs.

@ChadG If it's running from the 3.3v pin then it may even be using the internal 3.3v regulator of the CH340G, in which case you'd be lucky to get a few tens of mA from it...

Please provide a schematic and the type of HC-05 module you have. The HC-05 itself runs in 3.3V, but most modules, that you can buy, add an extra voltage regulator for 5V, so that you can power it directly from the Arduino.

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


text:
Why a servo doesn`t move to angles properly
I've got to do a project which uses a servo to drive a turntable.
How much I adjusted the angle, the servo seemed to shift every time it spinned. For instance, the 0 degree angle was getting a bit bigger. I think it is caused by the imprecise PWM control of the Arduino or the bad translation using, I think, the map() function.

Could you fix this issue in code, or the servo doesn't work properly. I observed that every servo (that I've tried) creates a buzzing noice for angles bigger than 170 degrees.
By the way, my code is:

#include

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

#define pos0 0
#define pos1 23
#define pos2 48
#define pos3 164

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);
}

void loop() {
  for (pos = pos0; pos  pos0; pos -= 1) {
    myservo.write(pos);
    delay(30);
  }
  Serial.print("pos: ");
  Serial.println(pos);
  delay(5000);
}

Edit: Should I try with a more powerful Arduino, like the Mega, which I think will be the perfect option having more GPIO than the UNO.

Every servo is different, they can have varying specifications:

Angular speed
Rotation range
Stall Torque
Size
Gear material/quality

Servos will vary based on brand; in addition each servo is going to have some individual variance.  So one has to characterize the servo, and discover what the proper control values are. Once the control values are established these are used to initialize the library so angular control will be accurate.

For instance, the 0 degree angle was getting a bit bigger

I have found that errors in repeatability, like this, are usually found in the mechanism the servo is driving, especially the connection between the servo and the driven mechanisms. Check the connection for slop, see if everything is tightened properly.

I observed that every servo (that I've tried) creates a buzzing noice for angles bigger than 170 degrees.

The typical maximum range of a servo is 160-190 degrees of rotation. The noise you are hearing is the servo trying to drive the motor to set the angle, but it is stalled as it can't turn that far.

Should I try with a more powerful Arduino, like the Mega, which I think will be the perfect option having more GPIO than the UNO.

IIRC the servo library can control 12 servos with a basic Arduino, and 48 with the MEGA. This difference is more than just pin count, the MEGA has 4x the hardware timers of the 328p; 12 x 4 = 48
If you need more features you can move to the MEGA, i.e. you need more PWM channels, and the servo library reduces PWM pins from 6 to 4 on the 328p. Another example could needing more timers.
Read the Arduino Servo examples for more information on usage of the servo library and control of servos, etc.

Try to use myservo.writeMicroseconds(x) function. For standard servos the value of parameter x is between 1000 to 2000 for 0 degree to 180 degree rotation. But you know all servos are not manufactured perfectly. Thats why servos can response to 700 to 2300. At first you have to verify the minimum and maximum responding values then use it. You can use map() for easy coding.

Not all Servos are perfectly built. One can get rid of the library itself; there is a way to make a servo turn by manually writing out the code.
for(x=0; x<150; x=x+1)
{
  digitalWrite(Servomotor, HIGH);
  delayMicroseconds(1500);          //Edit this delay to adjust the position
  digitalWrite(Servomotor, LOW);
  delayMicroseconds(18550);         //Don't touch this delay
}

By trying out different delays for the first delayMicroseconds(), you can test out which delay you need for what position.
To make your code more clean, you could safe different angles in another void function, and when you need them just type out the name
Have a nice day ;)

IIRC the servo library uses timers to generate the pulses so that you can still do other things while using the servo; with your method you will have to eventually re-implement the servo library yourself.

An inexpensive servo tester, e.g....
https://www.amazon.com/DIYmall-Digital-Consistency-Controler-Checker/dp/B012LZKTDO/ref=sr_1_12?crid=3BLBBVDUPTN53&keywords=servo+tester&qid=1644245707&sprefix=servo+tester%2Caps%2C93&sr=8-12
...is useful for determining the exact mechanical limits of a specific servo quickly and easily.  If the servo will only physically move 170 degrees and the connected mechanism requires 180 degrees, a different servo is needed.
It should be possible to use an oscilloscope connected to the servo control lead to determine a) what the tester output duty cycle is at specific angular positions, and b) what the actual Arduino output duty cycle is when running a program.
Use the servo tester to assure that the range of motion of your servo is adequate to correctly operate the mechanism.
Note the tester output at desired positions.
Adjust your program to produce the duty cycle(s) necessary to replicate the tester output at the desired positions.


text:
Looking to blink entire led strip
I am fairly new to FASTLED programming and am looking to make my entire LED strip blink at the same time. Similar to the Example Sketch "Blink" however all 30 of my LEDS. I might just be having a temporary mind derp right now but I cant figure it out.

please post the sketch that you are using .... include a clear description of observed behavior

look at the Cylon example code .... it shows you how to address the LEDs .... extrapolate to multiple LEDs  ......... the Blink example blinks the first LED .... think about what you would have to change in the code to blink the second LED ..... how would you blink the first and second LED at the same time?

FastLED has a function called fill_solid() which will change the color of an indicated range of LEDs in a strip.
From https://github.com/FastLED/FastLED/wiki/Controlling-leds#set-rgb-color

use new 'fill_solid', telling it to fill just one led. (v2) Note that
  this is a pretty silly way to set one pixel, but it lets us illustrate
  the existence of fill_solid, a new convenience function the library
  provides.
fill_solid( &(leds[i]), 1 /*number of leds*/, CRGB( 255, 68, 221) )

For your case, you want to change the color of all LEDS, so you would call:
fill_solid(leds, NUM_OF_LEDS, CRGB::Red);

To turn them back off, you would change the color to CRGB::Black


text:
I do not know what the board is. Can someone please help

It says that it is a pro micro, but I have searched the arduino website and i cannot find something that looks like this or is called this.

Sparkfun created a minimal version of the Arduino micro board and called it the pro micro. https://www.sparkfun.com/products/12640 Perhaps you can use it as a normal arduino micro board (with a few missing pins) or install the Sparkfun boards. With this cheap board, you don't know what kind of bootloader it has.

If the chip is an ATmega 32u4 I would guess a cheap clone of the Sparkfun Pro Micro

@Jot It plugged it in and it is reading it as an Arduino Leonardo

That is the same. The arduino micro is a minimal Leonardo and the pro micro is a minimal micro. I don't know if they all share the same bootloader. Use a picture of the pinmapping https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro  and you can use it as a leonardo as well. The leds can also be used (with limitations). The 3.3v/8MHz version is slower than the 16MHz Leonardo. Since "j1" is not soldered in your photo, I assume that you have a 3.3v/8MHz version.

Oops, I see a 16MHz x-tal. Maybe you should solder jumper "j1" to make it run at 5v.

I got it, just it is now not showing up on my com ports now but it was before

An Arduino compatible board don't have to look like one in Arduino web site.
There are many clones and custom boards are available.
Since it says pro micro, choose Pro micro from bard option and try uploading some code.

By default there is no Pro Micro support in the IDE. It needs to be installed.

As far as i can remember, Arduino IDE has by default support for pro micro. Even it doesn't, Leonardo has default support on arduino IDE. Which can also be choosed to program this board for testing.


text:
Doubt in choosing the right DC motor?
Take this motor as an example - https://www.robotshop.com/en/12v-100rpm-583-oz-in-brushed-dc-motor.html
it has torque of 42kg.cm
I know all the calculation to find the payload of dc motor from here - https://www.quora.com/How-do-I-calculate-how-much-weight-can-DC-motor-carry
My main concern is the output power. Power formula is:-
power = voltage x Stall Current
      = 12 x 2A = 24W
But the specification says that the power is 5W. Which value should I use in my calculation?

Do the same calculation with the rated values. What do you get?

then the value is too low, I want to make a mobile robot whose weight is 5kg. I want to use 2 dc motor for this project.

The stall current tells that the driver should be able to give that current or else the driver will get damaged. The 24W is only a calculation. I assume that the maximum mechanical power will be a few watts less. The 5W power is probably an average for normal operation. Perhaps the motor and gears are not designed to operate a long time near the stall current. Perhaps the motor gets too hot if used for a long time with more than 5W.

With a current rating of 0.68 A at 12 V you get the normal power requirement of 8.6 W for a 7Kg.cm torque.
If, for any reason, you stall the motor, your driver must be capable to output 2.2 A or 26.5 W to avoid a permanent damage.


text:
How to upload sensor data on pubnub IOT with JSON Format?
I am trying to send MPU9250 sensor data to Pubnub IOT platform using node mcu, but not able to do it since the sensor data is not in JSON format. I know about publishing string but don't know about variable.
About Pubnub Library - https://github.com/pubnub/arduino
This is the part which I need help in:-
IMU.readSensor();

PubNonSubClient *pclient = PubNub.publish(pubchannel, IMU.getAccelX_mss());

But above line has error so how do i send imu sensor data to pubnub? All connections are right and sensor is working since I tested it.

Have you tried enabling the debug option? To enable debug logging to the Arduino console, add #define PUBNUB_DEBUG before #include <PubNub.h>

format it in json before sending it out, for small payloads, hand-building JSON isn't that hard.

This is the format which helped me to upload the data successfully. I didn't knew what JSON format was and got stuck. In case if someone stumbles on a similar problem.
char buf[5] = {};

sprintf(buf, "\"%d\"", IMU.getAccelX_mss());

PubNonSubClient *pclient = PubNub.publish(pubchannel, buf);


text:
How to do a HTTPS post on ESP8266
I am trying to do a HTTPS post on ESP8266 as shown in Postman below

But I keep getting: 'HTTP/1.1 401 Unauthorized'.
Can someone please help me with how to build up the headers correctly in the HTTPS POST? And maybe also give a link to some documentation? I cant seem to find any...
My code is:
const char* host = "api.dgs.com";
const int httpsPort = 443;
String url = "/ccs-int/v1/applicationdatalogging/1.0";
String msg = "";

WiFiClientSecure client;

Serial.print("connecting to : '");
Serial.print(host);
Serial.println("'");
Serial.printf("Using fingerprint '%s'\n", fingerprint);
client.setFingerprint(fingerprint);

client.connect(host, httpsPort);

Serial.print("requesting URL: '");
Serial.print(url);
Serial.println("'");

client.print(String("POST ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n" +
    "Content-Type: application/json" +
    "Authorization: Bearer " + authorization_code + "\r\n" +
    "Content-Length: " + msg.length() + "\r\n" +
    "\r\n" +
    msg + "\r\n");

Serial.println("request sent");
unsigned long timeout = millis();
while (client.available() == 0) {
    if (millis() - timeout > 5000) {
        Serial.println(">>> Client Timeout !");
        client.stop();
        return;
    }
}

Unauthorized says it all. I can't see anything for authorization in your code

And the documentation you've asked https://httpstatuses.com/401

If you're getting to the point that you get a 401 back, HTTPS is succeeding. 'Unauthorized' should mean that there's an issue with your authorization code. Do you have access to a computer that can run curl? If you do, try doing this post from that. It would be something like curl -X POST --header "Authorization: Bearer AUTHCODE" --header "Content-Length: 0" https://api.dgs.com/ccs-int/v1/applicationdatalogging/1.0 replacing AUTHCODE with your authorization code. This may help you debug what's going on with it.

I moved the autorization part up earlier in the 'client.print', which fixed the problem. However now I get a 411 error (Content-length has to be specified). Any idea what might be my new problem? I have specified the content length and I have also tried different values with no success.

@T.Krebs...can you share the full code example, It's a bit difficult to figure out which portion is setup and which is loop.


text:
ESP8266 upload data to google cloud platform
I am trying to upload information to my appspot created with Google App Engine. I am able to do it when I in my browser type:
http://myname.appspot.com/query?city=Copenhagen&temp=20&id=website
But I cannot get it to work on the ESP8266. Here is my code:
const char* MY_URL = "http://myname.appspot.com";

void uploadHTTP() {
    // Define the WiFi Client
    WiFiClient client;
    // Set the http Port
    const int httpPort = 80;

    // Make sure we can connect
    if (!client.connect(MY_URL, httpPort)) {
        return;
    }
    else {
        Serial.println("Connected to MY_URL");
    }

    String url = "/query?city=Copenhagen&temp=20&id=ESP8266";

    // Post to appspot
    if (client.connect(MY_URL, httpPort)) {

        // Sent HTTP POST Request
        client.println("POST " + url + " HTTP/1.1");
        Serial.println("POST " + url + " HTTP/1.1");
        client.println("Host: " + String(MY_URL));
        Serial.println("Host: " + String(MY_URL));
        client.println("User-Agent: Arduino/1.0");
        Serial.println("User-Agent: Arduino/1.0");
        client.print("Content-Length: ");
        Serial.print("Content-Length: ");
        client.println(0);
        Serial.println(0);
        client.println("Content-Type: application/x-www-form-urlencoded");
        Serial.println("Content-Type: application/x-www-form-urlencoded");
        client.println("Connection: close");
        Serial.println("Connection: close");
        }
    //Done
    Serial.println("");
    Serial.println("my HTTP done");
    Serial.println("");
}

Are you programming the ESP8266 directly, or using it connected to an Arduino?

Your biggest problem is that you are trying to use a website URL as a FQDN. That's not going to work.
When you connect to a remote machine you connect to the name (myname.appspot.com) which gets translated into an IP address for you to open a connection to.
When you use a web browser it parses the URL to extract the protocol (http) and the FQDN (myname.appspot.com) and uses the protocol to determine the port (and what language to speak) to connect to, then look up the IP address from the FQDN.
You need to drop the http:// from your FQDN which is causing it to break (there is no host called http://myname.appspot.com).  The fact that you are connecting to port 80 and speaking the HTTP language implies that you are using HTTP.
To put it into more layman's terms: if you "need to call Fred to talk about going to the pub" you first look up fred's number in the phone book then call that number. Then only once he has answered do you talk about going to the pub. What you don't do is try and find the number to call by looking in the phone book under "talk about going to the pub with Fred". It won't be there.
If you are programming your ESP8266 directly you should consider using the much simpler bundled ESP8266HTTPClient.h library.

Thank you for the quick answer and the explanation - I did not know that! However I tried to change it to "myname.appspot.com" but it did not work?
I have also been trying to get it to work with ESP8266HTTPClient.h library but I could not get that to work either...

Is my 'Content-type' correct? Here is my code for the ESP8266HTTPClient.h:
['code']
(HTTPClient http;)
http.begin("myname.appspot.com");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpCode = http.POST("/query?city=Copenhagen&temp=20&id=ESP8266"); Sorry for the bad layout - I am new to this forum and cant get the comment to work....

You have no content, so content type is meaningless. You should really be doing a GET request not a POST request if there is no content to POST.

I have a content? I am setting the 'city' to 'Copenhagen', 'temp' to '20' and 'id' to 'ESP8266'

No, that's not content. Content goes in the body. You have URL parameters. URL parameters go on the end of the URL. You have no body, and zero content length, and your parameters are on the end of the URL. That is not "content".

Thank you! I now changed to GET and it is working


text:
ESP8266 - 12F High consumption in led blink (with pictures)
My esp is consuming 180mA with a led blink. The same consumption happens when I put it in WIFI_STA mode with the WiFi.mode(WIFI_STA); function.
What should I do to reduce consumption? Used AMS1117 CI as tension regulator.
My code:
void setup() {
  pinMode(2, OUTPUT); // pin number 2 is on board blue led
}

void loop() {
  digitalWrite(2, LOW); // blue led highlight with LOW level
  delay(100);
  digitalWrite(2, HIGH);
  delay(100);
}

Why all this consumption?

if it's in WIFI_STA  and not doing anything network-related, it should eventually go into modem sleep and draw a lot less.

The SDK library of the ESP8266 remembers on flash memory the mode, SSID and password of the last WiFi network it connected. At start or by enabling STA mode it tries to connect to that network. The SDK library is always part of the compiled sketch for the esp8266.
The esp8266 WiFi library has some functions to control this:

WiFi.setAutoConnect(false)
WiFi.disconnect(true);
WiFi.persistent(false)


text:
ESP8266WebServer how to parse Json payload in post request that is bigger than the ram
I need to post a big json to the nodemcu server which would be bigger than the ram's size
I am using esp8266werserver and arduinojson libraries. I know how to use arduinojson to parse huge json response from other servers by parsing the response as a stream using response.getstream() . I can reuse a small static buffer in the stack to parse the whole json in a loop which performs really well.
But when I use nodemcu as a server, I can't find any similar method in the ESP8266WebServer to allow me to process json response as a stream. All I can only do is to read the string file in server.arg("plain") which may crash as the string may get bigger than the ram.
Is there a quick and dirty workaround? I look at the source in parsing.cpp there is a readBytesWithTimeout method that seems to be responsible to actually parsing the response stream. I am wondering if I may override this function to do what I need but I don't know how.
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WebServer/src/Parsing.cpp

The ESP8266WebServer library can process only a HTML-Form POST request of application/x-www-form-urlencoded or mulripart/ content type.
You could sent the JSON as multipart 'upload' to save it to file, but it would require to build the multipart format of the POST body.
If you want to process POST with application/json content type, you could make a simple web server implemented with WiFiServer.

oh I didn't think about simply using WiFiserver. Seems like a nice workaround. Thanks so much for the suggestion.

But by the way what I will be missing if I use WiFiserver instead of the Esp8266webserver? Is the Esp8266webserver better optimised for the esp8266? Would like to know more about the trade off.

it depends how much of ESP8266WebServer functionality you use. ESP8266WebServer only wraps WiFiServer with HTTP and HTML-Form processing

Then seems like I should really look into WiFiserver instead thanks so much for your help Juraj


text:
Is there an open source compiler for Arduino Sketch codes?
I am working on a web app to program some nodeMCU devices that were flashed with the arduinoOTA library.
http://esp8266.github.io/Arduino/versions/2.0.0/doc/ota_updates/ota_updates.html
I tried the example and the OTA upload of the binary file compiled from Arduino IDE works.
Let's say my web app will allow user to code in Sketch, is there any open source server side or client side compiler that can compile the Sketch code into the bin file?

turn on verbose console output in Arduino IDE and you will see all the executed commands to compile and link. the builder is external and it is Open Source

see for example Sloeber, the Arduino Eclipse plugin, how it uses Arduino toolchain and core packages without Arduino IDE

@Juraj Please write this as an answer or give URL for a tutorial, etc. that already exists on the web, if you know of one.

The AVC GCC is used and is open source  https://gcc.gnu.org/

Just have a look here https://github.com/arduino/Arduino/wiki/Build-Process to understand the process.
In fact Arduino code is not "C or C++" at 100%. You can't compile directy as some informations are missing.
This is why when you "compile" with the IDE, it copies the files in a temp folder, add some lines at beginning of theses files and then call the basic and well known avr-gcc.
If you have a dedicated server you just have to search for the avr-gcc package according to the OS.
Eg, for Debian: https://packages.debian.org/stretch/gcc-avr
Then or you send directly the code avr-gcc is waitng for, or you apply on the code the same changes the IDE is doing before sending the code to GCC.
Hope this help

Try PlatformIO: https://platformio.org
Opensource and cross platform.

Great answer to some other question :)

Arduino IDE runs external tools to create the hex or bin file. First the ino files of a project are processed by arduino builder to cpp file. Then the arduino builder invokes the toolchain of the MCU architecture - compiler and linker. For example AVR tools for 328p or 2560; ARM toolchain from SAMD; xtensa tools for Espressif chips.
New is Arduino CLI, which focuses on using Arduino with command line.
Tha Arduino builder, Arduino CLI and esp8266 Arduino core are Open Source. Extensa tools and Espressif SDK are not open source, but are free.


text:
What exactly does the Arduino preprocessor do?
Arduino claims to be a "language," not just an "application framework," and Arduino files have their own extension, .ino.  The language is obviously C++, but not quite.  My understanding is that Arduino has some sort of special preprocessor which converts .ino files into C++ files before compiling them.
My question is: What exactly does this preprocessor do?  What exactly are the differences between "Arduino language" and real C++?  The Arduino documentation seems to gloss over this.
In particular, I've had weird things happen when I try to define my own classes in my sketch.  It's hard to figure out what I'm doing wrong when the language doesn't seem to be specified anywhere.

The Arduino ino to cpp converter doesn't touch your cpp and h files. It only converts the ino file to a cpp file as Majenko described in his answer.

I've had weird things happen - can you give an example?

@NickGammon It was a while ago, so I don't remember the exact error message.  But I suspect it was caused by the automatically generated prototypes.  (i. e. a function takes a struct or class as an argument, and the prototype is inserted before the declaration of that struct or class)

It does four things, basically:

It adds #include <Arduino.h> to the top of your file, which gives you access to all the classes, functions and defined variables/macros of the API.
It joins together all the INO files together into a single monolithic file (in the same order as the tabs in the window),
It matches #include entries with libraries and adds the files in those libraries to the list of files to compile, and
It scans through the ino file(s) looking for functions and adds prototypes to them to the top of your file.

It's the latter that can cause problems. Historically it never got the prototypes in the right place, and if you ever passed a structure of your own devising to a function it would break horribly.  It does a better job these days, but it's still not 100% perfect.
It basically means that you don't have to adhere to the "You must define it before you use it" rule of C/C++.  Which of course makes for lazy programmers.

and it concatenates all ino files of the project to one file, starting with the ino file with same name as the project folder a then the rest of ino files in alphabet order (it is the same order as tabs in IDE)

Ah yes, that too.

See my answer: How the IDE organizes things
I'm not sure if link-only answers which refer to a Stack Exchange link are OK. In case they are not, here is the first part of that answer:
This is how the IDE organizes your "sketch":

The main .ino file is the one of the same name as the folder it is in. So, for foobar.ino in foobar folder - the main file is foobar.ino.
Any other .ino files in that folder are concatenated together, in alphabetic order, at the end of the main file (regardless of where the main file is, alphabetically).
This concatenated file becomes a .cpp file (eg. foobar.cpp) - it is placed in a temporary compilation folder.
The preprocessor "helpfully" generates function prototypes for functions it finds in that file.
The main file is scanned for #include <libraryname> directives. This triggers the IDE to also copy all relevant files from each (mentioned) library into the temporary folder, and generate instructions to compile them.
Any .c, .cpp or .asm files in the sketch folder are added to the build process as separate compilation units (that is, they are compiled in the usual way as separate files)
Any .h files are also copied into the temporary compilation folder, so they can be referred to by your .c or .cpp files.
The compiler adds into the build process standard files (like main.cpp)
The build process then compiles all the above files into object files.
If the compilation phase succeeds they are linked together along with the AVR standard libraries (eg. giving you strcpy etc.)

A side-effect of all this is that you can consider the main sketch (the .ino files) to be C++ to all intents and purposes. The function prototype generation however can lead to obscure error messages if you are not careful.

Thanks!  Where did you learn all of this information?

Observation of what files get copied into the temporary directory, and looking at the commands being executed when "verbose" compiling is turned on.

Where are the temp files located? Can you configure Arduino IDE to keep them to make it easy to look at them?

If you turn on "verbose compiling" you can see where the temporary files are.


text:
Arduino UNO + CC3000 Wifi Shield, Reading webpage data
I'm new so I might be making a stupid mistake, but I'm declaring:
char dollars;
at the begging of file, afterwards I'm reading a data from a web page, printing it to my serial. That part work well. The data returned from the web page is a number, 55 for instance.
The number get's printed correctly to the serial. But when I try to save the complete number it changes. for instance, when I get 0 from the server. The printed result is 10.
here is the important part of my code:
unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    while (www.available()) {
      char c = www.read();
      Serial.print(c);
      dollars = www.read();
      lastRead = millis();
    }
  }

  www.close();
  Serial.println(dollars);

while the www.read is repeating each of the returned characters it works fine Serial.print(c); but when I save it to the dollars char var, it get garbled up into something different. What am I doing wrong?
I'm planning to show that number from the web page onto my 4 digit screen at the end.

Webpages usually return data in text format with new line characters at the end.
In case of 55 you would get "55\r\n" or [53, 53, 13, 10] in bytes.
You need to parse the characters, like Serial.parseInt() does.
You are also only sending every second byte back to the serial monitor and only saving the last byte from the other every second byte.
After you read a byte with Serial.read() you can't read the same byte again, you get the next one.
In case of 55 you would send back "5\r" to the serial monitor and only store "\n" or 10 into dollars.
In case of 0 you would send back "0\n" to the serial monitor and store some unknown value into dollars, because you read more bytes that was sent.


text:
Streaming IMU data over BLE using Sparkfun 6 DOF and Blend Micro
I am trying to use the RedBear Blend Micro to send data captured by my SparkFun 6 DOF IMU.  I am completely lost, and if anyone has any documentation I can read, or even tutorials that work for this specific IMU, I would highly appreciate it.


text:
Adding HC-SR04 ultrasonic sensor to the board
I would like to add three more HC-SR04 sensor
Currently I have combined the Arduino UNO R3 with the AR 293d(refer to below graph), and pluged in one HC-SR04 sensor to the SRO4 hole at the left top corner. So I need to find the holes for t3 more sensor.

I have done some research already , for the connection , found more document
HC-SR04 Arduino
Vcc     +5V
Trig    GPIO
Echo    GPIO
GND     GND

The questions are ,
1) From the above graph, is that mean I can only add two more sensor to the board , since there are only 2 more 5V, GND , 12 , 13 pins (at the top and bottom holes)
2) How can I connect them separately ? That means, what I need to connect from sensor to the board?
3) If I need other board eg. breadboard to connect them, How should I connect sensor to breadboard and how can I connect it with the main board(AR 293d)?
Thanks a lot for helping. Any answer is useful for me

Welcome to Arduino SE! Can you please clarify how this question is different than the linked question in the comment above? Thanks!


text:
redefining delay and delaymicros as personal function
Is it possible to redefine delay and delaymicros function with #define ?
I want to use timer2 interrupt instead of these.
Something like this:
#define delay(unisgned long ms) countMicros(uint16_t top, uint16_t storageVar)

setup(){}

loop(){
 delay();// function countMicros is called instead.
 }
void countMicros(uint16_t top, uint16_t storageVar){
//...}

Can you tell us why ? Have you heard about the XY-problem ? http://xyproblem.info/

@Jot Now I have !
I want to use timer interrupt for several time-sensitive calculations. One is to know when exactly to turn on TRIAC on 50 Hz AC system.
Second is time after turning it off.
The problem is with LiquidCrystal library which I have for LCD. It uses delay, so by initializing ISR with 1uS counter nothing works.

An ISR works also when a delay is busy. You should avoid Timer0, because the Arduino uses it. You can use Timer1 and Timer2 of an Atmega328p (Arduino Uno). If you need more timers, then use the Atmega32u4 (Arduino Leonardo / Micro). You are looking in the wrong direction for the wrong solution. I think this is indeed a XY-problem.

With timer2 set it does not work with liquidcrystal functions however, when the library with functions are commented out everything works fine. So I concluded that delay in LCD library is the cause.
The problem is following: red led flashes fast and LCD is frozen, when timer2 ISR is set.

The LiquidCrystal library does not use Timer2 and has nothing to do with it. Is your ram memory almost full ?

Is using Timer2 the real problem ? You have made a new question for that. That is okay. Let's continue there: https://arduino.stackexchange.com/questions/44889/lcd-library-and-timer2-ctc-interrupt-not-working-together

Not exactly like that. You will have to manage the different sets of
parameters, i.e. convert the incoming ms into the top and
storageVar that would be appropriate for calling countMicros().
Maybe something like this:
#define delay(ms) mydelay(ms)

void mydelay(unisgned long ms) {
    uint16_t top = some expression;
    uint16_t storageVar = another expression;
    countMicros(top, storageVar);
}

where both expressions are a function of ms.
If the expressions are really simple, you could even put the whole thing
inside a single macro, as in
#define delay(ms) countMicros(some expression, another expression)

Do parameters in original function have to match ones in a custom one, as you have shown in the beginning of your post ?
#define delay(ms) mydelay(ms)
I assume that in this case parameters passed in original function will get passed into custom function.  If that is so, what happens in case of your last example ?
#define delay(ms) countMicros(some expression, another expression)

@flowian: You should realize that the preprocessor only does textual substitution. If you #define delay(ms) countMicros((ms)*2, (ms)-4) and then you call delay(7), then the compiler will just see countMicros((7)*2, (7)-4).


text:
Data from RC522 to firebase real time database
#include<ESP8266WiFi.h>
#include<SPI.h>
#include "MFRC522.h"
#define RST_PIN D3
#define SS_PIN D4
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
}

void loop() {
  if ( !mfrc522.PICC_IsNewCardPresent() ) {
    delay(50);
    return;
  }

  if ( !mfrc522.PICC_ReadCardSerial() ) {
    delay(50);
    return;
  }

  Serial.print(F("Card UID: "));
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println();
}

void dump_byte_array(byte *buffer, byte bufferSize) {
  for ( byte i = 0; i< bufferSize; i++ ) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

I am able to get the unique ID of the RFID tag & card. But now the problem is that how can I send the unique ID from ESP8266 to the firebase realtime database.
The hexadecimal values that are generated are they unique? or they are something else? Because in some youtube videos I saw people using only numbers as a unique ID from RFID to distinguish between 2 cards or tags.
The wifi connection and firebase auth all are set peoperly ony the unique id number is the problem.

The "UID" of the card is supposed to be unique. Most RFID chips also have blocks of readable/writable space, but some systems do only use the UID from the chip as the complete identifier.
It may be that you come across RFID chips that have utilized random bytes as the UID, in which case there is a chance of duplication. Depending on the number of possible cards to be used in your system, this may or may not be a big worry for you. If it is a big worry, you may want to use the actual memory on the RFID chips to store your user's ID data.
Regarding HEX versus numbers -- Hexadecimal is just one way to represent numbers.
Your code:
Serial.print(buffer[i], HEX);

tells the print command to take the byte at buffer[i] and print its value in Hexadecimal format. You could replace HEX by DEC to see the base-10 (decimal) value instead. The actual bits underneath would be the same -- it's just one way to display/represent the underlying number.
One byte (8 bits) of data can be represented in decimal as the numbers 0 through 255. The same byte can be represented in Hexadecimal as 0x00 through 0xFF. ('0x' is one way to denote that what follows are hexadecimal values.) Each 'digit' in hex represents 4 bits of data (0-15 in decimal), so 2 hex digits can represent 16^2 values (256 decimal), hence 0-255 as the 1-byte range of decimal values.
(That explanation assumes un-signed types.)

After converting HEX to DEC in the code I get this value 75 201 248 102. So can I transfer this value to the database and consider as a unique value? My project is for education purpose I have 9 cards and 2 tags I only want this 10 to have unique identity that's it.

You can store the value as integer, HEX, DEC, string -- the UID of the card can generally be considered unique and all you are doing is comparing if the UID that is read from the card exists in the database or not. Yes, you can consider the UID in Decimal representation to be unique for your case.

Thanks for the idea to get value in decimal it will be very for me to play with RFID now. Now I have to do is append the values in a variable and push the data to database. Thanks for giving your valuable time.


text:
Get the uploaded code from arduino by using arduino IDE 1.0.6
Recently bought a arduino device which already have program,
it is model AR-293D and I have already connect it with my PC(windows 7) through usb
when I open the IDE , It seems there is no function that read the uploaded program?
And after searching a while , like some beginner tutorial , it only tell you how to upload the program but not how to get the uploadded program
http://www.forefront.io/a/beginners-guide-to-arduino
So, I wonder how to get the code? Thanks a lot for helping, I worried erase the uploadded program so I need to take caution about this

The problem is the uploaded code will be machine code and while you might be able to disassemble it there won't be a way to get the C++ code back out of it.

Yes that's right it will erase the old code and replace it, so you just keep your C++ code on the PC.

You can use khazama to read the chip, and then write it to a hex file. There are tons of other ways, but that's the one I've used previously, that was pretty easy.

You can download the hex machine code from the Arduino by using an ISP programmer, like this one:

A command like this could be used to read the flash memory and save it into myfile.hex:
avrdude -c avrisp -p m328p -U flash:r:myfile.hex:i

However be warned that this file will look like this:
:100000000C945C000C946E000C946E000C946E00CA
:100010000C946E000C946E000C946E000C946E00A8
:100020000C946E000C946E000C946E000C946E0098
:100030000C946E000C946E000C946E000C946E0088
:100040000C9488000C946E000C946E000C946E005E
:100050000C946E000C946E000C946E000C946E0068
:100060000C946E000C946E00000000080002010069
:100070000003040700000000000000000102040863
:100080001020408001020408102001020408102002
:10009000040404040404040402020202020203032E
:1000A0000303030300000000250028002B000000CC
:1000B0000000240027002A0011241FBECFEFD8E043
:1000C000DEBFCDBF21E0A0E0B1E001C01D92A930AC
:1000D000B207E1F70E94F1010C9401020C940000B8

As you can see, you haven't really got "the program" back.

As Mikael Patel points out, you can at least turn it into assembler by doing this:
avr-objdump -j .sec1 -d -m avr5 myfile.hex

However the output is still not C code like you see in the IDE:
  d4:   0e 94 f1 01     call    0x3e2   ;  0x3e2
  d8:   0c 94 01 02     jmp 0x402   ;  0x402
  dc:   0c 94 00 00     jmp 0   ;  0x0
  e0:   61 e0           ldi r22, 0x01   ; 1
  e2:   8d e0           ldi r24, 0x0D   ; 13
  e4:   0c 94 81 01     jmp 0x302   ;  0x302
  e8:   61 e0           ldi r22, 0x01   ; 1
  ea:   8d e0           ldi r24, 0x0D   ; 13
  ec:   0e 94 ba 01     call    0x374   ;  0x374
  f0:   68 ee           ldi r22, 0xE8   ; 232
  f2:   73 e0           ldi r23, 0x03   ; 3
  f4:   80 e0           ldi r24, 0x00   ; 0
  f6:   90 e0           ldi r25, 0x00   ; 0
  f8:   0e 94 f5 00     call    0x1ea   ;  0x1ea
  fc:   60 e0           ldi r22, 0x00   ; 0
  fe:   8d e0           ldi r24, 0x0D   ; 13
 100:   0e 94 ba 01     call    0x374   ;  0x374
 104:   68 ee           ldi r22, 0xE8   ; 232
 106:   73 e0           ldi r23, 0x03   ; 3
 108:   80 e0           ldi r24, 0x00   ; 0
 10a:   90 e0           ldi r25, 0x00   ; 0
 10c:   0c 94 f5 00     jmp 0x1ea   ;  0x1ea

Unless you are an assembler expert, making sense of that would be pretty hard, and the time taken to do it would be better spent simply rewriting the code from scratch.

The magical command for converting from hex to asm seems to be "avr-objdump -j .sec1 -d -m avr5 myfile.hex". Found this in http://www.avrfreaks.net/comment/158180#forum-topic-top

Amended to incorporate your comment, thanks!

But there are decompilers that can convert machine code to C, but I assume those do not work with this kind of assembler?

I don't see why they wouldn't work with this type, however there are limitations to what they can achieve. For one thing, they can't possibly know the variable names (apart from processor registers, I suppose) so your variables would become v1, v2, etc. The C compiler possibly inlines some function calls, so you might see functions turned into inline code. The compiler moves things around (or omits them, even) for efficiency, so that would be hard to get back. Anyway, re-reading the question, it doesn't seem like some very important stuff is there.

For a more complete backup of everything on the ATmega328p chip, avrdude -v -p m328p -c avrisp -U flash:r:m328p_flash.hex:i -U efuse:r:m328p_efuse.hex:h -U hfuse:r:m328p_hfuse.hex:h -U lfuse:r:m328p_lfuse.hex:h -U lock:r:m328p_lock.hex:h -U eeprom:r:m328p_eeprom.hex:i captures EEPROM data and fuse settings, as well as the executable flash object code. Restore backup by replacing all of the :r: with :w:.


text:
Print connection password typed by user on NodeMCU Lua ESP8266 ESP-12E
I want to make a WiFi Access point created with the ESP8266. Let's say that the SSID is 'net_work' and the password is '12345678'.
When a client tries to connect with a wrong password, I want to print that wrong password in the serial console. But nowhere in the docu I can find an event listener or something to do this... The only thing i can find in the docu is how to start the AP and wait for a successfull connection.

You can't print the password because you never know the password. The AP is never sent the password.

You can't.
The password does not exist.
In short:

The password is used to create a key
The key is used to encrypt the connection
If both ends agree on the encryption then it's "connected" and packets can travel back and forth.

There is no password for you to print, only the fact that encryption didn't agree.
It actuality it's more complex than that, but that's the rough outline of how it works.

Thanks for your answer. Maybe a question that does not belong in this topic, but do you know a book or a search term where to learn such deeper understanding about networks, connections and protocols?

https://www.ietf.org/standards/rfcs/


text:
Pointer memory allocation in function
I would like to know how Arduino allocate memory for pointers in function arguments.
For instance. I have this code that use 192 bytes (Arduino IDE compiler:
Global variables use 192 bytes (9%) of dynamic memory).
char alph [] = {'a', 'b', 'c','\0'}; // 4 bytes
int numb [] = {1, 2, 3, 4}; // 8 bytes
float flo [] = {1.1, 2.2, 3.3}; // 12 bytes

void fn(){
  Serial.println(alph);
  Serial.println(numb[1]);
  Serial.println(flo[1]);
}

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

void loop(){}

The following code is the same of above, but I'm using pointer to variables in arguments, that use 234 bytes (Arduino IDE compiller: Global variables use 234 bytes (11%) of dynamic memory).
char alph [] = {'a', 'b', 'c','\0'}; // 4 bytes
int numb [] = {1, 2, 3, 4}; // 8 bytes
float flo [] = {1.1, 2.2, 3.3}; // 12 bytes

void fn(char * _alph, int * _numb, float * _flo){
  Serial.println(_alph);
  Serial.println(_numb[1]);
  Serial.println(_flo[1]);
}

void setup()
  Serial.begin(9600);
  fn(alph, numb, flo);
}

void loop(){}

There is a difference of 42 bytes to use three pointers. Why? A char pointer is 1 byte, a int pointer is 2 bytes and a float pointer is 4 byte length. Do the difference must be 7 bytes?

I make it 224 not 234. However, you're forgetting one simple thing: The compiler is clever.

By the way: all pointers are 2 bytes, regardless of what they point to.

They use 192 and 224 bytes ram. I can reduce the 224 to 192 for the second sketch by adding the keyword 'const' in front of all three array declarations. The 'const' keyword give the compiler more possibilities to do clever things.

But if add 'const' to arrays I can't change it dynamically

If you want to find out what happens you’d have to look at the assembly code the compiler produces.

A char pointer is 1 byte, a int pointer is 2 bytes and a float pointer is 4 byte length. - No, a char is 1 byte, an int is 2 bytes, and a float is 4 bytes. However a pointer is always 2 bytes.

When you ask: "why?". The cheapest answer is: "why not?".
The compiler can do clever optimizations as @Majenko wrote. That is what this is about.
Even for such a small sketch, the compiler has many optimization methods to choose from. Changing a single line or adding a variable can make the compiler to choose other optimizations. It is therefor impossible to link the increased number of bytes to those extra pointers.
Sometimes the compiler can decide to keep a variable in a register instead of storing it in a memory location. Sometimes the compiler understands that a variable has a constant value and is used only once, then the compiler might not even use dynamic ram for it.
The used dynamic ram by the sketch is even more trivial, since Arduino sets the compiler to use the minimal size for the code.
Optimizing a sketch is best done with a large sketch. Your small sketch uses the Serial library, and that is the main part of the compiled code. Your own functions and pointers is just some code on the side.
For beginners, the compiler optimizations can be magical Abracadabra. However, using arrays will prevent the compiler to do extreme optimizations. There might even be a logical explanation for the number of increased bytes if the assembly code is studied as @Gerben wrote.


text:
local libraries and include dependencies
I'm using PlatformIO in Atom for Arduino programming. I get dependencies error when build. This is my reproduction sample code:
/lib/mylib/mylib.h
#ifndef MYLIB_H
#define MYLIB_H

#include <Arduino.h>

void fn();

#endif

/lib/mylib/mylib.cpp
#include <mylib.h>

void fn()
{
  Serial.println("fn1");
}

/lib/mylib/myclim.h
#ifndef MYCLIM_H
#define MYCLIM_H

#include <Arduino.h>
#include <DHT.h>

void fnclim();

#endif

/lib/mylib/myclim.cpp
#include <myclim.h>

void fnclim()
{
  Serial.println("fnclim");
}

/src/main.cpp
#include <Arduino.h>
#include <mylib.h>
#include <myclim.h>

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}

The above code is compiled without errors. But, if I remove the line #include <myclim.h> in main.cpp, I get the follow error:

Processing pro16MHzatmega328 (platform: atmelavr; board: pro16MHzatmega328; framework: arduino)
--------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/pro16MHzatmega328.html
PLATFORM: Atmel AVR > Arduino Pro or Pro Mini ATmega328 (5V, 16 MHz)
HARDWARE: ATMEGA328P 16MHz 2KB RAM (30KB Flash)
Library Dependency Finder -> http://bit.ly/configure-pio-ldf

LDF MODES: FINDER(chain) COMPATIBILITY(soft)
Collected 17 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <mylib>
Compiling .pioenvs/pro16MHzatmega328/src/main.cpp.o
Compiling .pioenvs/pro16MHzatmega328/lib2cc/mylib/myclim.cpp.o
In file included from lib/mylib/myclim.cpp:1:0:
lib/mylib/myclim.h:5:17: fatal error: DHT.h: No such file or directory

*************************************************************
* Looking for DHT.h dependency? Check our library registry!
*
* CLI  > platformio lib search "header:DHT.h"
* Web  > https://platformio.org/lib/search?query=header:DHT.h
*
*************************************************************

compilation terminated.
*** [.pioenvs/pro16MHzatmega328/lib2cc/mylib/myclim.cpp.o] Error 1

I'd like to know why it is happen. Some times, I need include myclim.h in main.cpp, but sometimes I don't. Why is it happens if DHT dependency is ok?
Thank you!

it depends if the dht library header is first processed in the sketch or in library?

It looks that when dht library is included in sketch, compiling is ok. But, when dht library is only in mylib, a dependency error occur. The path for dht library is the same. I don't know why builder not find dht library when it is included only in mylib.

did you try it in Arduino IDE?

Yes, I tried, @Juraj . I do not have error, including or not myclim.h in main.cpp. But, I note in Arduino IDE output that DHT.h is always compiled, even if myclim.h is not included in main.cpp.


text:
How to increase the range to IR transistor receiver
I have a Arduino project which controls LED using IR Receiver and Transistor.The circuits works fine,But the problem is the LED is Blinking Brightly  only for short range basically between 5-8 cm,but when i used my TV remote it works at for very long range(above 1 m).I have tried giving high voltage to IR Transistor,but no use.
Please help to solve this problem!!
Thanks in Advance!

Are you just using digitalWrite() to turn the LED on and off, or are you modulating it with a carrier frequency?

What is it you are trying to achieve? It might be better to use a IR receiver instead of an IR phototransitor.

@Majenko iam using just digitalWrite() to turn LED ON and OFF

Please add your circuit and your code to the question

@chrisl iam just using the arduino to turn IR Transistor on and off

An IR transistor does not (is not build to) emit IR light, it detects it. So why are you turning it on and off? For emitting IR light you should use IR LEDs

The reason your TV remote can work over a much longer distance is because it doesn't just turn an LED on and off.
Instead it turns the LED on and off really fast, and then turns that "turning on and off" on and off as well.
In technical terms: the light is modulated with a carrier frequency.  Just the same as a radio signal is modulated with a carrier frequency, you can do the same with light.
The receiver then samples the light falling on it over time and passes it through a band pass filter to remove any frequencies in the changes of light intensity that aren't within the frequency of the carrier signal.  What is left is then low-pass filtered to recover the overall "on-off" signal that is being transmitted.
Much of that is hard to do using an Arduino, so an IR receiver is used which integrates all the filtering and recovery of the signal. These are sold with different frequency sensitivities, and if you then turn an IR LED on and off at that stated frequency it will be able to "see" it far more efficiently than just having a light on or off.
There is a library for the Arduino that can handle the modulating of the LED at the right frequency for your chosen IR receiver.

thanks for the help


text:
Is there a way to read real-time port selection on Arduino IDE when using third-party toolchain and uploading program?
I am using a third-party program to build the binary file and upload it under Arduino IDE's GUI, meaning I am not using the built-in avr-gcc nor avrdude for building and uploading. As there is a on-board DAP chip, uploading binary file is done by copy&paste the binary file into the flash memory recognized as a removable storage by the OS.
However, this make reading user's current port selection very difficult because the IDE is written in Java, but the thrid-party program I am using is in C++.
Knowing which port the user has currently selected is very important to me, as sometimes I need to program multiple boards at the same time and monitor their received data on the serial port.
If someone can point me into the right direction or link me to the previously-solved similar question , it will be much appreciated!
PS: I am working under Ubuntu&Windows10 OS and using latest Arduino IDE.

I don't understand. What port does the user select if the upload target is the drive?

Hi Juraj, it doesn't matter which port the user select, the uploading program will always simply copy & paste the binary into the drive whose path already specified in the source code of the uploading program, this differs from arduino who uses serial port to upload binary instead of DAP(Debug Access Port).

yes, and then what is the question?

Hi Juraj, its ok I ve found the solution, thx :)

After someone from Github gave me a link, I think I ve found the way to read the real-time port selection even using third party uploading program.
The key is command line argument in the "Platform.txt" file located under "arduino15" folder. If you have the same issue as mine, try look up this link, where you will find loads of useful information:
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification
PS: rmb, after you change the command lines in the txt file, always close and restart your arduino IDE before those changes you made take effect.

Please be a bit more specific, so that future users can learn more from your answer, and also because links might die somewhere in the future.

thanks for the reminder, but I think my case is kinda rare so not many will run into the same problem as ours unless their dev board uses DAP chip for uploading as well.

anyway, this key is to get the serial port through command lines arguments written in "Platform.txt" (you can find it in your C drive).


text:
Bad Data : Arduino Mega & NodeMCU Serial Communication
Currently I am working on an Arduino project. The project required to establish communication between Arduino Mega and NodeMCU ESP8266. Here are some details about the project:

NodeMCU Rx Pin is connected to Arduino Mega Pin 14 (Tx3), while NodeMCU Tx Pin is connected to Arduino Mega Pin 15 (Rx3), Jumper Wires is used to connect NodeMCU and Arduino Mega
Both Arduino Mega and NodeMCU are using baud rate 115200

Code for NodeMCU ESP8266 (Send The Data to Arduino Mega):
void loop(){
       esp.println("0000");

       esp.flush();
}

Code for Arduino Mega (Receive Data) :
 if(Serial3.available()){

  data = Serial3.readStringUntil('\n');

  Serial3.flush();

  Serial.println(data);

}

The result :

The intented and expected result is "0000", however, the result shown in serial monitor is not accurate. Anyone could advise?

Is that a 3.3V Mega  or did you use a level shifter? You know that the 5V of a normal Mega can fry your ESP? And the other thing is: Why do you flush Serial3  but have not written to it? That is a hight baud rate, so event the quality of the wiring could be a problem.

did you connect grounds?

the spaces are \r. maybe the buffer overflows while you print the received string so you get incomplete 0000. try a small delay in esp8266

@PeterPaulKiefer, the esp8266 has no problems with 5 V serial communication on UART, SPI, I2C and similar. And I run Mega to ESP-12F UART with 500000 baud on jumper wires

@Juray I uv your comment questioning the grounds because I think that is the best idea and the most probable. -- As long as the arduino does not try to write to the ESP you're sure. But I had to bury one of the little esps I once owned after I tried to establish a 5V power connection ;-) So it may work or fail, but if it fails the part sails on the styx. The baud rate is not the problem. Want I meant is if you use a higher baud rate, lower parasitic capacitance can distort the communication. So if the connection are of bad quality, that could be a problem. But the gnd idea is still my favorit.

@PeterPaulKiefer, 5 V to Vcc is a different topic

Sir mane ardunio mega 2560 my programing k hy jo k different sensor k value lake display karty hy aur sir ab my us value ko server jo k thingspeak hy aus p bajna chahta ho sir aus k leye mane esp8266 node-mcu use kar raha ho to sir ab my chahta ho k arduino value lake node-mcu ko send kary aur node mcu phr server p sir in k leye serial communication chahyae between two arduino sir is k leye koi refrence or any help


text:
Flash size in boards.txt ATmega 328p 32u4
The ATmega328p and ATmega32u4 microcontroller have 32Kb of flash memory (as datasheet). Bootloader for each microcontroleer has different size (about 512 byte for 328p and 4kb for 32u4).
Why in boards.txt the "upload.maximum_size" parameters is 32256 for 328p and 28672 for 32u4?
I we have to consider bootloader size, the "upload.maximum_size" parameter for 328p must be about 31.5k and not 32k. And, if we do not have to consider bootloader size, as the default boards.txt configuration (above) for 328p, the "upload.maximum_size" parameter for 32u4 must be 32k not 28k. Correct?
Thank you

1KB is 1024 bytes, not 1000 bytes.
Therefore 32kb = 32768 bytes.
32768-512=32256, which is exactly the value used for upload.maximum_size for the 328p.
4kb=4096 bytes. 32768-4096=28672 which is the value for the 32u4.

You are right @Gerben. Excuse me for my attention fault. I found this thread about 32u4 flash size. Is it possible the available flash (with bootloader) be less then ~28k because USB stack (as questioned in thread)?

Yes, you are correct. The 32u4 bootloader has to implement the USB stack, which the 328p only has to do UART, which is a lot simpler.


text:
7-Segment, 3-digit display not displaying correctly
I have written the code that should work, but for some reason the numbers do not display correctly. When I choose to display 3 times the same number it works correctly (so pin connections are correct) but when trying to display different numbers on each digit things get messy. Can anyone see what is wrong with the code? I don't seem to find it. thanks!
Working when 3 digits are the same:

Not working with different numbers (should be 3, 2, 1:

And the code:
int a = 2;               //Defining segments corresponding to the pins
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;

void setup(void) {      //Setting Pins as output
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(A2, OUTPUT);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(g, OUTPUT);
}

void WriteNum(int PositionN, int Number) {
  int Position;
  int NumberSegments[10][7] = {{a,b,c,d,e,g},     //Defining segments for forming numbers
                          {b,c},
                          {a,b,d,e,g},
                          {a,b,c,d,g},
                          {b,c,f,d},
                          {a,c,d,f,g},
                          {a,c,d,e,f,g},
                          {a,b,c},
                          {a,b,c,d,e,f,g},
                          {a,b,c,d,f,g}};
  digitalWrite(A0, HIGH);                       //Setting begin conditions (All segments low and no digits turned on)
  digitalWrite(A1, HIGH);
  digitalWrite(A2, HIGH);
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(4, LOW);
  digitalWrite(5, LOW);
  digitalWrite(6, LOW);
  digitalWrite(7, LOW);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);

  switch (PositionN) {                        //Deciding which digit to turn on
    case 1:
      Position = A0;
      break;
    case 2:
      Position = A1;
      break;
    case 3:
      Position = A2;
      break;
  }
  digitalWrite(Position, LOW);
  for (int i = 0; i < sizeof(NumberSegments[Number]); i++){       //For each segment in number to display
        digitalWrite(NumberSegments[Number][i], HIGH);            //Light that segment
        }
  delay(5);
}

void loop(void) {
  WriteNum(1,2);
  WriteNum(2,2);
  WriteNum(3,2);
}

sizeof(NumberSegments[Number] is 14 (as an int is two bytes; 2*7=14). The least you should do is use sizeof(NumberSegments[0]/sizeof(NumberSegments[0][0]. Since you declare the sub-arrays to be of 7 integers, {b,c}, will actually be interpreted as {b,c,0,0,0,0,0},. So your code is also setting pin 0 to HIGH. Not sure if this have anything to do with your problem.

That was indeed the problem thanks! Because the sizeof() = 14, it will continue reading the next item in the list and light those segments as well. Setting pin 0 high did not appear to cause any problems but I filled the remaining spaces in the list with copies of an already lit segment anyway. I still wonder why this did not cause problems when the three digits were the same?

I have three recommendations for you. @Gerben was correct as to your problem, but doing the following three steps will improve the speed of your code:

Change your definition for NumberSegments to be [10][8], and put the number of active segments as the first number of each array:
 ...[10][8] = {{6,a,b,c,d,e,g},     // ...
               {2,b,c},
               {5,a,b,d,e,g}, // etcetera

Change your for loop as follows:
for (int i = 1; i <= NumberSegments[Number][0]; i++) { // ...
   digitalWrite(NumberSegments[Number][i], HIGH); // ...
}

This will only turn on the minimum number of segments required. Note the loop now starts at 1, and uses <= instead of <.
Put the keyword static in front of NumberSegments:
static int NumberSegments[10][8] = {{ // ...

This last one is a language nicety. Every time the function WriteNum is called, the poor thing has to re-create the (large) NumberSegments array - and it’s the same every time! The keyword static means “only create this variable once”. Next time into the function, it’ll already be available: no processing required!
You might also consider moving int position; below NumberSegments, since it’s convention to put static variables first in a function.
You can also use the keyword const on NumberSegments, since its values never change:
static const int NumberSegments[10][8] = {{ // ...

Thanks John! Much appreciated. Looks way more efficient indeed. I believe I'm getting the hang of it


text:
Wiring for Arduino Mega and multiple MPU 6050/Gy 521?
I have an Arduino Mega 2560 that I need to connect 4 MPU 6050/Gy 521's to.
I found some resources on the Mega and Uno, however I'm having trouble piecing them together.
This resource gives great detail for connecting a single MPU to a mega.
http://dummyscodes.blogspot.com/2014/07/mpu6050-gy-521-breakout-arduino-mega.html
This resource gives a trick for connecting multiple to an UNO.
https://playground.arduino.cc/Main/MPU-6050
My problem is that the wiring for the Uno and Mega are different. The resource I have for the UNO describes using the MPU AD0 (output) connecting it to different output pins for each MPU. The resource talking about the MEGA doesn't even use the AD0, and uses INT but I'm not sure if I can use the same concept.
Plus, I still don't actually understand how to connect/what other pins to use for the other 4.
I'm pretty new to Arduino, definitely new to anything with wiring.
Please help! I'm really confused about using multiple together, and about how to properly wire them.

MPU-6050 uses I2C for comm's, yes?
Connect all the SCLs in parallel to the Mega with a 4.7K, or 3.3K, pullup resistor. Same for the SDAs. I2C is D20, D21 (or D21, D22) on the Mega.
The MPU-6050 has an A0 pin to select from one of two addresses, let's call them Add0 and Add1 for simplicilty.
Connect each MPU-6050 A0 pin to a unique Mega pin.  When none are being addressed, have each Mega output high. When one MPU-6050 is to be accessed, take that device's A0 pin low and communicate with it using Add0. The other's will be looking for communications at Add1 and thus will not respond.
If the MPU6050 is a 3.3V device, then you should also remove the pullup resistor network package on the Mega that pulls SCL/SDA to 5V.  There are 2 pullups in a very little 8-pin package, the other 2 are not used. Connect the 3.3K or 4.7K pullup resistors discussed above to 3.3V.

This is the part, RN1, on the Mega R3 board. It may not be marked as such on the board. Remove it, or cut the traces next to the pad legs, one on the left side (connects to pin 3), one on the top (connects to pin 2).

I didn't know about the pullup resistor package on the Mega's I2C bus. Is that meant to be removable/replaceable, or do you have to snap it off destructively?

I wouldn't snap it off, but it would come without too much difficulty with a soldering iron.

CrossRoads' answer using the address selection pin on your MPU modules is excellent. It does tie up a GPIO line for each MPU you want to address however.
(If you are using a Mega 2560 this might not be an issue since they have tons of GPIO lines.)
You could also get a I2C addressing multiplexer. Adafruit and Sparkfun both offer them Example: https://www.adafruit.com/product/2717?gclid=EAIaIQobChMItYnah7zB4QIVAoTICh1JlAk3EAQYASABEgK7hvD_BwE
That one will multiplex up to 8 I2C devices with the same address, and doesn't require any additional pins. You send a single I2C command to it to select one of your 8 devices.
I don't know if anybody makes an I2C multiplexer that also does voltage conversion. Seems like that would be handy.


text:
Problems with passing objects in tree structure
I'm new to C++ and arduino. I want to build an object Tree, but it did not behave like I expected. Here is the code:
TreeNode.h
class TreeNode {

  public:
    TreeNode(String inputNodeName);
    TreeNode *children[];
    TreeNode &getChild(int index);
    int getLength();
    String nodeName;
    void addChild(TreeNode &node);
    String getName();

  private:
    int childLength;
};

TreeNode.cpp
  TreeNode::TreeNode(String inputNodeName) {
    nodeName = inputNodeName;
    childLength = 0;
  }

  TreeNode &TreeNode::getChild(int index) {
    return *children[index];
  }

  int TreeNode::getLength() {
    return childLength;
  }

  String TreeNode::getName(){
    return nodeName.c_str();
  }

  void TreeNode::addChild(TreeNode &node) {
    children[childLength] = &node;
    childLength++;
  }

I'm initialising it in the setup function:
void setup() {
    Serial.begin(9600);

    TreeNode mainTree("main");
    TreeNode firstChild("first child");
    TreeNode secondChild("second child");
    TreeNode subChild("subschild");

    Serial.println(mainTree.getName()); //prints "main"
    Serial.println(firstChild.getName()); //prints "first child";
    Serial.println(secondChild.getName()); //prints second child";

    mainTree.addChild(firstChild);
    mainTree.addChild(secondChild);
    Serial.println(mainTree.getName()); // prints an empty string
    Serial.println(secondChild.getName()); //prints second child"

    secondChild.addChild(subChild);
    Serial.println(secondChild.getName()); //prints an empty string
}

So my problem is, when I'm adding a child to a node, the node name is empty, or strange characters will be displayed.
I think I misunderstood passing an object by reference. Can anybody explain what I did wrong?

Arrays do not expand like in Java or Basic. You need to allocate a specific number of entries, or use a linked list or C++ STL wrapper object like vector.

Here we go - I have just drafted a blog entry on C arrays: https://majenko.co.uk/blog/arrays-pointers-what-c

TreeNode *children[];

That declares an array of pointers however it also requires that you assign memory to it. I never see you allocate that memory.
If you only expect a small amount of children then you can use that upper bound as a static allocation:
#define MAX_CHILDREN 10

//...
TreeNode *children[MAX_CHILDREN];

Otherwise use a vector instead:
std::vector<TreeNode *> children;


text:
ISR definition causing boot loop?
I am trying to compile and upload code to an Arduino Uno from the command-line, however I seem to be experiencing an odd issue.
When I compile this code:
#include <avr/interrupt.h>
#include <stdbool.h>

ISR(TIMER0_OVF_vect) {
}

int main() {
  while (true);
}

With these commands:
$ avr-gcc -mmcu=atmega328p -DF_CPU=16000000 -std=c17 -O3 -Wall -Wextra -c boot_loop.c -o boot_loop.o
$ avr-gcc boot_loop.o boot_loop.elf
$ avr-objcopy -j .text -j .data -O ihex boot_loop.elf boot_loop.hex
$ avrdude -p atmega328p -c arduino -P /dev/ttyUSB0 -U flash:w:boot_loop.hex

My Arduino ends up in a boot loop, flashing the LED 3 times every second or so (similarly to when you press the reset button or the device powers up).
I've tried it without an empty ISR and also with different interrupt vectors (e.g. TIMER0_COMPA_vect) but to no avail. Completely removing the ISR definition stops the boot loop.

just add a nop

Your problem is not with your code. It's with how you're linking your elf file.
You haven't specified the chip to link for.
$ avr-gcc -mmcu=atmega328p boot_loop.o -o boot_loop.elf

That's the ticket! Can't believe I missed that, thanks!

You know why I spotted it so readily? Because I did the exact same thing once :)


text:
Using two sensors with delay concurrently
I want to use an ultra-sonic sensor and the led concurrently. I want the led to blink every 0.2 seconds and the ultra-sonic to measure distance without regard to the blinking.
The problem is I have the following code for blinking:

digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(200);

which makes the ultra-sonic sensor to be delayed as well, but I want it to keep measuring distance.
Any tips?

look up blink without delay. Which will tell you how to do things concurrently.

The NewPing library does not use pulseIn. With the blink-without-delay ( https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay ) for the led and the NewPing (it is in the library manager) for the ultra-sonic sensor, you can do many other things as well, but don't use delay in the sketch anymore.

There is a non-blocking library that works similar to delay() Virtual Delay. This sketch turns your Uno's built-in LED ON for 1 second, then OFF for 200ms, repeatedly.
#include <Arduino.h>
#include "avdweb_VirtualDelay.h"

VirtualDelay delay1, delay2;

void setup(){

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

}

void loop(){

  // This sequence has a deadlock.
  if(delay1.elapsed()){
    digitalWrite(LED_BUILTIN, LOW);
    delay2.start(200);
  }

  if(delay2.elapsed()){
    digitalWrite(LED_BUILTIN, HIGH);
    delay1.start(1000);
  }

  // This breaks the deadlock. You can start with any
  // delay object you want e.g. delay2.start(0);
  DO_ONCE(delay1.start(0));

  // Your code here.

}

The library's author has an excellent tutorial on their website: avdweb Virtual Delay timer for Arduino.

You could try to use millis(). It is a timer that measures how long your program has been running. With some math, you could use millis to let your LED blink without delaying the ultra sonic sensor.


text:
Arduino Convert std:string to String
I'm working on BLE project with espressif library. And It returns me founded BLE device.
std::string getManufacturerData();
std::string getName();
int         getRSSI();
BLEScan*    getScan();

When I want to print device name to serial port
BLEAdvertisedDevice founded_dev;
founded_dev=foundDevices.getDevice(0);
Serial.println("Name -> " + founded_dev.getName());

It gives me error like this
no matching function for call to 'HardwareSerial::println(std::__cxx11::basic_string<char>)'

So how can i convert to std:string to String in Arduino?

Don't. Instead just access the underlying C string:
Serial.print(F("Name -> "));
Serial.println(founded_dev.getName().c_str());

That works for getName() but not some of the other methods such as BLEAdvertisedDevice::getAddress() or BLEAdvertisedDevice::getServiceUUID()

@TomAuger That's because they don't return a string.  The first returns a BLEAddress, the second a BLEUUID. Custom types that will need special handling.

For the UUID you can use getServiceUUID().toString().c_str(), For the address you can use: getAddress().toString().c_str().


text:
ESP8266 01 wifi module
I have a weird problem  , as I.m trying to connect to esp8266 01 with Arduino Uno when i try sending commands from the serial it doesn't work but if i send it in a function in the setup phase it works
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2, 3);

void setup()
{
Serial.begin(9600);
esp8266.begin(9600);
delay(1000);
//sendData("AT", 1000);
//sendData("AT+CWMODE=1", 1000);
}

void loop() {
// put your main code here, to run repeatedly:
if(esp8266.available()) // check if the esp is sending a message
  {
      while(esp8266.available())
      {
          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          Serial.write(c);
      }
  }
  if(Serial.available())
  {
    delay(1000);
    String command="";
    while(Serial.available()) // read the command character by character
    {
        command+=(char)Serial.read();
    }
    esp8266.println(command); // send the read character to the esp8266
  }
}

void sendData(String command, const int timeout) {
 String response = "";
 esp8266.println(command);
 long int time = millis();
 while ((time + timeout) > millis())
   while (esp8266.available()) {
     char c  = esp8266.read();
     response += c;
    }
 Serial.println(response);
}

try to print back to Serial the command variable

i did , the command was fine just AT command it responds with busy p... then error

do you have CR/LF in Serial Monitor? then replace println(command) with print(command)

sorry , i don't know about CR/LF . i tried print and it just responds with error

in Serial Monitor one of the settings is line ending. LN & CR

ooh , i found it it's set to Newline

AT firmware requiers \r\n (CR/LF). println adds it. so you need to set it in Serial Monitor or don't set in Serial Monitor and use println. (\n\r\n was the worst combination)

i changed the settings to Both NL& CR and now it works ... thanks man

well ... another problem appears ... AT+CWJAP="SSID" , "password" dont work ... this i have tried with send data function and serial monitor i don't know what is the problem although that AT+CWLAP works

you have a space after the comma? you still print back the command? is it complete?

AT+CWJAP="ssid", "password"     that's exactly how i wrote it

remove the space after the comma

tried it and many other ways i tried space after and before comma , and removed all spaces ... nothing works

did you send CWMODE first?

omg .... finally it's connected .. many thanks you are great

ya i did but my problem was a space before = i guess

i wanted to do that from the beginning but i can't you added comments not answers add an answer so i can upvote

I take your code as a test sketch and will not comment on the terrible way you read Serial input.
The AT firmware requires \r\n as command ending characters. You can set them in Serial Monitor as option LN & CR, but then use print to send the command to esp8266.
Or set in Serial Monitor "No line ending" and let in sketch the println to send the command. println adds \r\n to printed string.
If you had only "New line" set in Serial Monitor and used println the resulting command was for AT firmware disturbing "AT\n\r\n".

i don;t know the right way to read serial input can u please demonstrate as i took the code from internet .

I fixed that problem now i send AT commands and it responds well my problem now is connecting to an access point


text:
Neopixle animation help
Ok I'm stupid when it comes to coding. I have a simple project that I need some help with. Is it possible to make neopixle change what animation runs via multiple switches. Example they stay off till switch is flipped then if a different switch is flipped they run a different animation and vice versa.

Can you show us the code you have written so far?

There is too much unspecific language (e.g. "change what animation runs", "stay off") that it's hard to work out what you are actually asking. Also no need to write at the start of your post "I'm stupid when it comes to coding".  You're not, everyone has problems to solve, that's why this site exists.  Consider editing your question also taking into account VE7JRO's comment.

I get so confused with this stuff lol. What I wanted is the pixels to stay off then when a switch is flipped it does a color wipe and they stay on. Then if another switch is flipped they do a continuous color wipe. And the same in the reverse sequence.

Yes absolutely it is possible. As a beginner, I suggest something like this:

simulate this circuit – Schematic created using CircuitLab
In your setup you will need to declare D4 - D7 as inputs. I have used D4 - D7 but you can choose whatever pins are available.
Then in the loop part of the code you want to look for the rising edge on the input (ie when the switch is pressed). Switch debounce is less important for this application as it is not a counter but rather a mode change.
I have written a good answer for detecting a button press here.
Nick Gammon has an excellent switch tutorial gammon.com.au/switches that covers all kinds of conceivable situations (high or low, GND or +5V, internal pull-up or pull-down, capacitor debounce or software debounce, etc.)
I would imagine the code would look something like this:
if( digitalRead(SW1) == HIGH )
    mode = 1;

if( digitalRead(SW2) == HIGH )
    mode = 2;

if( digitalRead(SW3) == HIGH )
    mode = 3;

if( digitalRead(SW4) == HIGH )
    mode = 4;

You could then use a switch-case statement to run the various NeoPixel patterns.
For more programming reference see: https://www.arduino.cc/reference/en/

Thanx makes it much more understandable

This is driving me nuts lol. does anyone know somewhere i can pay someone to write arduino code.

The Arduino Forum has a Gigs and Collaborations section where you can offer to pay to have code written for you. However if you just want a fancy light show, you can buy those off the shelf, if you aren't interested in learning the programming side of things.

I would like to learn it. Just got frustrated with it for a awheil. I'm trying to make lights for a golf cart. Just like a car has stop,tail,and turn signals. I get  close then mess it up to the point it doesn't work anymore lol

We can do code reviews here on Arduino Stack Exchange. Just add the code review tag to the question you ask.

@Gcompston is there a (part of a) video of something similar to what you want to achieve?


text:
How to install your own library with Arduino IDE 1.8.5?
I'm struggling a bit with Arduino language + its IDE not being 100% real C++. I wrote my own I2C library for a sensor but can't get the IDE's compiler to recognise it. I'm using Ubuntu 18.04.
I get no such file or directory for all of these things I've tried:

Include the .h file by absolute and relative path in the .ino code
Put .cpp +  .h files in ~/Arduino/libraries
Put .cpp +  .h files in ~/sketchbook/libraries
Put .cpp +  .h files in ~/sketchbook/libraries/mylibrary
Put .cpp +  .h files in ~/sketchbook/libraries/mylibrary and try to "install" the library in the IDE (Sketch -> Include library -> Manage libraries; it's not listed)

I'm following the official guide here. Any ideas on how to get the compiler to recognise my library?

You need to:

Create the folder ~/Arduino/libraries/MyLibrary
Place the library files in there named as:

~/Arduino/libraries/MyLibrary/MyLibrary.h
~/Arduino/libraries/MyLibrary/MyLibrary.cpp

Restart the IDE if it is running
Use #include <MyLibrary.h> in your sketch

This is assuming your sketchbook is set to ~/Arduino - change that to wherever the sketchbook is set to (check in Preferences for that location).
Note that in Linux capitalisation is important. The filesystem is case sensitive, and the name of your folder should have the same name and capitalisation as the name of your header file.

No, but what capitalisation you use on your files you should also use on the folder, and you must use in the #include.

I'm not sure how critical it is, but it should be the same as the .h file.

You're right, it was the sketchbook location. I had fiddled with my installation a few times, and hadn't updated the preferences. Thank you.

Have you confirmed where you sketchbook folder actually is? Mine is ~/Arduino (I updated the answer to reflect that).

I would add that the source files can be in src subfolder of the library folder to not mix them with library configuration files and github readme file if you want to publish the library. ~/Arduino/libraries/MyLibrary/src/MyLibrary.h https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

Only if you have a library.properties (or whatever it is) to describe the library...

"I'm not sure how critical it is" When multiple files match the #include directive, the IDE uses folder name matching as one of the factors for determining which gets preference. That's the only time a matching folder name matters.

@per1234 UECIDE is more strict and needs the folder named properly so it can identify precisely what a library is. It needs that so it can do proper recursive library inclusion, which is something the Arduino IDE sadly lacks.


text:
How to connect both MicroSD module and MPU9235 power in an arduino
I'm really new at electronics and wiring, so please be kind. Coding is my stuff, but I'm trying to learn something here.
I'm working with a project to store the movements of a skateboard through a MPU 9235 and the idea is to save the output of the sensor to a MicroSD.
I have both components and acquired a LiPO 3.7v 400mAh to take everything off the protoboard and attach at the bottom of the skateboard.
The code is working, everything code wise is working ok, but I'm strugging to understand how to power both MicroSD module and MPU9235, since both have the VCC pin (VDD in some versions).
The current connections are replicated in Fritzing. Only replacing Arduino Uno for an Arduino Nano, and the MPU 6050 from the picture for a MPU9235.

My first thought was to connect the LiPo battery into VIN and GND pins of Nano. From there I believe that I can wire up the 3V3 output directly to VCC from MPU9235.
But what about the MicroSD module?
How would I power its VCC pin since I have no 3V3 pin left? I read that it's not right to use a digital pin as power output.
How can I connect two components that needs power from external source?

VIN takes 6-12v and it sends it through the on board regulator - so that is the best way to power the nano.
If you take a wire from the 3v3 pin and split it (solder two wires to one) then you will have two 3v3 feeds to wire to your two devices.  This will be the same as you have to do for the Gnd connections, back to the Nano.
Does that make sense? (if not I'll try and draw you something).

Yes it does. It didn't make sense before because I did think that splitting a wire would provide half of 3.3v. Thing is, the board will always try to provide 3.3v for the output wire and if I ended up having too many devices connected to it, to this 3.3v output wire, the battery life will be low. Is that correct?

"The wire" will supply 3.3v to all devices connected, but the board will have to 'split' the maximum current that it can supply between the devices.  Each device will get UP TO the maximum mA it requires, but that may not be enough for it to functions.  I THINK you battery will drain faster, the more devices you have but you can get 10AH+ lipo batteries that aren't much bigger than a AA battery.


text:
Connecting an ESP8266 to WiFi without hardcoding the credentials
I've recently achieved connecting my board, an ESP8266 to my local WiFi, but I've had to hardcode the credentials to the code, just like in 99% of the tutorials online. My code looks somewhat like this:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>

#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;

void setup() {

    USE_SERIAL.begin(115200);

    WiFi.mode(WIFI_STA);
    WiFiMulti.addAP("SSID", "Password");

}

void loop() {
    // Some more code
}

The thing is, I would like to know if there is some way to parametrize the credentials so I don't have to recompile and upload the code to the board everytime my WiFi password changes.
One of my ideas was to connect all the boards to a local router without actual connection to the internet and have a server in that same LAN manage the sensitive information, not the boards. That would allow me to manage credentials properly. Does this even make sense?

Have a read about SmartConfig here. I stumbled across this recently after getting some ESP32s to play with, and it's available for the ESP8266 too. However, I'm not implementing it myself and haven't read enough about it to answer formally. Like you, though, I am creating a WiFi network that isn't connected directly to the Internet. This allows you to create 'bridge' in future, perhaps with Ethernet or WiFi dev boards, to be a smart link to the outside world.

save them to a text file with SPIFFS, then open an API to update the config file. should be a just a few lines of code in total.

The common way to do this is to put the ESP8266 into AP (Access Point) mode and then serve a web page with the configuration interface.
To make it even easier, you can create a captive portal so that the user doesn't need to open a specific IP address in their browser. The captive portal will cause the configuration page to be loaded no matter what address they open.
A popular Arduino library that makes this all very easy is WiFiManager:
https://github.com/tzapu/WiFiManager

It looks pretty solid. Does it consume much resources from the chip?