text:
Arduino nano power 5V or 12V and LED strip 2812B 5V
I would like to know a little more about Arduino inputs and outputs.
I'm doing a small project which is composed of 1 LED strip with 40 LED's.
Can't find any definitely information about Arduino +  LED strip.
At the moment all of this doesn't work correctly and I guess the reason is bad power connection .
The main power is from USB. So all of this in a car. I have ~12v (+2 or -2 Volts ) and then Voltage regulator to 5V with USB output and then cable connecting 5V through USB Arduino . Then I took wires from VIN ( pin number 30 ) to LED strip +5V ( which is basically main fuse on the strip ) and then GND to ground of led strip and of course DIN to DIN like it should be.
Conclusion is - the led strip won't work normally and colors are not proper .
How should I do connect ?
If I will take off the voltage regulator then main fuse from the car ~12V connect to the VIN (it will be a main arduino power) . GND - GND pin obviously.  - and then again from same point ~12V of car will connect to voltage regulator 12V to 5V and that 5V must be with LED strip FUSE +5V ?
Is it will be correct way ?
And one more question, shall I put between "main fuse from the car ~12V connect to the VIN (it will be a main arduino power)" - Voltage regulator 12V to 5V ? is it necessary ?
Thanks for you answers guys, hope you will help me with this.
I'm going to read same questions and answer with this any way. Will wait your answers too :)

Does your strip need 12V or 5V? This isn't clear from the question. Also: won't work normally and colors are not proper what does this mean? What do you actually observer?

the 5 V pin is to power 5 V devices

5V needs , I mean on the end of strip she is flashing and shows another colors

hm... okay then, I have to put regulator 12V to 5V before VIN connection. Actually Arduino nano tech specs says VIN can be connected from 7~16V . Thats why Im asking about it .

okay, so.. I should connect through voltage regulator to VIN (comes 5V ) and GND . - this is arduino power . (or I can connect same USB - only for arduino power. ) and then I must take 5V on LED strip from a car voltage regulator , not from arduino VIN pin . Is in it ?  What about Ground for LED strip.?  Should I take it from Arduino GND to LED strip GND or never mind I can take GND from the car ?

How many LEDs do you have on that strip? Power loss (=> turned into heat) is (Vin - Vout)*I for linear regulators. So if you want to drive 64 full on LEDs, you'll need big ass regulator with huge heat sink. Or you can use switching DC-DC regulator.

I have just 40 :) slightly less :) ~800mA needed if every led takes ~20mA . and 5V.

WS2812 leds can use upto 60mA each (20mA for Red, 20mA for Green, and 20mA for Blue). So that's 2.4A of max current. In that case the voltage regulator would have to burn away 17Watts of power. No way it's able to do that.

You can't draw ≈800mA from the 5V pin on an Arduino that's being powered through USB.  There is a fuse that limits TOTAL current drawn from USB to 500mA. Exceed that and it will shut down.

The main power is from USB. So all of this in a car. I have ~12v (+2 or -2 Volts ) and then Voltage regulator to 5V with USB output and then cable connecting 5V through USB Arduino .

Good. That is the best way of powering an Arduino in a car. Use a phone charger is best.

Then I took wires from VIN ( pin number 30 ) to LED strip +5V

There's no such thing as a "pin number 30" on an Arduino Uno. However, powering anything from VIN when you are supplying power into the Arduino through USB is very bad.
Basically, the current has to flow backwards through the onboard regulator to get to the VIN pin - and the regulator really doesn't like that.
Instead, you should be connecting your LED strip to the 5V pin of the Arduino so it is connected direct to the 5V USB power.
Note, however, that the USB power has a limit of 500mA.  This is not a limit of the supply - it is a limit imposed by a 500mA PTC fuse on the Arduino that will shut off the current if more than 500mA is drawn.  It would be far better if you could cut the USB cable and take the 5V and GND wires and directly connect them to both the Arduino's 5V and GND pins, and the LED strip's 5V and GND connections.  That will then mean that the LEDs are taking their power directly from the power supply, not from the Arduino.

That`s Great!! Thank you so much!! I feel better now!

40 LEDs can draw up to 60mA x 40 = 2.4A (2400mA). Make sure you have a large enough current source if you are planning on using full white on all LEDs.
Arduino regulators are not selected to support 2.4A. 600-700 mA tops, and then only if the voltage to the barrel jack is 7.5V max. With 12V, much less current is supported as the regulator gets hot dissipating (12V - 5V) x current draw as excess heat.
And 500mA for USB as noted due to PTC fuse.


text:
Esp32 sending a wav file to API via POST
I'm trying to send a .wav file to an API with an ESP32 using a HTTP Post request with a multipart/Form-data content type.
I can already send the API Key as it is a plain key and get a return from the server, but I fail on how to add the .wav file into the post request.
I am currently reading the wav file from an sd card, it's 5 secs long 16 bit,11025Hz. and about 400 kb.
If anyone have experience with this, your help would be greatly appreciated!
This is the code snippet where I send the key and where the data should come;
I tried putting the code into a buffer as and concatting the data but I'm not sure if this is the right way to do it
char buf[1024];
 if (https.begin(client, host, port, path)) {

   //https.addHeader("Content-Type", "multipart/Form-data");
   //int httpsCode = https.POST("apikey = XXX");
Serial.println(WavFile);
     https.addHeader("content-type", "multipart/form-data; boundary=----123");
    String HTTPSPost ="------123\r\nContent-Disposition: form-data;
`

----------

name=\"apikey\"\r\n\r\XXX\r\n------123--\r\nContent-Disposition: form-data; name=\"wav\"; filename=\"test444.wav\"\r\nContent-Type: audio/x-wav\r\n\r\n\r\n";
  `
    //wav recording Comes here
    String WavData ;
   // for (int i = 0; i < 1024; i++) WavData.concat(buf[i]);; // Tried to put Wav file in a buffer
  // Serial.println(WavData);

    String End = "------123--";
    String full = HTTPSPost + WavData + End;
    int httpsCode = https.POST(full );
        if (httpsCode > 0) {
              if (httpsCode == HTTP_CODE_OK) {
                res =  https.getString();
                JsonObject& obj = jb.parseObject(res);

                String token = obj["error"];
                if (obj.success()) {

                } else {
                    res = "failed to parse json";
                }
              }
        } else {
            res = "failed to Post";
        }
   } else {
    res = "failed to connect to server";
   }
https.end();
return res;
}
`

better code because httpclient can't do sd cards, but wificlient can;
File file = SD.open("/xxx.wav");

if (!client.connect("XXX", 443)) {
  Serial.println("Connected FAILED!");
  return;
}

Serial.println("Connected ok!");

client.println("POST  HTTP/1.1");
client.println("Host: ");
client.println("Cache-Control: no-cache");
client.println("Content-Type: multipart/form-data; boundary=----123");
client.println();
client.println("------123");
client.println("Content-Disposition: form-data; name=\"grant_type\"");
client.println();
client.println("client_credentials");
client.println("------123");
client.println("Content-Disposition: form-data; name=\"apikey\"");
client.println();
client.println("XXX");
client.println("------123");
client.println("Content-Disposition: form-data; name=\"wav\"; filename=\"xxx.wav\"");
client.println("Content-Type: audio/wav");
client.println("");
client.print("Content-Length: ");
client.println(file.size());
//client.println();
//while (file.available()){
//      client.write(file.read());
//}
client.write(file);
client.println("------123--");
Serial.println(">>><<<");
if (client.available())
    {
      String serverRes = client.readStringUntil('}');
      Serial.println(serverRes);
    }

what is HTTPSPost+buf[1024]+End? you can't put binary data into a String. a 0 would be end of the data

You're right, it's a leftover from me trying to put the buffer into the string... the Full string should be placed into it, edited that part.

Is there a way to convert it, or how to make it 'correct'? I guess that is my question

The esp32 only has 512kb of RAM. Putting a 400kb wave file, plus some HTTP headers, in memory will probably not fit.

you can't do it with HTTPClient. use WiFiClient. if the file is in SPIFFS you can use client.write(file) for the binary part of the POST request

Thanks! I tried using it with WiFiClient now, can you client.write(file); for a file on an sd?

yes you can use client.write() for SD card file too

Thanks for all the input Juraj! I edited the Q an added the better code, but there seems to be a problem with the apikey still, is it the correct way to implement it? Can I still ask this question here? I don't want to overload the question :)

try to add content-length to every part

source: Stack Exchange

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

sort: votes


text:
Does data coming in on Arduino serial port store for some time?
I am using Arduino Uno and my question is when data is coming on Rx pin and at that time our program is not checking Serial.available()
Then after some time the program will check Serial.available().
Can we read data? Does it get stored in memory?
If stored how to remove that?
Is the answer the same for Software.Serial()?

Yes.  The serial port uses a ring buffer (also known as a circular buffer) for storing the incoming data until you want it.  That buffer is 16 bytes in size on the smaller Arduinos and 64 bytes in size on the larger one.  A similar ring buffer is used to store transmitted data until the port is ready to transmit it in the background.

What happens if the buffer is full and my PC writes an extra character?  Does the PC block until there is buffer space, is an old character dropped or is the next character dropped?

The next (incoming) character is dropped.

Note that when the IDE is on a Raspbian, HardwareSerial.cpp is located at /usr/share/arduino/hardware/arduino/cores/arduino - go into HardwareSerial.cpp and look at where it detects it has more than 1000 bytes of memory (The Rpi3 has 2048) and that is where the ring buffer setting is 64. I haven't found any need to expand it, but it can be done.

Only if you installed it through apt - which generally installs an ancient (1.0.6 IIRC) version. Sensible people download the tar file from Arduino's website.

I used sudo aptitude install arduino months ago and it is version 2:1.0.5 - and it works great.  Since it installed it never occurred to me to look elsewhere.  (Except on Windows, of course).

Ouch - even older than I thought.  Arduino used to (years ago) push up to the debian repos. They haven't done it for a long long time now. 1.8.4 has been released (I just published UECIDE packages for it) and you really should be on that or something close to it these days...

OK, I see 1.8.4 there as a tarball.gz - Will get it.  (What is UECIDE?)

Better than Arduino's IDE ;)

I notice that I am at 1.8.2 on Windows.  So I can update both of them, also.  (This means updating 8 computers now, thanks very much.  ;-)

Let us continue this discussion in chat.

Yes.  The receive ring buffer is 64 bytes and will discard anything past that until the program reads them out of the buffer.

But be careful:  In serial monitor, any number of bytes more than 64 and ending with Enter will give you Serial.available==63 at the Arduino - and no \n at the end.  This is important especially if you are using readline() in Python.
However, when NOT in the serial monitor, you can actually get the result Serial.available==64 and use Serial.read() to get them in sequence.  No \n is required.
So be careful debugging in the serial monitor when it comes to buffer size and newlines.  It is subtly different when programs are talking vs the serial monitor.
Most important difference is that a program can send a single byte and continue.  Serial monitor will send a single character, but is blocked until you press newline to get it to transmit.  Yet serial monitor does not send the newline character.

Simple scenario:  You want the Arduino to respond to a single-byte command code send via the serial cable from a Raspbian system running a Python data logging program based on something the Arduino reads or by time of day.
You need to trigger the Arduino to take some action as a result.
So on the Arduino you want to first clear the receive buffer by simply reading it out like so:
Arduino code to read a single-character command:
byte ch;
void setup() {
  Serial.begin(9600));
  while (Serial.available>1) ch = ser.read();
}
void loop {
  if (Serial.Available==1 && Serial.read()=='X') {
     .....respond to the X command....
  }
  else
     ....etc...
  delay(60000);
}

Note that when a Rpi Python program is sitting there waiting for linein=ser.readline() the Arduino transmit buffer size is not relevant.  Python collects each byte as it comes in until the \n then returns the string to linein.  The line can be very long.  I have tested it to 100 bytes.

Software.Serial acts exactly the same way.

When you start the Python program it will do a ser=open("/dev/ttyUSB0",9600) to communicate with the Arduino, which causes the Arduino to reset just like starting the serial monitor does. It is good practice to run the above setup code to clear the Arduino's receive buffer so you know you have an empty channel both ways.

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


text:
I want to build a radar alert system with Arduino
I'm new to all this. I bought an Arduino Uno recently and an Ultrasonic distance sensor. My mom's cats keep walking down into the basement and doing their... business. Anyhow, I want to create a radar system which detects movement past this door. I'd like to have an alert sent to my computer or Android. Is this within a basic Arduino level? Other than the Arduino what else might I need?

The widely available ultrasonic modules are more suited to detecting object presence (ie distance) than specifically motion, but they are at least cheap and easy to experiment with.  You could also consider an IR beam-break for presence.  In terms of an alert, would a local audio transducer be workable?  If not you can look at bluetooth, or wifi, perhaps even running your project on an Arduino-ified ESP8266 instead of an actual Arduino in the latter case.

That would be a sonar, not a radar.

Of course, you could do what I did when my kids were babies ... put a gate across the stairs.

I think that's quite possible. As mentioned, not technically radar. I don't know if cats could hear it, but then if it scares them off, job done, right?
I don't know if sending the alert to a PC would help or not - you might just consider an audible alarm using a cheap 8-ohm speaker. Otherwise, USB, bluetooth, wifi, or SMS for notification. A PC or phone (on all the time) to receive the data. Some thought about what you will do with it.
As a deterrent, a water pistol is ideal, you'd need a motor - solenoid? - to fire the water pistol. Harmless, but very distasteful to cats.
https://www.youtube.com/watch?v=lxmRYRlgreo
Update: Inspired by @SDSolar, I checked it out - yes, cats can hear that frequency.

Cats have excellent hearing and can detect an extremely broad range of frequencies. They can hear higher-pitched sounds than humans or most dogs, detecting frequencies from 55 Hz up to 79 kHz.

(from https://en.wikipedia.org/wiki/Hearing_range#Cats )
This means they will probably learn to associate the sound with the water pistol (yes, cats CAN be trained, if they are motivated). This means if you remove your device, they will probably come back, but if you leave the sensor (active), but remove the water, then it will continue to work!

Cats can't hear 40 KHz.

According to wiki (as per my update), they can. Citation?

I stand corrected.  I am very surprised.  I didn't know any animal could hear that except maybe bats.  But I found this reference that confirms what Wikipedia says, sort of.  This one says up to 59 KHz:  http://pets.thenest.com/frequencies-cats-hear-8238.html  TNX for the info.  Learn something new every day.  So perhaps the mere presence of the sensor would be a deterrent?  Probably not for cats, unless the water pistol or a loud noise is triggered when they get in the critial range.

I'm not convinced an ultrasound detector will detect a cat.  They're fluffy and (usually) soft, so the ultrasound might not bounce off.
Instead I suggest you just try a gadget that annoys cats and keeps them out of the area.  It's an ultrasound emitter, and the noise is claimed to be objectionable to cats.  I've seen them sold in gardening stores, for keeping cats away from the bird table:
Opinions on cat scarers

Ultrasound should detect a cat - the question is more, if it will detect a cat amid background clutter at similar ranges.  Generally for the cheap pulse-in/pulse-out sensors, you have to arrange the situation so that the first substantial reflection is the object of interest.

If the other side of the stair provides a reliable reflection, then the reading would change with any obstacle in the way.

Ultrasonic sensors can only measure the distance to the nearest object in their cone. Are you sure you can detect a "small" thing like a cat?
I think the only feasable way is to use optical recognition (motion sensor with a camera - even a webcam - and a board like a raspberry pi).

Or there's an off-the-shelf solution: Innotek ssscat is a bottle of compressed air and a motion detector. The spray is harmless but it sounds like a hiss, which is Cat for GTFOuttaHere!

That is cool.  A bit pricey but I would love to see one in action.  If they were a quarter of the price I would use them as perimeter guards around my solar arrays to keep the critters away, including the family dog.  Upvote.

ANSWER BASED ON YOUR TITLE:
Here is a microwave RADAR motion-sensing module that you might find useful.  You could mount it right by the stairs.
http://www.ebay.com/itm/262662221979
LFS-DC04 2.7GHz Microwave Radar Module DC 5V 360 Degree High Level Signal New

Product Introduction:
1.Model:LFS-DC04
2.Frequency:2.7GHz
3.Size:40*22mm
4.Input Voltage:DC 5V
5.Output Type:level signal output
6.Connection Method:VCC,GND connect with positive negative input, OUT,GND signal connect with output
7.Installation Height:1-3.5m
8.Sensing Ditance:5-8m
9.Delay Time:30s(quick testing mode is 4s)
10.Sensing Angle:360 degree
11.$1.59 price via the slow boat

ANSWER BASED ON YOUR TEXT:
Ultrasonic can work - you will want to position it so your software can tell whether there is a cat/no cat, like pointing it across a step.  With no cat it would give a reliable distance reading from something on the other side of the step.   With the cat in the way, that reading would change.
Yes, this is in the realm of Arduino, for sure.
Here is a Google search to get you started:
https://www.google.com/search?q=arduino+with+ultrasonic+sensor
To tell the difference between a cat an a human you would want a second sensor, above the cat's height, also.
Or you could use a DS3231 RTC module to decide when it is night-time so you wouldn't need to discriminate between cats and people at all.

As a project building a cat detector sounds interesting, but as a cat owner I can promise you that if you actually go through with it the cats will see it, play with it and trash it within 5 minutes.  If it is successful and you do manage to scare them out of the basement they are just going to find somewhere else to 'do their business' and that could be in your bed.
However, your sensor will need to scan a large field of potentially rapidly moving objects.  A beam wouldn't be suitable because they could step over or under it.  I think PIR would be best for this task, but PIR sensors might not be sensitive enough to detect the little darlings.
Another idea maybe a gas sensor based project to provide an audible warning when a human enters the area that there are 'landmines' in the proximity and extreme caution needs to be used, if you know what I mean :)

Sounds like you want the Arduino-Fart-O-Meter - http://www.instructables.com/id/Arduino-Fart-O-Meter/  -- which I found doing this Google search:  https://www.google.com/search?q=arduino+gas+sensor+for+cat+poop

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


text:
RFID Reader ID12-LA reads every card as ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
My new RFID reader ID12-LA by SparkFun can recognise an RFID tag, but it can't read its tag number - the Arduino IDE outputs the tag as ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
Any help on how to convert this into a proper ID would be much appreciated - btw I have tried other baud rates; no difference.
Thanks, Raihaan
Edit - the code I'm using is this:
#include <SoftwareSerial.h>

SoftwareSerial rSerial(4,5);

void setup() {
    rSerial.begin(9600);
}

void loop() {
    if (rSerial.available() > 0) {
        int b = rSerial.read();
        Serial.print(b);
        Serial.print(" ");
    }
}

This now returns 255 6 times... Any ideas?
Schematic:

Raihaan, please edit question and format the code as code.  To do so, highlight the code and press ctrl-K.  Add a blank line before and after the code.  Also, use cut and paste when you include the code -- there are some missing characters.  Also, where are you getting data from the reader?  Do you have one connection for the reader, and one for the IDE, with one or the other not shown in your question?  Fix the question.

There is a format selector (I can't quite read the image because of the wire). It should be grounded to select ASCII format.

ÿ is 0xFF (255 in decimal). That is, all 1-bits set. It is also what is returned from Serial.read() if there is no data (actually it returns -1 which is 0xFFFF in this case however that will look like 0xFF if you stuff it into one byte). Possibly there is a gross mismatch in baud rates. An occasional 0-bit will look like a start bit, and then if you get all 1-bits after that, you would get 0xFF returned.

If you have one of the regular Arduino models, the hardware UART is connected to pins 0 and 1, which are also used by the USB programmer and in your case obviously your serial monitor, on which you expect to see some output.
Configuring a SoftwareSerial on pins 0 and 1 is probably not going to work at all. If you need the USB programmer to stay connected and the serial monitor for debugging, you have to use different I/O pins and setup your SoftwareSerial accordingly.
I assume that you are aware that the ID12-LA chip only works on the 125 kHz band and is incompatible with common tags running on 13.56 MHz?

Ok, so I'e switched the SoftwareSerial pins to 4 and 5, but I'm still not getting an output - is it because I'm not using EM4001 ISO tags?

@Raihaan What kind of tags are you using?

No idea- only ones that advertised themselves as compatible with any RFID reader

Except the ID12 says that very specific ones are the only ones compatible - i.e. the EM-4001 ISO tags

RFID is an umbrella term for many similar, but otherwise incompatible transmission technologies. There simply are no tags 'compatible with any RFID reader'.

You created a SoftwareSerial connection to read from the module and then you're printing what you just read to the same module. You probably want to print to the serial monitor on your PC. You should add Serial.begin(9600); to your setup() and ensure that all print()s are to Serial and not rSerial().

Thanks, now it outputs strings, but still quite unusual - 255 13 times - I'm starting to believe the issue is not from the Serial connections but with the actual RFID hardware - either the reader or the tags.

@Raihaan Edit the code in your question. Also include your circuit.

Done - code has been updated, schematic has been included (from Sparkfun)

Like Nick Gammon has said, you need to connect the FORM pin to GND to select ASCII format. Also connect the RES pin to 5V.

How should I select ASCII format? Is this in the serial monitor?

What do you know... It worked! Cheers guys!


text:
Receive data from multiple wireless sensors simultaneously
I want to receive data from multiple (2/3) wireless sensors at the 512 Hz data rate simultaneously at a single receiver (bluetooth or any other wireless standard). Is it possible with one receiver or I need  multiple receivers?
I am novice to wireless communication please guide me to any available resources.
Thank you.

It is possible to do this with Zigbee. The API mode in the Xbee modules enables this.
Unlike the AT mode in Zigbee the API mode enables you to distinguish between the packets that you receive from different slaves.
In the API mode, you send each data packet with as a frame with a header which contains start delimiter byte, most significant byte (which tells where the start byte is at), least significant byte (which tells the end of the byte), an API identifier, the data that you want to send and a checksum byte.
This link provides a nice tutorial which shows how to setup Xbees on API mode with an Arduino and Python:
http://serdmanczyk.github.io/XBeeAPI-PythonArduino-Tutorial/
I hope this helps.

Thank you @MayBee for your answer. I went through the link and found useful. Since I am at the design phase right now, I would like to know whether it is possible with wifi or bluetooth? I don't have any power constraints , also I want to know, since data is coming at 512 Hz from each sensor(3 sensors) what type of issues which may occur while synchronizing all the sensors? thank you.

One issue that I faced was that the XBee modules could not handle large data packets in the API mode. Usually, Bluetooth only allows one to one communication but I believe that there are certain modules that will allow multiple slaves. In the case of WiFi, you could perhaps set up an external server and the modules could communicate using that. I have done this for a paid of RNXV WiFly module.  But, you should be able to add more slaves to this without issues. If you want a personal area network with multiple nodes, Zigbee would be the easiest to work with.


text:
Converting `millis()` to decimal seconds?
I would like to get my Arduino to print milliseconds as decimals of seconds.  For example, instead of printing 10456, printing 10.456
I have tried to set a float value or millis, and dividing by 1000 but that gives me a whole number "0" to "1" which is not ideal
The code I use is:
float ourtime = (millis() / 1000);
dataFile.print (ourtime);

What would be the easiest, and least taxing (for the processor) way of getting a script to return milliseconds as seconds while taxing the unit as little as possible ?

Could you make explicit the meaning of "the best way"? Do you mean, a way that works properly, a way with readable code, a fast way (how fast), a way is as little code as possible?...

Dividing an integer by an integer (1000) yields an integer, regardless of what you cast that result to.
Instead you need to divide the integer by a float, or cast the integer to a float first. The simplest way is:
Serial.println(millis() / 1000.0, 3);

The 3 as the second parameter tells Serial.println() how many decimal places to print. The .0 at the end of 1000.0 forces the compiler to see 1000 as a float value (you can also use 1000f if you prefer).
Since floating point can be quite expensive it's possible to emulate it using integer division and modulus (although they are still quite expensive):
uint32_t now = millis();
uint32_t secs = now / 1000;
uint32_t ms = now % 1000;

Serial.print(now / 1000);
Serial.print(".");
if (ms < 100) Serial.print("0");
if (ms < 10) Serial.print("0");
Serial.println(ms);

You could replace the % with a x1000 and a subtraction too if you like:
uint32_t now = millis();
uint32_t secs = now / 1000;
uint32_t ms = now - (secs * 1000);

Serial.print(now / 1000);
Serial.print(".");
if (ms < 100) Serial.print("0");
if (ms < 10) Serial.print("0");
Serial.println(ms);

A further method would be to first "print" the milliseconds to a string, then split it into two chunks. Print the first chunk, then a decimal point, and finally the second chunk. This avoids the use of any division or multiplication, but does use expensive string operations:
char num[10];
snprintf(num, 10, "%lu", millis());
uint8_t nlen = strlen(num);

for (uint8_t i = 0; i < nlen - 3; i++) {
    Serial.write(num[i]);
}
Serial.write('.');
for (uint8_t i = nlen-3; i < nlen; i++) {
    Serial.write(num[i]);
}
Serial.println();

So really there is no "perfect" method for converting milliseconds into seconds that uses hardly any CPU cycles. All base 10 operations tend to be a bit expensive on a small microcontroller without hardware support for integer MUL/DIV instructions, or a Floating Point Unit.

You mean if (ms < 100) and if (ms < 10). Integer division is not cheap either: I timed your float code version at 11480 CPU cycles (not counting the call to millis()) and you int version at 7561 cycles, i.e. 34% less time. Both for the millis value 12345678UL. So it's faster, but not by orders of magnitude.

You are right, my keyboard is hiding under the desk at the moment and I can't actually see it.  No division on an AVR is cheap. If you are that concerned about the speed of division you would pick an MCU with a hardware division unit, or an FPU and use floating point.

Serial.println(millis() / 1000.0, 3);
is a great idea, but if used alone, it drops zeros.
So the output would be "0.849", "0.874", "0.95" (and not "0.950") which may cause problems.

Sure. I am just saying that replacing floating point division by integer division does not provide as large a speedup as one may naively expect.

Also you have to wonder how much of the difference is due to the serial print routines, one handling float and the other handling integers...

A third method would be to print each character individually via a string without using any division at all...

uint32_t ms = now % 1000; given that you already have done thee division, the mod operation is unnecessary, especially given how expensive it is.

@dannyf You would have to multiply by 1000 and subtract it from now instead, which can be as expensive.

@dannyf: The compiler is smart enough to factor the now / 1000 and now % 1000 into a single call to __udivmodsi4().

Division is quite expensive.
Division can be done with subtraction, or shifting - right shift 10 (= /1024) and then compensate for that 24....
You may need too benchmark to see if on your chip this will yield any gaiin.
edit:
I did some quick benchmarking against the brutal force approach by Majenko (division followed by the mod operation), for full range 16-bit types, dividing by 1000, on a PIC16, XC8 free mode:
for 16-bit types
 1. Majenko's approach (1000 divisor + mod): 45.9M ticks;
 2. revised Majenko's approach (1000 divisor, no mod): 36.9M ticks;
 3. My approach (1024 divisor, no mod): 20.8M ticks.
[edit 2]for 32-bit types
 1. Majenko's approach (1000 divisor + mod): 101.6M ticks;
 2. revised Majenko's approach (1000 divisor, no mod): 63.0M ticks;
 3. My approach (1024 divisor, no mod): 19.3M ticks.
the same trend applies under the pro mode.
the same trend applies for AVR, with the speed gain being bigger.
edit 2: 32-bit benchmarking added.
I also revised my approach for 32-bit types to speed up the execution a little.
lessons learned:
1) mod ops shall be avoided as much as you can;
2) divisions shall be avoided as much as you can.
3) algorithm rules!
however, be cautious to extrapolate the data here. on a chip with hardware multiplier + divider (STM8, my favorite chip), this trend may not apply and you should benchmark on the target chip to be safe.

Care to show the algorithm to “compensate for that 24”?

I don't think it the division that is slow, but the use of a float on a CPU that doesn't support floating point operations.


text:
How to change the default name of ESP8266-12E module
Is there any way to change the default name (ESP_xxxxx) that the module generates?

What do you mean by name?

canadiancyborg I edited the question. Now it's understandable!

Which firmware are you using?

Hi gre_gor! I'm not using any firmware, I am using the Arduino IDE.

@SrJulien You must be using a firmware on the ESP or it wouldn't work, please determine it before we can really help you efficiently.

The function is: WiFi.hostname("Name");, make sure you call it before Wifi.begin()

This is the actual (modern) answer

This line of code should hopefully do a difference.
wifi_station_set_hostname(myHostname);

For more information :
https://www.reddit.com/r/esp8266/comments/3zl3pi/change_esp8266_network_name/

Hi canadiancyborg!  I tried to use 'wifi_station_set_hostname', but without success! I appreciate any suggestions!

Here you are the code where you can see how you can change network name of your ESP8266 working in AP mode:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

IPAddress ip(192,168,1,81);         // choose IP address
IPAddress subnet(255,255,255,0);

ESP8266WebServer server(80);

void handleRoot() {
  String page = "<!DOCTYPE html>\n";

  page += "\n\n
Some heading

Generated by ESP8266\n\n";
  server.send(200, "text/html", page);
}

// what to do when accessed through http://ip_address/something_undefined
void handleNotFound(){
  String message = "File not found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void){
  Serial.begin(74880);                      // so you can see debug messages automatically sent by ESP8266
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(ip, ip, subnet);        // declared as: bool softAPConfig (IPAddress local_ip, IPAddress gateway, IPAddress subnet)
  WiFi.softAP("SOME_NAME", "password", 7);  // network name, network password, wifi channel

  IPAddress myIP = WiFi.softAPIP();
  Serial.println();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.on("/", handleRoot);               // what to do when accessed through browser using http://IP_address

  // what to do when accessed through http://ip_address/test
  server.on("/test", [](){
    server.send(200, "text/plain", "This is another page");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started...");
}

void loop(void){
  server.handleClient();
}

check the Erase Flash>> Tools >> Arduino IDE before uploading your sketch and select erase previous wifi settings

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


text:
Make OTA work with Arduino Uno Wifi
I just bought a Arduino Uni Wifi Rev. 2, with the itention of doing over the air uploads to the devices.
By reading the official Gettings started with the Arduino Uno Wifi guide, I thought the process was just to power the devices, connect to the SSID, then browse to it's IP and set it up.
But it seems like this is not the case, and that others have made this same mistake. This Arduino device doesn't create network by default, we have to upload a sketch that connects to our wifi.
So I have two questions.

What Arduino board are they referencing in the guide linked above, that we can just connect to out of the box?
How can I get OTA support for my particular board?

have you gone through this? https://www.arduino.cc/en/Guide/ArduinoUnoWiFi

@SimSon Yes. That's the article I linked to in my post. It's only for Arduino Uno Rev. 1 it looks like.

What Arduino board are they referencing in the guide linked above, that we can just connect to out of the box?

The first Uno WiFi was made in 2016 by arduino.org. It is retired and not available in stores.

How can I get OTA support for my particular board?

The OTA support for Uno WiFi Rev. 2 is ready or almost ready, but the required additions are not merged in GitHub firmware and library repository even if they wait some months now. It looks like Arduino focuses on something else.

Thanks for this. Do you have a link to the Github issue/pull request for that feature, so that I can follow it?

As far as I understand, it should be possible to upload a sketch to the arduino over USB, that connects it to your wifi, so that it then can support OTA uploads. Do you have any insight into that?

not for Uno WiFi Rev 2. for many others https://github.com/jandrassy/ArduinoOTA

and plans for Uno WiFi Rev 2. https://github.com/arduino/nina-fw/issues/36

https://docs.arduino.cc/retired/getting-started-guides/ArduinoUnoWiFi

@Bruno that is for Uno WiFi Developer Edition, not for Uno WiFi Rev2


text:
Parsing HTML GET request with params with WiFiEsp
So I'm Setting up webserver with esp-01f+arduino uno. I'm using WiFiEsp library.
I want to toggle led on. Pin will be given in GET request by url.
Example:
host.com/?ledpin=9
How can I parse it, then get 9 number?
Code:

#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif

char ssid[] = "Twim";            // your network SSID (name)
char pass[] = "12345678";        // your network password
int status = WL_IDLE_STATUS;

int ledStatus = LOW;

WiFiEspServer server(80);

// use a ring buffer to increase speed and reduce memory allocation
RingBuffer buf(8);

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT); // initialize digital pin LED_BUILTIN as an output.
  Serial.begin(115200);   // initialize serial for debugging
  Serial1.begin(9600);    // initialize serial for ESP module
  WiFi.init(&Serial1);    // initialize ESP module

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
  printWifiStatus();

  // start the web server on port 80
  server.begin();
}

void loop()
{
  WiFiEspClient client = server.available();  // listen for incoming clients

  if (client) {                               // if you get a client,
    Serial.println("New client");             // print a message out the serial port
    buf.init();                               // initialize the circular buffer
    while (client.connected()) {              // loop while the client's connected
      if (client.available()) {               // if there's bytes to read from the client,
        char c = client.read();               // read a byte, then
        buf.push(c);                          // push it to the ring buffer

        // printing the stream to the serial monitor will slow down
        // the receiving of data from the ESP filling the serial buffer
        //Serial.write(c);

        // you got two newline characters in a row
        // that's the end of the HTTP request, so send a response
        if (buf.endsWith("\r\n\r\n")) {
          sendHttpResponse(client);
          break;
        }

        // Check to see if the client request was "GET /H" or "GET /L":
        if (buf.endsWith("GET /H")) {
          Serial.println("Turn led ON");
          ledStatus = HIGH;
          digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
        }
        else if (buf.endsWith("GET /L")) {
          Serial.println("Turn led OFF");
          ledStatus = LOW;
          digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
        }
      }
    }

    // close the connection
    client.stop();
    Serial.println("Client disconnected");
  }
}

void sendHttpResponse(WiFiEspClient client)
{
  // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
  // and a content-type so the client knows what's coming, then a blank line:
  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:text/html");
  client.println();

  // the content of the HTTP response follows the header:
  client.print("The LED is ");
  client.print(ledStatus);
  client.println("
");
  client.println("
");

  client.println("Click here turn the LED on
");
  client.println("Click here turn the LED off
");

  // The HTTP response ends with another blank line:
  client.println();
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print where to go in the browser
  Serial.println();
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);
  Serial.println();
}

Details gives me only this:
GET /favicon.ico HTTP/1.1
Host: 192.168.0.165:5000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
Accept: image/webp,image/apng,image/*,*/*;q=0.8
Referer: http://192.168.0.165:5000/H
Accept-Encoding: gzip, deflate
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7

First print to Serial all of the received request. Then look at it and think. How do you know that the payload is 9? What distinguishes it enough that you can always identify it in a request? What do you look for? Once you can answer these, you can then frame a more specific question to know how to implement your algorithm or just use google to find the right functions.

Can you easily say how to parse GET /pin=9?

And one more question how can I write it to serial?

I rolled back the edit. Don't change completlly a Question. Someone is maybe working on an Answer.

OK. Thanks. Juraj

Juraj can you give answer? Or I must explain more

Heey. Is anyone alive?

Where did you copy this code/sketch from? There are several C/C++ standard functions that can help parse the request. Also the Arduino String class contains several member functions for this. Do you want us to write/update the sketch for you?

Here is a tutorial https://techtutorialsx.com/2016/10/22/esp8266-webserver-getting-query-parameters/

Mikael Patel, if you can  please

The tutorial works only on esp8266 flashing

please update my sketch

EEEYYYYYEYEYEYEYEYEYEYEYEYEYEYEYE

HEY please update my sketch please,PLASE,PLASE

HEEY. Anybody . Update my sketch please

The answer is to use indexOf and substring functions of response String


text:
Connecting Arduino Uno to a smartwatch via bluetooth
I have a U80 Smartwatch from Bluetooth Watch International, which has bluetooth function. It is meant to be connected via to my smartphone (and it works perfectly).
I also have an Arduino Uno board and a corresponding BLE ZS-040 bluetooth chip.
I need for my smartphone to be able to detect my Arduino board, so I can send data from a simple circuit connected to the Arduino board to the smartphone.
Basically, my circuit is meant to be a simple push button. When the button is pushed, and the circuit is closed, the Arduino board will send a signal to the smartwatch. This will cause the smartwatch to ring and vibrate, as if it is receiving a call. Then to turn off the ringing and vibrating, the user can simply 'answer the phone call', and it will stop.
From what I understand, (I'm very new to Arduino) I have to connect the Arduino board to the smartwatch first, which means I have to somehow get the board to be detected by my watch, which it's not doing yet, eventhough the bluetooth module is connected to the board.
Then the push button needs to send a signal to the watch. Which means the command {if buttonpush='1', send (receiving call)}, so when the button is pushed, the signal is sent and the watch acts as if it is receiving a call. Basically showing all the physical signs (eg. vibrating and/or ringing based on the watch's setting, showing 'answer/deny call', etc.). Btw, the push button is not to be held down. As long is the button is pushed and released once, the signal should be sent, and the watch will buzz until the 'phone call' is answered or denied.

I have absolutely no idea how to get the board connected to the smartwatch via bluetooth.
And while I have a rough idea on the push button circuit I need, I also need to send the signal for the watch to act like it has received a call.

Mainly, I'm looking for any help with coding here. If anyone can help with the physical circuit connections, that would be awesome too.

What is your "corresponding bluetooth chip"?

Sorry, I have edited to add in the information. HC 05

Unless the watch has a developer API for bluetooth (master) you can not use anything else than the Android app to connect to it properly even assuming you have a BTLE module.

HC-05 is a Bluetooth 2.1 SPP only chip (BR/EDR). Your bluetooth watch will be Bluetooth Low Energy 4.x (BLE Single Mode).
The two are not compatible.
You will need a BLE module for the Arduino which is capable of running as a "Central Device".

Thank you. I was a bit confused between the two, but I managed to confirm that mine is ZS-040 which is the BLE chip I think ><?

This isn't exactly an answer but I will like to share my experience after attempting a similar project for the past week.
I have an Arduino UNO and a HM-10 Bluetooth module that is capable of functioning in central mode. I referred to http://www.martyncurrey.com/hm-10-bluetooth-4ble-modules to setup.
I am trying to connect the Arduino UNO/HM-10 with a Hexiwear (http://www.hexiwear.com) bluetooth IoT development smartwatch that is capable of sending sensor data such as steps, heartrate, temperature etc. via bluetooth to a BLE central device.
The Hexiwear will generate a random 6 digit pin when you attempt to connect to it. It works with its own companion Android app and reads sensor data perfectly. Someone managed to pull in the hexiwear's sensor data to a Raspberri Pi via BLE here: https://mcuoneclipse.com/2016/12/19/tutorial-ble-pairing-the-raspberry-pi-3-model-b-with-hexiwear/comment-page-1/#comment-97375.
With my Arduino UNO, I managed up to the point were I could connect the hexiwear and it pops up to ask for the random 6 digit pin so that it could pair to my Ardunio.
And then I am stuck, because I know nothing about the Arduino UNO and HM-10 that can send the pin code back to the Hexiwear.
Here's where I thought might be useful:
1) Do you have the U80's BLE specifications. This is how much hexiwear's BLE specification looks like https://github.com/MikroElektronika/HEXIWEAR/blob/master/documentation/HEXIWEAR%20Bluetooth%20Specifications.pdf.
My Hexiwear wearable comes with source code. If I try hard enough I can probably hack it to make what I want to do possible.
2) Does U80 require pairing with pin code? I am stuck here in my project.
3) Is the library for your BLE chip capable to sending said BLE requests and responses to communicate with the U80? This is where I believe I am going to be stuck further.
Hope this helps in some ways.


text:
Inkjet Printer Robot Wheels
I'm newbie about Arduino.
Can i build arduino robot wheels using Canon/Epson Cartridge inkjet printer?
The idea is like Drawing Robot

but i want to use cartridge printer instead of using a pen.
so after searching, and it look like ZUtAPocketPrinter

The Drawing Robot is using Trinket Pro
And ZUtAPocketPrinter is using Arduino (don't know using Uno/Nano/etc)
Can I use Trinket Pro or what types of arduino that i can use (Uno, Nano)?
And what hardware, sensor that require to scan/measure size of the paper?
And if there is tutorial, please share the link.

Usually a robot uses 2 identical motors for drive in order to change directions or go straight.  Usually a printer will only have 1 motor to drive the paper and 1 motor to drive the print head.  And usually they are not identical.  Making it difficult to build a useful robot.  Also, printers usually use stepping motors.  Most people building their first (small) robot usually use continuous servo motors.  This makes for an easy to build first (small) robot as seen in this picture:

But the OP already marked the answer as correct.  Also, it has become more apparent that the OP is looking for an opinion.  Many people will not like that as it solicits discussions instead a clear question and a concise answer.  Stackexchange works best when the OP builds something, then comes and asks why something does not work.


text:
Is there any way to efficiently code reading of four sensors and sending a serial output once it does detect a reading?
I am actually wondering if there's a way to efficiently do this block of code. There are two things in my specifications and these are:

Four IR Sensors that detects blockage. Basically just to trigger it HIGH or LOW
Once one of the sensors got tripped/triggered, it sends a Serial output

In order to do that, I made this code. Basically just stuffing digitalRead and their if conditions in the loop. Is there any way to make the code shorter all the while make it faster for the Serial to get sent?
#define IRSignal1 2
#define IRSignal2 3
#define IRSignal3 4
#define IRSignal4 5

int IRVal1;
int IRVal2;
int IRVal3;
int IRVal4;

void setup() {
  // put your setup code here, to run once:
  pinMode(IRSignal1, INPUT);
  pinMode(IRSignal2, INPUT);
  pinMode(IRSignal3, INPUT);
  pinMode(IRSignal4, INPUT);

  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  IRVal1 = digitalRead(IRSignal1);
  IRVal2 = digitalRead(IRSignal2);
  IRVal3 = digitalRead(IRSignal3);
  IRVal4 = digitalRead(IRSignal4);

  if (IRVal1 == LOW) {
    Serial.print('1');
  }
  if (IRVal2 == LOW) {
    Serial.print('2');
  }
  if (IRVal3 == LOW) {
    Serial.print('3');
  }
  if (IRVal4 == LOW) {
    Serial.print('4');
  }
}

If you have tips, or a go-to resource for efficient coding practices that also helps with memory allocation, shorter code, and speed, I would also love to hear them if that's alright with you.
I use both arduino mega and uno in case this information is useful.

For what are you optimizing? The code as you posted it should be fast enough to track moving things. If they are really fast you might wanna increase the baudrate (since at 9600 baud the duration of the transmission will be in the lower millisecond range). Or do you actually have more code and this is only the part with the IR sensors? This is important, since that other code might change the frequency at which the loop() function is executed and more.

is there any way? almost always has a yes answer ... in your program., you could send the state of the four sensors as bits of one byte ... use the four spare bits to signal a sensor state change

@chrisl Hello! For this system, I really just use 4 IR Sensors. However I am curious about what it does to the sketch if there are going to be more to the code than IR Sensors (Motors or actuators for example). How will it affect the frequency? For example if an IR Sensor (IRSignal1) is tripped then it turns a DC Motor (Motor1) for example as a response. While Motor1 is turning, one of the other IR Sensors (IRSignal2) was triggered. Will it trigger another DC Motor (Motor2) simultaneously or will it have to wait until Motor1 is done?

@fireblazer10 That depends entirely on how you program these actions, not on the sensor code, since that is already rather fast. You would need to write the action code in a non-blocking way, so that it doesn't block everything else. Though that is not specific to your sensor code, but a general programming paradigm

There are always other ways to code something (at least if it's non-trivial). What does 'efficiency' mean to you, in this case? If speed is a concern, increase the baud rate. Whenever at least one sensor is HIGH for longer than one loop iteration, the serial output time will be controlling. Other ways to optimize speed would be to put your loop code in an infinite loop inside either the loop() function or the end of the setup() function, saving the call and and return and function entry code of the loop function. Likewise, you can read the input registers directly and save the four calls to digitalRead().
But either of your Arduinos is more than fast enough (i.e., way faster than the phenomena it would be tracking), that there's little point in optimizing.
Update:

As for my second statement under my code about efficient coding practices, its about memory allocation, speed, and shorter code because what if in the future there's going to be a dozen of IR Sensors there, sill it still maintain speeds?

Even your Uno is still fast enough, with enough memory, to manage a dozen such sensors to the level of processing demonstrated in your supplied code - and then some!
However, I would already be thinking ahead to processing multiple sensors without multiple repetitions of your code, which brings up another kind of efficiency: the best use of your time.
If you kept an array of sensor data and looped over it, processing each sensor in turn, one set of code that works correctly once, will work correctly 'n' times. It will be more easily read by someone else (or your future self who, if you're like me, has forgotten some of the details), and it will be easier to fix or expand if you only have to get it right in one place instead of 'n' places.
Want to change what the terminal output looks like when your project has grown to 12 or 14 sensors? It's easy, when you only have to get it right in one place!
I'd be thinking about an array of sensor data containing, for each sensor, its pin number, present state, and any information that might be relevant in the future - sensor location, for example.
Depending on how you expand your processing, you could conceivably run out of speed or memory, but based on your presented code, that day looks a ways off. And you did mention there is a Mega standing by ...  :-)

as I understand the question OP wants to solve as first to print to Serial only if the state of the sensor changes

No device spec is given. The code as written properly detects and reports the 'triggered' state (apparently a LOW signal). If a state-change report is wanted, that was neither stated nor coded. I've answered the question that was asked - regarding efficiency. If the OP hasn't received the help he wants, editing his question to be more specific will elicit more specific help.

Oh apologies, I just realized that I haven't explained what efficiency means in the context of my post. I will edit it properly but what I actually mean is speed and making the code shorter. As for my second statement under my code about efficient coding practices, its about memory allocation, speed, and shorter code because what if in the future there's going to be a dozen of IR Sensors there, sill it still maintain speeds? But I am not sure if it warrants another thread for that?

As others have noticed, this code will be more than fast enough for
its intended purpose, so you should not feel obliged to optimize it
further. That being said, I do see an inefficiency that you may be
interested in hearing about, hence this answer.
If an IR sensor turns LOW and stays LOW, the program will send the
appropriate message repeatedly, as fast as it can. Since the code runs
way faster than the serial port, this will soon fill up the serial
port's output buffer. When this happens, Serial.print() will not be
able to put its message into that buffer anymore. Facing this situation,
it will switch from its regular non-blocking more of operation to a
different, blocking mode. In this mode, it will block the program
while waiting for the serial port to make some room in the buffer, and
only then will it put its message there and return. The end result is
that the program will be slowed down and match the speed of the serial
port: only 960 executions of the loop() function per second.
An interesting side effect of this situation is that, when the sensor
stops detecting some blockage, the Arduino will nevertheless continue
sending the messages that say that a blockage is detected. It will
continue doing so for about 66 ms: the time needed to empty the
63-byte serial output buffer.
If you are concerned about this issue, an easy way to alleviate it would
be to increase the baud rate. This will not change the qualitative
behavior, but it will make these things happen faster. I suggest you
consider to instead change the communication protocol you have defined
for the Arduino: instead of repeatedly sending information about the
current state of the sensors, it could send information about the state
changes. That is: one message is sent when a detector turns HIGH, and
a different message is sent when it turns LOW. Alternatively, it could
send the full state information (what sensors are LOW or HIGH)
periodically, or every time that state changes, or a combination of
both. I do not know what you are doing with this information on the
other side of the serial link, so I cannot say which option may be the
more appropriate for you.
You wrote in a comment that you may consider in the future driving a
motor instead of sending serial messages. If you go this way, you will
definitely have to work on state changes. In order to run
continuously, a motor does not require you to repeatedly press the “ON”
button a thousand times per second, and it will not turn off all by
itself just because you stopped turning it on. Instead, you turn it on
once and leave it alone, and it will stay on. When you want it to stop,
you have to actively turn it off. The turn on/turn off actions are
required only to change the state of the motor, not to keep the
current state.

The simplest way to do this is with digital interrupt, however the limitation here is that the standard Uno has only 2 interrupt capable pins (2,3) so it would not work with 4 sensors. However other boards like the ESP8266 support interrupts on nearly all pins (just needs ICACHE_RAM_ATTR declaration in the function called)
void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  //attach interrupts to trigger function on pin state change
  attachInterrupt(digitalPinToInterrupt(2), pinAtriggered, CHANGE);
  attachInterrupt(digitalPinToInterrupt(3), pinBtriggered, CHANGE);
}

void loop(){
}
//if using ESP8266 it would look like this:
//ICACHE_RAM_ATTR void pinAtriggered() {
void pinAtriggered(){
  Serial.println("triggered");
}
void pinBtriggered(){
  Serial.println("triggered");
}

Though on the Uno one could use the PinChangeInterrupt, which is available for way more pins.

It is generally a bad idea to Serial.println() from an interrupt service routine.


text:
74HC595 to 4 Digit 7 Segment using SevSegShift Library
I have a question regarding the use of SevSegShift library. I followed the example properly and tested it to see if it works. It was able to power up the seven segments and light up the whole LEDs (even the decimal) but it's not showing the output I want to show.
Based on the code below, I want to show the number 500 but it does not. Even tried sevsegshift.setChars("abcd"), no change.
This is my code:
#include <SevSegShift.h>

#define SHIFT_PIN_SHCP 6
#define SHIFT_PIN_STCP 5
#define SHIFT_PIN_DS   4

SevSegShift sevseg(SHIFT_PIN_DS, SHIFT_PIN_SHCP, SHIFT_PIN_STCP, 1, true);

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {9, 10, 11, 12}; // These are the PINS of the ** Arduino **
  byte segmentPins[] = {0, 1, 2, 3, 4, 5, 6, 7}; // these are the PINs of the ** Shift register **
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_CATHODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = true; // Use 'true' if your decimal point doesn't exist or isn't connected

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros, disableDecPoint);
  sevseg.setBrightness(10);
}

void loop() {
  sevseg.setNumber(500);
  //delay(1000);
  sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
}

This is my breadboard schematic down below.

(220 ohm resistors on the digit pins and the segment pins are connected to the shift register)

See the comment of the last statement. It says, don't use blocking code in the for loop e.g. delay() and one line above you use delay(). Hmmm, possibly ?! The shift register must be update very fast i guess.

@PeterPaulKiefer Thank you, that was an oversight on my part. Took out the delay() and still the same output :(

Did you connect +5V and Ground to the breadboard? Your schematic doesn’t show them.

@StarCat Yep! I'm sorry I forgot that part. Will edit it :D

OK, for me this was the most obvious possibillity of failure. But there are more. A brightness of 10 seems very low to me (max is 100). If you have COMMON_ANODE LED-Bars but you have configured COMMON_CATHODEs this would invert the brightness. Dark is Bright and Bright is Dark. Take this together and i might result in your observations. And probably the wiring is not correct. If you add a picture to the post we could check it. Btw. pin 12 can not provide PWM output (no ~ symbol), so it can not be used to regulate the brighness of the connected digit.

@PeterPaulKiefer That actually made a lot of sense! I changed it to COMMON_ANODE and set brightness to 100 so that I don't need to change pin 12. That helped a lot! The only problem now is that the display is showing in reverse and the decimal point is showing even if I set the disableDecPoint to true but I was able to fix that by reversing the digit pins and also setting disableDecPoint to false. I will put the updated code and also some picture output :D

swap the digit selection pins

Please forget the last sentence in my last comment. I've looked intio the lib code and they do not use PWM to control the brightness. Instead they use custom method the controll the brightness over the on and of time of an LED.

@PeterPaulKiefer, PWM wit 595?

@Juraj. If you controll the backpath (digit selector pins) it should work. Of cause the shift register can not be used for PWM ;-).  And yes, their custom method is far more clever then PWM. I have to admit.

@PeterPaulKiefer, PWM on digit selection pins? it makes even more less sense. only one digit can be lit at time. the redraw is fast lighting up digits one by one. the time between the redraws determines the brightness of the display

@Juraj As I wrote it is not a clever alternative but it depends an the speed of the PWM if it is possible or not. I admit, the idea of PWM is not the best one I had, and also it would be better if I try to think before I write. ;-)

hello i made this but i have question how we can turn on dots??

this program and wiring god but i cant find a way to turn on decimal point with numbers

Finally able to fix it with the help of @PeterPaulKiefer, I was able to find the problem. The problem is in the code itself (schematic is alright. No changes there) and this is the updated code.
#include <SevSegShift.h>

#define SHIFT_PIN_SHCP 6
#define SHIFT_PIN_STCP 5
#define SHIFT_PIN_DS   4

SevSegShift sevseg(SHIFT_PIN_DS, SHIFT_PIN_SHCP, SHIFT_PIN_STCP, 1, true);

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {12, 11, 10, 9}; // These are the PINS of the ** Arduino **
  byte segmentPins[] = {0, 1, 2, 3, 4, 5, 6, 7}; // these are the PINs of the ** Shift register **
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_ANODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros, disableDecPoint);
  sevseg.setBrightness(100);
}

void loop() {
  sevseg.setNumber(500);
  sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
}

What changed:

Turns out my 7-segment is COMMON_ANODE so I changed my hardwareConfig
Set brightness to 100
(At this point, it shows the number in reverse but with a decimal point in each digit)
Set disableDecPoint to false
(At this point, the display is showing but in reverse but no more decimal point)

To fix this, I set the digitPins[] in reverse and it now shows the proper format

Thank you so much Peter for helping me figure out what's wrong!
Also the LED Bar I use is 4-Digit 0.36" LED, 7-segments display, common-anode. (The link is to the shop I got it from)


text:
Unable to control fan with IR circuit despite capturing and reproducing the IR transmissions
I'm trying to use an Arduino to control my Bionaire window fan. I followed several guides to build an IR receiver circuit to record the patterns sent by the remote for its five buttons . From there, I've tried both an IR transmitter circuit with IRSendRaw and a separate Raspberry Pi circuit using an IR transceiver hat and LIRC , but the fan does not seem to pick up either. I've verified that the Pi receiver recognizes the commands from the Arduino transmitter circuit just as it does from the fan's actual remote and vice-versa, but even if I put the fan directly against the IR LED, it does not respond to any of the commands from the circuit.
What else might I need to do to make this work properly? As an alternative, what would be the best way to go about directly activating the 'buttons' on the remote circuit board pictured above?
Thanks in advance for your help
For future refernece, these are the signals I recorded for the remote, which match up with this post on electronics stackexchange.
power: 4E87E0AB
1300 -400 1300 -350 450 -1200 1300 -400 1300 -350 1300 -400 450 -1200 500 -1200 450 -1200 1300 -400 1300 -350 450
temp_up: 4EA240AE
1300 -400 1300 -350 450 -1200 1300 -400 1300 -350 1300 -400 450 -1200 450 -1250 450 -1200 450 -1250 1300 -350 1300
temp_down: 1D2FEFF6
1300 -400 1300 -350 450 -1250 1300 -350 1300 -350 500 -1200 1300 -350 500 -1200 450 -1200 500 -1200 450 -1200 450
mode: 39D41DC6
1300 -350 1300 -400 450 -1200 1300 -350 1300 -400 450 -1200 500 -1200 1300 -350 500 -1200 450 -1200 450 -1250 450
air_flow: E0984BB6
1300 -400 1300 -350 500 -1200 1300 -350 1300 -400 450 -1200 450 -1250 450 -1200 1300 -350 500 -1200 450 -1200 500

This is the sketch I'm trying to use to transmit data (just a modified version of the send raw demo from the library). Note that I also tried with only 23 items in the array (as originally recorded), but that made no difference:
#include <IRremote.h>

IRsend irsend;

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

}

void loop() {
  int khz = 38; // 38kHz carrier frequency for the NEC protocol
  Serial.println("Sending power");
  unsigned int irSignal[] = {1300,350, 1300,350, 500,1200, 1300,350, 1300,400, 1300,350, 450,1250, 450,1200, 450,1200, 1300,400, 1300,350, 500, 1200};
  irsend.sendRaw(irSignal, 24, khz); //Note the approach used to automatically calculate the size of the array.

  delay(1000); //In this example, the signal will be repeated every 5 seconds, approximately.
}

EDIT to show that I seem to be able to replicate the real signal.
In the following output from the IRecvDump2 example, the top two signal dumps are from the real remote and the bottom two are from my RPi sending the recorded signal. They're very slightly different, but seem (to me) to be within the variation of the recording of the true signal anyway.
What else could I be missing? Could there be some brightness threshold such that even holding the Pi directly up to (i.e. touching) the fan receiver wouldn't work? Some other sort of wake-up signal that for whatever reason the Arduino isn't recording/receiving?
Encoding  : UNKNOWN
Code      : 4E87E0AB (32 bits)
Timing[23]:
     +1300, - 400     +1300, - 350     + 450, -1200     +1350, - 350
     +1300, - 350     +1300, - 400     + 450, -1200     + 500, -1200
     + 450, -1200     +1300, - 400     +1250, - 400     + 450
unsigned int  rawData[23] = {1300,400, 1300,350, 450,1200, 1350,350, 1300,350, 1300,400, 450,1200, 500,1200, 450,1200, 1300,400, 1250,400, 450};  // UNKNOWN 4E87E0AB

Encoding  : UNKNOWN
Code      : 4E87E0AB (32 bits)
Timing[23]:
     +1300, - 400     +1300, - 350     + 450, -1250     +1300, - 350
     +1300, - 400     +1300, - 350     + 450, -1200     + 500, -1200
     + 450, -1200     +1300, - 400     +1300, - 350     + 450
unsigned int  rawData[23] = {1300,400, 1300,350, 450,1250, 1300,350, 1300,400, 1300,350, 450,1200, 500,1200, 450,1200, 1300,400, 1300,350, 450};  // UNKNOWN 4E87E0AB

Encoding  : UNKNOWN
Code      : 4E87E0AB (32 bits)
Timing[23]:
     +1350, - 350     +1300, - 350     + 450, -1200     +1300, - 350
     +1300, - 350     +1300, - 400     + 450, -1200     + 450, -1200
     + 450, -1200     +1350, - 350     +1300, - 350     + 450
unsigned int  rawData[23] = {1350,350, 1300,350, 450,1200, 1300,350, 1300,350, 1300,400, 450,1200, 450,1200, 450,1200, 1350,350, 1300,350, 450};  // UNKNOWN 4E87E0AB

Encoding  : UNKNOWN
Code      : 4E87E0AB (32 bits)
Timing[23]:
     +1350, - 300     +1350, - 350     + 450, -1200     +1300, - 350
     +1300, - 350     +1350, - 350     + 450, -1200     + 450, -1200
     + 450, -1200     +1300, - 350     +1350, - 350     + 450
unsigned int  rawData[23] = {1350,300, 1350,350, 450,1200, 1300,350, 1300,350, 1350,350, 450,1200, 450,1200, 450,1200, 1300,350, 1350,350, 450};  // UNKNOWN 4E87E0AB

Those codes look way to short to me. They also don't seem to include a preamble. Could you tell how you got those signals codes?

I got the signals from the IRRecvDump2 example in the Arduino-IRremote library.
I thought the signals looked odd as well, but I found one other post in the EE stack exchange where someone had recorded the same signals.
I am using the IRSendRaw example from the same library to send from the Arduino and lirc's irsend when sending from the Pi

Updated the main post with my sketch @jsotola

there is another thing to try ... if you have access to a learning IR remote ... use it to learn one of the fan remote control buttons and confirm that it can control the fan ... next use it to learn the arduino non-working signal .... then use the arduino to record the learned code .... compare it to the original recorded values

one other thing you could try .... set all the timing values to what the controller IC datasheet shows   ... the two values are 1266 μs and 422 μs   .... the trailing gap should be 6752 μs ... so 1300,350, 1300,350, 500,1200 ... should be 1266, 422, 1266, 422, 422, 1266 ... and the very last 1200 should be 6752

Thanks for the suggestion. I don't have a learning IR remote at the moment, but I can get one at some point.
And ah, I didn't think of that for the last gap. I guess I figured that since it was 'off' that just having no signal afterwards would be sufficient (and why the signal got recorded the way it did).

Your code assumed that C1 and C2 bits are set to 1, but according to the EE stack exchange link, those pins are float, and therefore should be consider as '0' instead of '1' as shown in your irSignal data.

@jsotola Unfortunately, changing the intervals to align exactly with the spec didn't seem to help.

@hcheung I saw that, but if that's what my arduino recorded being sent by the remote, then shouldn't that be what I send to the fan?

is your device actually outputting IR? ... check with your phone camera

Yes. I checked with my camera and, as I said, also tried using one of pi/arduino to transmit and the other to read and both directions recognize the signal.

is there a difference between a signal captured from the remote control and a signal captured from the second arduino?

The IRecvDump2 output is the same when I send the recorded signal from my Raspberry Pi

Interesting question with a lot of paths. I know nothing about your controller but in working with IR remotes in the past I found almost all IR remotes use the infrared frequency range (300 GHz - 400 GHz). This range should not be confused with the modulation rate (carrier frequency) of the remote control. The remote control codes are sent to the receiver using the modulation rate. The modulation rate for the remotes and set top boxes is between 36 kHz and 60 kHz, typically 36 kHz to 39kHz. Try this link it may be a bit redundant but it may help. http://www.pehratek.com/documents/FAQ-Infrared-Light-Control.pdf

I think you meant 300Ghz - 400Ghz.

@Gil There is no link in your answer. Maybe you forgot it

Sorry, I should have clarified: I'm using IRSendRaw example from the Arduino-IRremote library to send, so the 38 KHz modulation should be handled.

Sorry I am not familiar with that example or library.  Sorry Gerben I hit a K instead of a G, thanks, I changed it.

@Gil  gHz is gram hertz   ... it should be GHz


text:
What's the best way to operate a remote control circuit board?
What would be the best way of using an Arduino to operate the pictured remote control circuit board? My initial instinct would be to leave the batteries in the remote and use a separate transistor for each of the five switches, connecting wires (solder or electrical tape) to the two sides of each button and the base to an Arduino output pin. I'm certainly not an expert, so I wanted to confirm whether (a) that would work and (b) if there's a much better way. The control is normally powered by two AAA batteries.

Edit: There's also a small capacitor on the underside of the circuit board, if that changes anything.

Thanks in advance for your help
Note: I've tried to simply record and emit the IR signals from the remote using my Arduino, but have thus far been unsuccessful, so want another way of using the Arduino to control my fan: Unable to control fan with IR circuit despite capturing and reproducing the IR transmissions

All the right sides of the buttons are connected to the negative of the battery (that is ground). So you connect the remotes GND to the Arduinos GND.
Next solder five wires to the left side of the buttons. You can do this by scraping away a bit of the green solder mask that's on top of the trace going to that button pad. Or find out which pin on the IC goes to the button, and solder a wire to that leg.
I wouldn't mess with the black stuff (graphite?) on top of button pad. That way you can always return the remote to it's original function.
Then connect those wires to the Collectors of NPN transistors. The Emitters all connect to GND. The Bases (via a resistor) to the Arduino pins.
Alternatively, you can connect them directly to the Arduino pins. But you'd have to be careful to never set the pin to HIGH, as the remote won't like 5V on it's input pins while it is itself running on only 3V. You "press" the button by setting the pin to OUTPUT. After a "press" you set it back to input.
To prevent accidentally supplying 5V to the button pin, you can also use diodes (instead of transistors described above). Put the diode between the Arduino pin, and the button wire, pointing towards the Arduino. That way current can only go towards the Arduino. Then you can safely use digitalWrite.

Thanks so much for the detailed response @Gerben! I don't have time to wire it up tonight, but plan to tomorrow.
Also, I can't believe that I forgot this before, but there's a capacitor on the underside of the circuit board (added a picture to the main post). Does that change anything?

No. The capacitor is across the batteries. It smooths out the voltage.


text:
Arduino auto power of circuit possible issue with higher voltage agains output pin?
I've use the following circuit to be able to shutting the my Arduino down after some time of it not being used:

I'm now concerned that while you press the button to turn on the Arduino, the 9V from the battery can flow directly to the PIN X (one of the digital pins of the Arduino configured as output). After the Arduino is started the PIN X will be set to high, to keep the Arduino running when the button is released.
Is this a problem which I need to solve? And if yes how. The finished project is intended for a child, so I assume that the on button can be hold for a long time just as it is funny to press on the button. The circuit itself is running fine.
As a possible solution I thought to add a diode between the junction after the R1 and the PIN X. Would this be an ok solution?
The circuit is not my own invention I've found it here: http://educ8s.tv/auto-power-off-arduino-simple-circuit/

adding a diode would stop the 9v from hitting the pin. the uno also has internal resisters that act as a gate de-flap.

Having 9 volts reaching pin X through R1 is indeed a problem, one that could destroy transistors in the pin's IO structure.  The problem is mentioned in some comments following the video, but no solution is mentioned there.  Presumably users of the circuit usually get away with ignoring the problem because it is one of short duration:  A few milliseconds after the MCU starts up, it sets pin X to +5 V, which then leads to 4 V at 40 μA being dropped harmlessly across R1.  (Note, R1 is 100KΩ rather than 100Ω, per video and its notes.)
One approach to guard against the problem is to place a 5.3–5.7 V zener diode from ground to pin X.
Another way is to use a better and more capable on-off circuit, a Pololu Pushbutton Power Switch #2808.  This costs about $4, and is rated for operation from 2.2 V to 20 V at up to 6 A.  The board is about 15x18 mm and has a small pushbutton on it, but you can parallel a momentary switch of your own if you like.  The pushbutton toggles power on or off.  The board also has control inputs called On, Off, and Ctrl, with the first two turning the board on or off.
A big advantage of the #2808 switch is its current draw is small (less than 0.1 μA) when switched off.  The circuit illustrated in the link has close to 0.5 mA draw when off, which is enough to run a battery down in a few weeks.

That electronic power switch board looks like an interesting idea; hopefully it solves not only the input voltage problem, but the more permanent leakage path self turn on one.

Thanks for the response, I've seen the Pololu Solution when I was searching for circuit to solve this issue. I've did not order it as the shipping cost was around 20$ to my country and I have the the risk of additional import taxes on top of it. And this for a 4$ component :-( And the lokal distributor does not carry that part. This was the reason I've wen't with the other "solution".
Not the best decision in hindsight :-(

ok, had another look on the page, and found a distributor in Germany which also sends to my country. Ordered now the board and also a stepup voltage  regulator to solve the other issue with powering the arduino board by battery.

@Chris, that's good.  Note, the #2808 is ok with low voltages (2.2 V to 20 V) and the #2809 with medium voltages  (4.5 V to 40 V).  Power-on indicator LED is red on #2808, and I think draws some 200 μA/V when the unit is on (eg 1–1.2 mA at +5V), and is green on #2809, drawing ca. 100-120 μA/V when the unit is on.  You can remove the LED if that power loss is a problem.

Yes I will remove the led, need to to the same on the uno as well.

No.  It is not possible for a modern IC such as an MCU having I/O protection diodes to enable/disable its own power using a single external N-Channel or P-Channel device.  The reason is that the path broken by the single switch ends up being partially completed through I/O pin's internal protection diode and your pulldown resistor, and depending on the voltage drop that results across that, partial turn on the FET itself.  This is enough to have the processor at least partially on - perhaps not enough to operate, but enough to keep consuming battery, and in some cases also enough to make clean startup on manual operation of the power switch unworkable.
To make this work, you need two stages of switching - two fets are a possibility.
However another easy one is to use one of the USB power switches chips intended to be included in the rarely seen "full" USB hubs that have software control of the downstream ports' power.  These are hardly ever fitted in the hubs sold, but they exist as a part, are easy to apply, typically have low leakage, and are often specified to operate correctly both substantially below and somewhat above the 5v they would see in a USB application.  Most importantly, they are multi-stage solutions in a single package - typically they function as high side switches, but they are enabled by an input going high, and as result, they do not suffer the parasitic partial turn on issue via the MCU's protection diodes in the way that a high side switch enabled by an input going low would.  I believe the RT9701 that I used in the past to do this with an ESP8266 is officially discontinued, but still available and likely replaced by newer similar parts.
Given your input voltage, another thing to consider would be using a regulator with an active-high enable input.  But realize that a linear regulator is an inherently wasteful device, and a lot of the compact switchers don't have very high input voltage allowance.

Just out of curiosity do you know a place where there would be a circuit of such a dual FET solution? I would like to learn how it works correctly.
The RT9701 look interesting, but I'm not yet ready to solder smd components. And I was only able to find it in smd configuration.


text:
What is the most memory-friendly way to declare integer literals?
I'm having SRAM overflow problems with my 8bit atmega328p in my Arduino Uno, which has 2KB of SRAM, so I'm defining all my for loops with bytes as counters instead of ints. As in:
for(byte i=0;i<16;i++) buf[i]=(char)ap1[i];

Would it make any difference if I declared the integer literal 16 as a constant?
const byte BUFSIZE=16;

Or using the preprocessor:
#define BUFSIZE 16

There's also the macro PROGMEM which stores variables in flash memory, which I've decided to use for all my constants, but is it not the point of const to do this? as well as aiding the compiler in warning you if you screwed up changing the variable.
const byte BUFSIZE PROGMEM=16;

AFAIK, using const would save BUFSIZE in the flash memory, but how about using the preprocessor? Using the preprocesor would be the exact the same as using the literal 16, as far as i'm concerned.
This fear arose from the fact that string literals are saved in Flash and then transferred to SRAM, wasting twice the space, which you can solve using the arduino macro F("thisisastring"), which stores them in flash memory, and I don't want to waste 2 bytes of SRAM in every for loop I use

The compiler should optimise out any constants into the most compact form possible. Take a look at the assembly code if you're curious.

Well, it's easy to just try and see... Let's try the following program:
#ifdef USE_CONST
const byte BUFSIZE = 16;
#else
#  define BUFSIZE 16
#endif

char buf[BUFSIZE], ap1[BUFSIZE];

int main(void)
{
    for (byte i = 0; i < BUFSIZE; i++)
        buf[i] = ap1[i];
    return 0;
}

I compiled this for an Uno both with and without #define USE_CONST,
and it doesn't make any difference! avr-size reports the same sizes for
both versions, and the generated assemblies are identical: the optimizer
transformed the loop into something like
byte *Z = ap1;
byte *X = buf;
do {
    *X++ = *Z++;
} while (Z != ap1 + 16);

where X and Z are two of the CPU's pointer registers, and ap1 + 16 is
an immediate constant, i.e. part of the instruction itself, c.f. the
AVR addressing modes.
It is worth noting that, in C++,
const implies internal linkage.
Thus a const global variable is very much like a preprocessor constant.
This is unlike C, where you would need to qualify the variable as
static const in order to get the same behavior. Otherwise the compiler
would need to allocate storage to BUFSIZE, just in case it is
referenced as extern from another source file, even though it can
replace occurrences of BUFSIZE in the same file with its immediate
value.
On the other hand, the Arduino IDE compiles your code with
-ffunction-sections -fdata-sections
and links it with
--gc-sections,
which means the linker will eventually get rid of the unused reserved
storage.

Yes, defining "const byte bufsize" would make a difference - it'll use one additional byte of SRAM. All variables are stored in RAM unless they're annotated as being PROGMEM.
A #define gets translated into its value by the preprocessor, and so looks the same to the compiler.
Your constant '16' isn't taking up any SRAM in the first place; look elsewhere (at actual variables) if you need to optimise.
String literals are treated the same way as arrays of any numeric type: they're copied to SRAM on startup because the code has to be able to dereference the pointer (which is what myarray[x] does) and find the location in RAM. Single numeric constants do not have this issue - they're value types - and so don't get copied into RAM.

It's actually slightly worse. The const byte is first stored in flash by the compiler/linker, and then during the preamble it's copied to SRAM. So you're taking twice the hit needlessly.

Did the test: you are actually taking zero times the hit, not twice.

At higher optimization levels of course (for a given definition of "higher").


text:
Advice on cabling, packaging and connectors for 12v light project
My project is to have a 12V solar LED strip lighting system throughout my apartment. This has 6 individual lights, with 5 white and 1 RGB = 8 channels.
I've got the whole setup working on my breadboard. Now it's time to transfer it to a "live" setup. Since it's my first such project, I'm looking for any and all recommendations on cabling and connectors to deal with reliability, isolation, modularity, aesthetics and of course safety.
Schematically, it all looks something like this
solar panel------\
                  charge controller--5v regulator--arduino--mosfets x 8--\__lights
12v battery_fuse_/                  \____________________________________/

So I have questions such as:-

should I use a prototype shield, or a discrete pcb?
do the MOSFETs (RFP30N06LE) need a heatsink, and any recommended unit?
what connectors are recommended?
any suggestions on box/packaging for the above?
wire gauge? Maximum run is 4m to the furthest light.

And any other hints, tips and suggestions greatly appreciated. Bonus appreciation for amazon links to the parts :-)
update
The breadboard is simply the mosfets, each with a current limiting resistor on the gate. The lights range from 8W to 40W. I will generally have them dimmed using PWM.

Can you share what you have on the breadboard, and particulars about the current draw, etc?  Those are the kinds of details you'll need to attract useful answers.

if the proto board isn't warm it's fine if not mobile. 2. not unless way under-driven or over-loaded (small binder clips can double TO220's dissipation) 3. "terminal connectors" or solder. 4. dollar-store decorative box/container/lunchbox, or box-store outlet box 5. 18AWG or lower (thicker) is fine; aka "alarm", "doorbell", "speaker", "18/2"

@SDsolar question updated. thx

generic DC connector advice:
avoid the use of connectors which connect serially, like headphone jacks. you make strange combinations while plugging in
avoid connectors which do not latch, like headphone jacks
in a system like yours, with stages and signal processing in between, use different connectors for each phase, so you can not get it wrong
use connectors that can not be connected backwards for DC. I prefer:
Hopkins 47965 2-Pole Flat Extension for raw solar power.Not because    it's a great connector, but because it's common in low power solar

Anderson Power Poles for regulated DC power. you can secure them
together with a tie wrap; you can't connect them backwards without
doing things that are obviously counter intuitive.
Fuel injection    connectors from Autozone for signal wires. they got
a million of    them, they are made for DC at useful current levels
Trailer    connectors for multiple lead serious power.
XLR connectors can be    found from 3 to 6 pins, and you can't jam a
5 pin into a 6 pin, so    you can't cross connnect

keep things dummy proof.


text:
MQTT (was WiFi) interference when using two nodeMCU devices
I have two nodeMCU boards, one from LoLin (192.168.1.52) and one from Amica (192.168.1.53). For each nodeMCU, I have mapped its MAC address to a fixed IP address using my Movistar WiFi router. I confirm from the serial monitor that each nodeMCU is being correctly assigned to the correct IP address
My sketch is a simple IoT/MQTT client.
My problem is that if I power up both nodeMCUs, the WiFi connection is broken on both.
The WiFi portion of my sketch is
void setup_wifi() {
  Serial.println(" Booting..");
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, PASSWORD);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    myBlink(LED_PIN, 20, 100);
    delay(5000);
    ESP.restart();
  }
  WiFi.printDiag(Serial);
  Serial.println(WiFi.localIP());
}

The output is
Mode: STA PHY mode:
N Channel: 1
AP id: 0
Status: 5
Auto connect: 1
SSID (13): MOVISTAR_xxxx
Passphrase (20): 509A8EC4Exxxxxxxxx
BSSID set: 0

192.168.1.53 (or .52 on the other device)

I realise that the symptoms are consistent with clashing IP addresses, but to confirm, both the serial diagnostics and the DHCP report from my router confirm that the two devices are on different IP addresses.

I realise that the symptoms are consistent with clashing IP addresses - how do you figure this, since they each output a different IP address - try staggering the power up times - does the problem persist? try having the units further apart - does the problem persist?

My bad!
Although my symptoms were consistent with WiFi interference, the interference was actually at the MQTT level.
The root cause was that I hadn't realised that each MQTT client must have a unique client ID. When the 2nd nodeMCU connected, it disconnected the first nodeMCU from MQTT, which then went into a reboot sequence to recover, which then returned the favour to the other nodeMCU.

I can only do that after 24 hours. Thanks for the hint to the solution.


text:
Serial not displaying sketch for MPU6050
I followed this tutorial on youtube: https://www.youtube.com/watch?v=M9lZ5Qy5S2s
Where he provided the code below. The problem I'm having is the serial monitor shows nothing. I tried changing the baud to 115200 and still nothing showed up. I'm using an Arduino nano.
Update: I wrote a Serial.print in each function (printing the name of the function), and I found it just printed up to "recordAccelRegisters" then stopped. Then I put a Serial.print after each line in the function, and it prints until the line
while(Wire.available() < 6);
Is this a problem with the while function or I2C?
Ok, so I reinstalled Arduino and got this message on the serial print with the I2C test:
"Scanning... I2C device found at address 0x69  ! done."
#include <Wire.h>

long accelX, accelY, accelZ;
float gForceX, gForceY, gForceZ;

long gyroX, gyroY, gyroZ;
float rotX, rotY, rotZ;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  setupMPU();
}

void loop() {
  recordAccelRegisters();
  recordGyroRegisters();
  printData();
  delay(100);
}

void setupMPU(){
  Wire.beginTransmission(0b1101000); //This is the I2C address of the MPU (b1101000/b1101001 for AC0 low/high datasheet sec. 9.2)
  Wire.write(0x6B); //Accessing the register 6B - Power Management (Sec. 4.28)
  Wire.write(0b00000000); //Setting SLEEP register to 0. (Required; see Note on p. 9)
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x1B); //Accessing the register 1B - Gyroscope Configuration (Sec. 4.4)
  Wire.write(0x00000000); //Setting the gyro to full scale +/- 250deg./s
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x1C); //Accessing the register 1C - Acccelerometer Configuration (Sec. 4.5)
  Wire.write(0b00000000); //Setting the accel to +/- 2g
  Wire.endTransmission();
}

void recordAccelRegisters() {
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x3B); //Starting register for Accel Readings
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6); //Request Accel Registers (3B - 40)
  while(Wire.available() < 6);
  accelX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
  accelY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
  accelZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
  processAccelData();
}

void processAccelData(){
  gForceX = accelX / 16384.0;
  gForceY = accelY / 16384.0;
  gForceZ = accelZ / 16384.0;
}

void recordGyroRegisters() {
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x43); //Starting register for Gyro Readings
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6); //Request Gyro Registers (43 - 48)
  while(Wire.available() < 6);
  gyroX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
  gyroY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
  gyroZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
  processGyroData();
}

void processGyroData() {
  rotX = gyroX / 131.0;
  rotY = gyroY / 131.0;
  rotZ = gyroZ / 131.0;
}

void printData() {
  Serial.print("Gyro (deg)");
  Serial.print(" X=");
  Serial.print(rotX);
  Serial.print(" Y=");
  Serial.print(rotY);
  Serial.print(" Z=");
  Serial.print(rotZ);
  Serial.print(" Accel (g)");
  Serial.print(" X=");
  Serial.print(gForceX);
  Serial.print(" Y=");
  Serial.print(gForceY);
  Serial.print(" Z=");
  Serial.println(gForceZ);
}

https://github.com/VRomanov89/EEEnthusiast/blob/master/MPU-6050%20Implementation/MPU6050_Implementation/MPU6050_Implementation.ino

I put a serial.print in the first line of each function. It stops after recordAccelRegisters

tried http://playground.arduino.cc/Main/I2cScanner same problem

Got it. I used the address from the I2C test and everything looks great. Guess I'll have to do this for any cheap modules I get on ebay :)

Ground the AD0 pin. I thought the address should be set to 0x68 without this, but from what I've seen it fluctuates between 0x68 and 0x69. If you want the address to be 0x69 short the AD0 pin to 5V. I guess this would be useful if you need to use 2 MPU6050s with different I2C addresses without doing something in software. Haven't looked into that yet
Still, the I2C scanner for arduino may be useful for detecting the address/debugging: http://playground.arduino.cc/Main/I2cScanner


text:
How to define SoftwareSerial pins on ESP8266
I'am new to arduino yun and ESP. In fact, i have an arduino yun which has a sim808 dfrobot shield on it which uploads GPS data online at a regular time interval.
I want to connect the dfrobot sim808 shield to esp so that the latter will send the data online thus making the system low cost by not using the arduino yun
#include  <DFRobot_sim808.h>
#include  <SoftwareSerial.h>
#include  <Console.h>

#define PIN_TX    10
#define PIN_RX    11
SoftwareSerial mySerial(PIN_TX, PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

I want to know which pin on the sim808's TX and RX pin should be connected to the ESP8266 like define above, pin 0,1 are used by the yun for Wifi connectin so pin 10 and 11 are used. . By the way, I am currently using ESP8266 12E nodemcu. Please help me with that.