text:
ESP-01 does not run code after Deep Sleep
When using the deep sleep functionality on several ESP-01 boards, the boards require two resets in order to wake up properly (regardless of whether the resets are done by manually bridging the rst pin or by soldering a wire to do it from an interrupt). The boards do wake up and print some text automatically, but they do not run their firmware/code.
#include <ESP8266WiFi.h>
void setup() {
    Serial.begin(74880);
    Serial.print("\n--------------STARTING----------------\n");

    //pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    //digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off (gpio @ high= off)

    delay(500);
    ESP.deepSleep(2000000, WAKE_RF_DEFAULT );
}

void loop() {
}

I have not been able to just wake the board and run the code like most examples on the web intend to work, so I suppose the problem is not with this code.
On a successful wake up, the serial output looks like this:
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld

--------------STARTING---------------

After the first reset, the board does indeed wake up, but it does not run it's code. It only prints this
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

And then hangs there. After another reset, it successfully runs it's code.
This issue persists across all the esp 01 boards i own, and i have tried pulling UP and DOWN almost every combination of pins recommended. The line that is printed in the fauly cases does indeed say it is booting in the right mode, but still the code does not run, nor mine nor the one that runs before mine

Had you tried ESP.deepSleep(2000000); instead of ESP.deepSleepInstant(2000000, WAKE_RF_DEFAULT ); ?

@fabiuz7 yes, i tried deepSleepInstant to test if it had any different results from deepSleep, with no effect

Are you using this board ? It seems not exposing the pin 16, required to make the deep sleep working.  https://www.mouser.it/ProductDetail/SparkFun/WRL-13678?qs=WyAARYrbSnZdmwzlRTs1Tw%3D%3D&vip=1&gclid=Cj0KCQjw3Nv3BRC8ARIsAPh8hgJygBYf_pJV_0gmP_mQjns1tsS1YFMyzQ1WgaypqsutPeeVbyJw27caAmcNEALw_wcB

I've tested your code on a Wemos D1 mini and it works as expected

@fabiuz7 pin16 is actually needed to wake the chip from deepsleep. I mentioned in my post that i have the issue when resetting manually as well as from an interrupt.
For example, if i don't connect pin16 i have to manually reset twice. If i connect that pin16 to the rst pin, i still have to reset manually once.

GPIO16 provides the Reset signal after wake. The GPIO16 pin needs to be connected to RST. This is difficult with the ESP-01/ESP-01S module, as the GPIO-16 is not exposed, nor is it connected to the RST pin on the board. Big bummer. Connecting GPIO16 to RST on a ESP-8266 module with all the pins exposed does work. I was also able to connect the GPIO16 on my ESP01 to Reset and it also works.

Yeah, i'm sorry but i specifically described that i got weird behaviours even when using the RESET pin. This default answer of "oh you just didn't know to solder a wire" is what made me go insane at the time, because it's repeated like a mantra even to completely unrelated issues.

What sasso is describing is classic Deep Sleep Zombie mode. There's someone else here with ESP-01 boards with the same issue.  I'd bet you got your boards in blister packs from Inland.  I didn't see any ESP-01 boards from Inland at my local computer store, only ESP-01S, and that one works with Deep Sleep just fine.  I only bought the one for a test.  I believe it's the Flash chip, but we haven't proven that yet.  I have plenty of Winbond flash in case I find a board that goes zombie, and can prove or disprove my theory.  I have 8 different types of boards and modules, and all come out of Deep Sleep correctly.
edit: If the pic at Ali is correct, the Puya Flash shouldn't be causing an issue, presuming it's real and not a clone.  Half the time the pics are only 'representative examples' of what they ship.  The ESP8266 Arduino core has supported Puya for a while now.  Also, on sober reflection the Inland package I bought said ESP-01S, and it's actually an ESP-01 (false advertising).  I looked closer and didn't see the pull-up resistors. :-(
If you're powering it from that USB programmer board, it should work.  If you have a separate 3.3V supply, I'd be suspicious of the supply.  The current spikes as the ESP is booting will cause many switching supplies to drop below 2V briefly, and the ESP goes insane.  Without having a zombie in front of me, I'm at a loss to go a lot further as my 'scope leads aren't that long.

Thank you very much for answering, the fact that almost no one ever aknowledged this problem around the net was driving me crazy. I got 8 boards from aliexpress from china, none of them works after deep sleep. I recentrly tried ordering a couple more to see if it was an hardware issue or not. Let me know if you need any info on the boards i got

Do you have the ali link, or a very good photo of the top of the board so that I can read the ID on the Flash chip?  I suspect it says T25S80 (supposedly Bright Moon Semi) which you can also get by doing Serial.println(ESP.getFlashChipId(), HEX); after you've started the serial port.  I get 14605E with what I think is a Bright Moon chip, although the manufacturer ID doesn't match their datasheet.

https://www.aliexpress.com/item/32834727685.html?spm=a2g0s.9042311.0.0.4c334c4ddxlsF5 this is where i got them, the  ESP-01S  variety

Any update about that one @KrazyOldGuy ? I have the same issue with a ESP12F from aliexpress. FlashChipId is 1660C4 for me (but i cant have a look at the flash chip because there is a metal cover on the board.


text:
What happens if I don't open the USB serial port of Arduino Pro Micro / Leonardo?
My question is related to this one. My sketch seems to stop responding after some time if I run it with debug enabled and I don't open the serial port/monitor on the computer.
Does the UART buffer fill up and block or something? Or, does it discard the excess data and keep working?
I can't find information about it.

In the avr hardware serial implementation, a write/print command will block until there is room if the buffer is full. My guess is that USB serial would act the same.

In your other thread I suggest a way of testing the Serial port periodically to see if it is available.

As far as I can see from CDC.cpp it attempts to see if the USB is available and if not, do not write anything but set the "write error" flag.
size_t Serial_::write(const uint8_t *buffer, size_t size)
{
    /* only try to send bytes if the high-level CDC connection itself
     is open (not just the pipe) - the OS should set lineState when the port
     is opened and clear lineState when the port is closed.
     bytes sent before the user opens the connection or after
     the connection is closed are lost - just like with a UART. */

    // TODO - ZE - check behavior on different OSes and test what happens if an
    // open connection isn't broken cleanly (cable is yanked out, host dies
    // or locks up, or host virtual serial port hangs)
    if (_usbLineInfo.lineState > 0) {
        int r = USB_Send(CDC_TX,buffer,size);
        if (r > 0) {
            return r;
        } else {
            setWriteError();
            return 0;
        }
    }
    setWriteError();
    return 0;
}

This is the same test as is done in operator bool() without the 10 ms delay.
// This operator is a convenient way for a sketch to check whether the
// port has actually been configured and opened by the host (as opposed
// to just being connected to the host).  It can be used, for example, in
// setup() before printing to ensure that an application on the host is
// actually ready to receive and display the data.
// We add a short delay before returning to fix a bug observed by Federico
// where the port is configured (lineState != 0) but not quite opened.
Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

Judging by the comments above, this may not be the most reliable thing in the world.

The whole CDC/ACM system has a fundamental flaw in that there is no way of knowing if the port has been opened - you can only examine the line states (DTR and RTS) to see if something the other end has asserted those lines.  On some operating systems those lines are asserted by default (though that behaviour can be disabled) and on other operating systems it's left to the whim of the software that opens the port. The whole arrangement is very hit-and-miss, and it's for precisely that reason that FTDI developed their own proprietary protocol instead of using CDC/ACM.

At least on Windows 10 Serial starts to return 'true' when the COM port is open and keeps returning 'true' no matter you open or close it. So if you close it the output buffer may full up and block forever on write calls. I gave it other power source and now I can see disconnecting the USB cable makes Serial to return 'false' and connecting it back and opening the COM port again makes it 'true' again.

@Majenko How can I examine the DTR of Serial on Arduino Pro Micro?

@aalku if (Serial) - that's what it does.  It examines the control line states. But of course it's down to the remote end as to what that actually means.

@Majenko Well, you can't trust it. At least on Windows 10. If DTR is signaled write should not block as far as I know, and it does. That can't happen in a hardware serial port. You write and if the other end can't listen the data is lost.

source: Stack Exchange

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

sort: votes


text:
Inappropriate ioctl for device
I am using an Arduino Uno and a Mac and trying to upload my code into the board.
I tried uploading the program from different computers(MacBook Air and Pro) and I still have this problem.
How do I fix this? I tried downloading the FTDI driver. I went to the website that they suggested and tried following the instructions. I even followed other posts in Stack Exchange but I still cannot upload the code.
EDIT
Programmer -> AVRISP mkll
I am using a cable to connect to my Mac and I am using the Arduino software. The cable connected between the Arduino USB and Mac USB port.
I tried quitting and relaunching Arduino app. Once it launches I just press the upload button while my USB is plugged in. My available ports in the app are /dev/cu.Bluetooth-Incoming-Port and /dev/cu.Bluetooth-Modem
And this is the error
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1421": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

Please edit question and add following info:  How the Uno is connected to Mac, including name or model number of cable or whatever, and what connects where.  The program you used and the commands you entered to upload the code.  If you are using arduino ide, what options you selected, eg which port, which programmer, programming mode.  URL of "the website they suggested".

Better, but please add the other info requested.  The problem will be something simple but if people don't know what you have or what you did, then their answers are just guesses.  What options did you set?  What buttons did you click? What's selected at Tools/Port ? at Tools/Board ? What is each end of the programming cable plugged into? What's the cable? (Eg say if it is a USB A to USB B micro, connected to a USB port on Mac and USB on Uno)

Tried running your arduino as a root user?

yes. But i have the same error

Your question is unclear.  Are you trying to program the Uno through the Uno's on-board USB interface, or are you trying to program it through a hardware programmer?

i don't get you. Sorry i am just a beginner

I think @Majenko is asking if you are using a plain USB cable vs some add-on programmer board.  From your latest edit, I assume you use a plain USB cable.  I don't know much Mac stuff but it looks to me like port setting is wrong – Bluetooth is totally not relevant to this USB cabled connection.  See Getting Started w/ Arduino on Mac OS X which says to use a port like /dev/tty.usbmodem or  /dev/tty.usbserial

Also see Mac OS X usbmodem ports missing?, a lengthy discussion of ins and outs of getting  usbmodem ports to show up on Mac

Did any of the answer help you to resolve your issue? If so, could you mark the answer that helped you the most as "accepted"?

Plug your Uno into the Mac using a known good USB cable.
Go to the Apple menu -> About This Mac -> More Info -> System Report
Under the USB selection (on the left) please confirm whether or not you see something like this:

You can also open a Terminal window and type:
system_profiler SPUSBDataType

Amongst other things you should see:
USB:

    USB High-Speed Bus:

      Host Controller Location: Built-in USB
      Host Controller Driver: AppleUSBEHCI
      PCI Device ID: 0x3b34
      PCI Revision ID: 0x0006
      PCI Vendor ID: 0x8086
      Bus Number: 0xfd

        Hub:

          Product ID: 0x2514
          Vendor ID: 0x0424  (SMSC)
          Version: 0.03
          Speed: Up to 480 Mb/sec
          Location ID: 0xfd100000 / 2
          Current Available (mA): 500
          Current Required (mA): 2

            Communication Device:

              Product ID: 0x0043
              Vendor ID: 0x2341
              Version: 0.01
              Serial Number: 9314036423335121A0B1
              Speed: Up to 12 Mb/sec
              Manufacturer: Arduino (www.arduino.cc)
              Location ID: 0xfd130000 / 8
              Current Available (mA): 500
              Current Required (mA): 100

Note the "www.arduino.cc" entry.
In your Arduino IDE you should see the Arduino as a tty.usbmodemfd131 (or some similar number).

If you see all that it should work.
If not, please state in what way it differs.

Programmer -> AVRISP mkll

The Tools > Programmer menu selection is only used when you do Tools > Burn Bootloader or "Upload Using Programmer. It is completely ignored when doing a standard "Upload". You should be doing an "Upload" (Command-U) not an "Upload using programmer" (Shift+Command+U). So it makes absolutely no difference what you select from the Tools > Programmer menu.

I solved this problem.  Maybe this post will help others.
I've come across this problem a couple of times.  I literally searched for hours for the answer and ended up using several suggestions.
Both scenarios I solved are documented below as 'Scenario A' and 'Scenario B':
======================
Scenario A
Plugged in a new Arduino Uno R3 board, successfully compiled the standard "Blink" sketch.  When I tried to upload it to the board, I got this message:
Sketch uses 1,066 bytes (3%) of program storage space. Maximum is 32,256 bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes. avrdude: ser_open(): can't open device "COM1": No such file or directory ioctl("TIOCMGET"): Inappropriate ioctl for device Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
The Port Options in the IDE (Tools--> Port) only showed  /dev/cu.incoming-bluetooth-port
Here's what worked:

Downloaded and Installed the CH340 driver
Removed the FTDI drivers from my mac.  Apple recently installed a new utility that prevents removal of what it considers to be critical components.

The process that enforces this rule is called csrutil.
You'll have to disable this process to remove the FTDI driver.  Then you'll need to re-enable it when you are done.  This required a restart in recovery mode.  Here's how to do that:
a.)  power off the mac then hold 'command'+R during the restart until the image of the apple appears.
b.)  when the screen refreshes, click on 'Utilities' menu then 'Terminal.
c.)  type csrutil disable
d.)  Hit enter
e.)  Restart  [Note:  You may be able to execute the next two commands in the terminal before restarting.  I just didn't test it that way.  If the system will allow you to, then by all means run all three commands one after the other THEN restart and you should be on your way.]

remove the FTDI drivers by opening the terminal program again and entering the following command:
   sudo rm -R /System/Library/Extensions/AppleUSBFTDI.kext

Type in your password when prompted.

Restore the apple csrutil by following steps a and b above.  Task c will be the same EXCEPT you'll type this instead:
csrutil enable

Then follow steps d and e.

When you restart the arduino IDE, you should see a more comprehensive list of ports besides just the bluetooth port.
======================
Scenario B
This board was an import and clearly not an original Arduino/Genuino.  Attempts to load sketches resulted in this lovely error:
    Using Port                    : /dev/cu.usbmodem1421
    Using Programmer              : arduino
    Overriding Baud Rate          : 115200

avrdude: ser_open(): can't open device "/dev/cu.usbmodem1421": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device
There was only one Port listed in the IDE, dev/cu.Bluetooth-Incoming-Port.
It had been a while since Scenario A had occurred and since then I'd installed a few OS updates.  Checked the drivers and low and behold, the darned FTDI drivers had RETURNED!!
I repeated the steps in scenario A above but the problem remained.
Then I installed an updated board configuration from arduino and it worked!  Testing on the first board I'd used under scenario A were successful as well.  Here's what I did:

In the IDE go to Tools-> Boards -> Boards Manager
I installed 'Arduino SAM Boards (32-bits ARM Cortex-M3) by Arduino version 1.6.8
Unplugged and replugged the USB cable into my arduino.
In the IDE go to Tools -> Port.  The /dev/cu.usbmodem1421 was listed as a port option.  Selected that.
Uploaded my sketch.
Bask in glory of SUCCESS!

I hope this was helpful to you.  I spent two days on Scenario A and 3 hours on Scenario B.

Warning to future testers, after installing that driver whenever I plug my arduino it freezes my mac and I have to restart

I got this error on my Macintosh system and the problem was that I needed to choose the correct port on the USB. Somehow it had auto-connected to a Bluetooth port which was listed under Tools->Port as /dev/cu.Bluetooth-modem and was my daughter's cell phone. I chose a port labeled /dev/cu/wchusbserialfd... and it worked fine.

I've also had this error message when I've left another serial terminal connected to the same port the Arduino IDE is trying to use.

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

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


text:
Arduino Due and BNO055 address in i2c mode
I have a project where I need to have several IMUs, the BNO055 shuttle board (I explained my project here), I manage to get the Euler angles from one BNO055 sensor, which have the address 0x29, because I linked the I2C_MODE_ADR_SEL to a HIGH level.
I would like to have another sensor with the address 0x28. As the datasheet says, I must link the I2C_MODE_ADR_SEL to a LOW level (to the GND) the i2c Scanner from the Arduino Playground does not recognize any i2c device.
I don't know how to change my sensor address, can anyone help me with this issue ?

I've built MotioSuit, a mocap suit based on the BNO055 which currently has 9 sensors but could go up to 18.
https://hackaday.io/project/9266-motiosuit
The sensor board and library are open-source and documented in the link, I hope it helps!

You might mention that it uses multiplexing using the TI http://www.ti.com/product/PCA9548A chip and  https://github.com/bqlabs/I2C-multiplexer code.

Wow sorry, I've just seen it. Indeed, it is all explained in the text linked. Just to clarify, that is a fork from https://github.com/alvaroferran/I2C-multiplexer which I actually wrote for that very project :)

Oops.  I missed that you were the author of the interface code. I was looking for BN055 code got distracted by the hackaday project and skipped to google to find the BN055 code.  Thanks for the links.

No worries, glad it was useful :)

According to Table 4-7 on page 90 of the BNO055 datasheet at adafruit.com, the BNO055 supports three I2C addresses: 0x28 or 0x29 in slave mode (selected by COM3 being low or high, respectively), or 0x40 in the HID-I2C configuration.
According to the diagram on page 2 in file BNO055_Shuttleboard_Flyer.pdf (Bosch's description of the BNO055 Shuttle Board), COM3 on pin 17 of the BNO055 (or, PSERCOM3) is wired via 0Ω jumper R106 to the middle pin of J102.
If you plan to get data from five different BNO055's, you may need to use a multiplexer (or several I/O's) to set COM3 on one BNO055 board to a different level than on the other four, to select one of the five boards for access.  For example, you could use a 7438 (eg, an MM74HC138 or DM74LS138).  When you set the 7438's address input to j, line Yⱼ (from among Y₀ to Y₇) will go low while the the other Yᵢ remain high.  The BNO055 with COM3 attached to Yⱼ then would be the only BNO055 that would respond to I2C address 0x28.
For testing, you could set up several BNO055's and use several separate I/O lines to control several COM3 inputs.  Using separate I/O lines takes five I/O lines for five COM3's, vs three I/O lines using a 7438 multiplexer; saving two lines might not be worth the extra effort of obtaining and using a multiplexer.
Another approach is to use two more Arduino (eg Pro Mini or Micro) units to support separate I2C busses for additional BNO055's.  These auxiliary Arduinos could do some data reduction before sending data (via serial or I2C) to the principal Arduino.
Note, it is not clear to me that using more than one or two BNO055's makes sense.  If the assemblage of BNO055's moves through space more or less as a unit, but with attitudes, roll rates, etc differing between BNO055's, then 3/4 or so of the data from different BNO055's will be the same.  Possibly less-general sensors (eg, without magnetometer) with different I2C addresses could be used instead.

The project aim to monitor the movements of the upper limb. For the moment I want to monitor only one arm I just need 3 sensors (One on the arm, one on the forearm and one on the chest), so I don't need a multiplexer. My problem is I can't get the sensor working when I put a low level on the pin that select address. I tried wiring it to the GND, or on a digital pin of the Arduino, that send a low level, and everytime the i2c scanner does not detect the sensor.

I would recheck (with a meter or scope) that pin 6 PS0 and pin 5 PS1 are low, and that pin 17 COM3 goes low or high as you connect or disconnect it from ground, and also would try reading at address 0x28 even if the I2C scanner doesn't see that address.  Which I2C scanner program are you using?

I use this one http://playground.arduino.cc/Main/I2cScanner

I checked with a scope, the PS0 and PS1 are low (0V each), and COM3 is at 3.3V when connected to the source and 0V when connected to the ground. I read that maybe I should use pull up resistors, would i be useful in my case ?

No pullups needed.  See p. 89 of BST_BNO055_DS000_12.pdf, table 4.6 which says COM3 has an internal pullup, typ. 40K.  Note, after table 4.4 it says “It is not allowed to keep the protocol select pins floating” ie the PS pins should be tied high or low.  Have you tried using address 0x28 with only one BNO055 connected up?

Yes, I tried with only one BNO055. I tied the PS pins to the GND everytime. I managed to use two BNO055 at the same time, one on the second I2C input (SDA1, SCL1) and 1,5kOhms pull up resistors (at the address 0x29), and the other one on the regular I2C (PIN 20 and 21). Again, it only works with the address 0x29.

Although this is an older question, I believe there may be people still looking for a solution to this problem. Documentation for the BNO055 Shuttle board is pretty thin. I've added a bit of the schematic below.
BNO055 Com3 (pin 17) is presented on pin 22 of the shuttle board (12C_MODE_ADR_SEL). This pin must be connected through a resistor either to shuttleboard pin 4 (SD0, GND) or to shuttleboard pin 5 (SD1). The datasheet makes mention of 2-position jumper J102 which should accomplish this, but there are versions of the Shuttle board that do not include this jumper or any place to mount it. In the photo of the OP's setup (pasted at bottom in case his link goes away) the jumper header would be installed across the three holes adjacent to pin 3 (GND), and jumping the center pin to the left or right-side pin would set the address to 0x028 or 0x029.
If you don't have the jumper, just connect the pins directly: when I connect pin 17 to pin 4 through a 10K resistor, the Arduino "example" scanner does see it at I2C address 0x28.
Personally I like the Adafruit BNO055 board a lot better than the Shuttle -- it has a voltage regulator and a lot of other additions, and it uses 0x028 as its default I2C address.
For those working in the Arduino code environment and wishing to incorporate more than two BNO055 devices and who do not wish to use a multiplexer, I might suggest looking at the Teensy family of 32-bit ARM cortex CPU boards. These are completely code-compatible with Arduino, but offer more than one I2C bus. In fact the Teensy 3.6 (180 MHz!! with 1M Flash, 256K Ram, 4K eeprom, an FPU) offers four* separate I2C Wire interfaces on different ports, which would permit 8 of the BNO055 devices to be used.
I've personally been very happy with the performance and functionality of the Teensy boards when used with multiple BNO055 devices.


text:
How to blink LED's unsynchronized?
I'm new to Arduino. For my first project,  I want to make aviation strobe lights. My challenge is to use ONE Arduino to blink both sets of lights. My issue is,  I DON'T want them to be synchronized. I saved a sketch of the blink example from the Arduino IDE software after editing it to do what I want. But, the LED's are synchronized. One LED strobes twice,  while the other strobes once as I want them to. However, they begin their loops together currently and stay synchronized,  which isn't what I want.
So my question is: What is the code I need to write to make each LED blink unsynchronized from the other without having to use 2 Arduino units?
Code:
int led = 11;
int led2 = 12;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop() {
  digitalWrite(led, HIGH);
  delay(50);
  digitalWrite(led, LOW);
  delay(1000);
  digitalWrite(led2,  HIGH);
  delay(50)
  digitalWrite(led2, LOW);
  delay(100) ;
  digitalWrite(led2,  HIGH);
  delay(50)
  digitalWrite(led2, LOW);
  delay(1000);
}

Could you post your current code?

That code is only for one led. You said you got things working for two LEDs.

OK,  I fixed it to reflect what I've got.

The Arduino Blink example uses delay() to pause the Arduino in a specific state, so that for a specific amount of milliseconds the device will keep the blinkPin HIGH or LOW.
Instead of using a delay(), you should use millis(). The main advantage of millis() over delay() is that it does not interrupt the code. When you call a delay() the whole code pauses, nothing can be done during those milliseconds. But millis() doesn't work that way. You also don't call it the same way as delay().
What millis() does is that it stores a timer value into an unsigned long. At a later point in time you can substract a new millis() from your previously stored millis in the unsigned long. The result is a difference in time between each millis() in milliseconds.
Now, instead of using only one unsigned long, we use two different ones: one for each LED. Now you can log a time interval, independently, for each LED. Furthermore, if you apply the logic of millis() for keeping the LEDs on or off, you don't have to interrupt the code with delay() functions. This means, that regardless of each LEDs state (HIGH or LOW), the timer keeps running, keeps logging and thus can control both LEDs simultaneously.
To give you a bit more information on millis(), below are some references that will get you started in how to implement. If you have more questions, just comment on this answer :)

millis() reference on the Arduino website
Blink without Delay example

Using the millis function call is generally always better than delay.  However it is more complex to use the millis functions as the developer needs to understand a different variable type (unsigned long) as well as consider what happens when the millis function wraps around (however infrequent). I think, in this case, using delays for the time base and counters that do not over flow for any variable type makes for an easy to explain and simple to implement answer to the question.

Although more complex, it allows for much more functionality on a device. Simply more than one thing can be done without completely disrupting the code. I never use delay() anymore, except when it is the only way to process some stuff (for example with a WiFi chip or Serial communications where short delays are sometimes needed to simplify the code). Anyway, millis() is amazing and delay() is not, haha.

You need to implement a pair of LFSRs, one for each LED. This will give a result that eventually repeats, but with registers of differing lengths and the correct polynomials it won't repeat quickly enough for it to matter.

But then OP would have to implement finite filed arithmetic for polynomials on an adruino for implementing an LFSR.

The article gives a couple of sample implementations in C that strictly use bit operations. It's not as complex as it sounds.

It is not possible to escape the fact that both LEDs will be driven from a common clock.  However, it is possible to arrive at a convincing solution where the LEDs appear to be unsynchronized.  What is necessary is a rather fast event loop and rather large numbers which are not quite multiples of one another. As an example consider a loop with a delay of 10ms and two counter which will count up to 100 and 51 respectively.  Each time the counters reach their goal their respective LED is toggled and the counter is reset to zero.  One LED will appear to turn on off on with a period of about 2 second.  The other LED will turn on off on with a period of about 1 second.  However, over time,the second LED will start to trail the first.  Giving the appearance that they are not synchronized.
You can use any numbers you wish.  Edger suggested in the comments to use golden ratio numbers 144 and 89.
If you want to emulate the short burst of strobe lights you need to alter the suggested design (which provides a 50% duty cycle) to something that provides, say, a 10% duty cycle.
Let's adapt your code from above.  Add 2 counters one each for LED1 and LED2.  Define numbers for the period of LED1 and for LED2. Also define a number for the length of time the LEDs will be on for.  Notice that we only need one 10ms call to the delay method. All counters are incremented each time we enter the loop method.  Since our delay is 10ms we enter the loop method 100 times a second.  Inside the loop method we keep track and cap the counters at their predefined limits.  When we get close to those limits we turn on the appropriate LED.  When we hit the limit we turn off the appropriate LED and clear that LED's counter.
// What is the period of led 1 in 10s of milliseconds.
#define LED1_PERIOD_10MS 144
// What is the period of led 2 in 10s of milliseconds.
#define LED2_PERIOD_10MS 89
// How long to keep the LED on in 10s of milliseconds.
#define LED_ON_TIME_10MS 10

int led = 11;
int led2 = 12;
unsigned int count_led1;
unsigned int count_led2;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);

  count_led1 = 0;
  count_led2 = 0;
}

void loop() {
  count_led1++;
  if(count_led1 == LED1_PERIOD_10MS - LED_ON_TIME_10MS)
  {
    digitalWrite(led, HIGH);
  }

  if(count_led1 > LED1_PERIOD_10MS)
  {
    count_led1 = 0;
    digitalWrite(led, LOW);
  }

  count_led2++;
  if(count_led2 == LED2_PERIOD_10MS - LED_ON_TIME_10MS)
  {
    digitalWrite(led2, HIGH);
  }

  if(count_led2 > LED2_PERIOD_10MS)
  {
    count_led2 = 0;
    digitalWrite(led2, LOW);
  }

  // Delay 10ms.
  delay(10);
}

I have only proof read the above code.  If you find any problems make a comment below and I will make the corrections.

So,  how would I write the code to achieve the counter reset? Basically,  what I've got is:

This answers your question.  However, it's worth noting LEDs lack the ability to simulate incandescent light bulbs as they have little thermal inertia. In order to simulate this you might consider programmable LED and slowly bringing up the down the brightness.  You can also use a normal LED and the Arduino's PWM feature to control the brightness.

The code isn't difficult.  In your Arduino loop method increment each number and test one for, say, greater than 100 & the other for, say, greater than 51.  If the test is true toggle the pin connected to the respective LED and zero out that counter.  Then you need to call a delay, say, 10ms.  The loop method will be called over and over again as this is part of the Arduino design.

Oh,  Ok.looks like it's gonna be a bit of tinkering to get the desired result. No problem,  as it helps me learn.

The strobes I'm making are based off the xenon high intensity strobes. 2 white wingtip strobes,  and 1 red belly strobe. LED's will do perfectly for what I'm doing.

Instead of 100 and 51, which is almost a factor 2, I would probably try something close to the golden ratio, like 144 and 89. The golden ratio being in some sense the “most irrational number”, it should provide a feeling of completely unrelated frequencies, instead of the “slowly drifting synchronization” you would get with 100/51.

Strobes?  Then using LEDs as is should get you the desired attack & decay.  I imagined you were trying for rotating beacons.  Then a slow attack and delay would look good.  Also, my solution creates a 50% duty cycle.  To emulate a strobe you need a much shorter duty cycle.  Say 10%.  Which would require the code to get a bit more complex.  For some reason, good answers for this question are getting down voted.  So, unless you ask for it, I'm not going to invest time to add an example of a 10% duty cycle to my answer.

@st2000, if I was shooting for a rotating Beacon,  I would just use fade in and out. Of which I did try with my wingtip blink code,  but the problem I run into with the fade in and out,  is that once the code initializes,  the led to fade fades in,  and stays on. Never fades back out. I tried changing pins to see if it was just the pins being too close... But the problem persisted. I would most definitely love to know your example. I have not been down voting anything. I am actually going to try all suggestions to see which one works the best.

The fade code example from here looks like it should work.  Make sure you are flipping the sign of the variable fadeAmount when you reach 255.  Copy and past the example so you know you didn't make a typing error.


text:
Is my atmega2560 schematic correct?
I'm designing a custom board with an atmega2560. It will be programmed using ArduinoISP. I want to be sure that i have made no mistakes on my schematic design before I order it. I folloud the schematic for the arduino mega 2560 from the arduino website. For the basic function of uploading a sketch is my design correct?
I can upload the full schematic on pdf if you need it but it just contains some ICs for the final board.
This is the pcb design as asked in the comments!

You want us to evaluate a board you've designed but won't show us the gerbers? How are we supposed to be able to answer that?

I would be happy to show you the "gerbers" if I knew what they are!

They're what you send to the board house in order to have them actually make the board. Load them into a viewer and post the images here.

Oh you mean the pcb design. I dont find a reason to post it because its just the schematic on a board but if you need it I will...

You need to read AVR042.

I don't have much time but from a quick look on the example layout maybe i have a problem on decoupling my gnd/vcc pairs but i think its covered by the 3 caps in series. Although its not a big mistake to correct.

Atmel recommends to have one decoupling cap per VCC/GND pair, and to place it as close to the pair as possible.

Your ground paths leave a lot to be desired.  Flip C1 and use a ground pour.

for the basic function of uploading a sketch your board schematics is indeed correct and going to work.
I can't say much on the PCB as what you have posted is a partial design, in particular it doesn't show the solder mask expansion and other details which might greatly influence the final result.
Please also note you don't need a reset button, a voltage regulator nor an external oscillator for the basic function of uploading a sketch, but I believe you also want to have the ability to run the sketch without the programmer being attached...

Thank you very much. I actually do want it to run without the programer and the PCB is indeed partial as the final design will have lots of junk stuck on it. But thanks anyway, really helpful!

You don't need the crystal on the very first upload. However, once you have programmed the fuses to have the AVR clocked off the crystal, you will need it for any subsequent upload.

@EdgarBonet you are right, but he might also decide to program the fuses so the internal 8MHz oscillator is used... It really depends on what he wants to do with it.
I have my own designs running at 3.3V 8MHz internal in order to trim down costs.

See the schematic and the PCB design in the question: there is a crystal with matching caps connected to XTAL1/XTAL2. I would make little sense have that crystal and program the fuses to use the internal RC oscillator.

@EdgarBonet I am saying the crystal is not mandatory.... you say the cristal is needed with certain fuses, I say the fuses can be changed and you get back to the presence of the crystal?!?
I am saying the crystal is OPTIONAL and I agreed with you it would than require a proper setting on the fuses. Going back to the schematics makes no sense whatsoever to me.

@FrankF. then if your design involves specific analog stuff than there is space for improvement: a proper analog reference and separating the decoupling capacitors for digital and analog lines would improve the quality of your analog readings.

@RobertoLoGiacco I'm going to use the external oscilator and I'm going to use a bunch of analog lines. I'm actually attaching 3 CD4051B analog multiplexers for 24 analog lines but i don't actually need perfect quality. Although, connecting a single decoupling capacitor on each gnd/vcc pair instead of 3 to all of them would improve anything?

To improve your analogRead you should decouple AVCC-AGND separately from VCC-GND, so, depending on your requirements, 220nF capacitance on each of the two separate lines might do.
A big boost in analogRead quality would also come using an external precision reference voltage rather than using the internal reference.
I haven't read the CD4051B datasheet though, so take my comment as a general advice rather than a specific solution.

Well thank you but I'm not going to change anything. I really don't need all this presition as my project is a dj controller. Here are my complete schematics and grebers.


text:
Can't upload to Arduino UNO (kuman UNO)
I am trying to upload my code to my new Arduino (Just got one today, so im very new).
I can compile my code with no problems, but uploading it gives me:
[Arduino: 1.6.11 (Mac OS X), Board: "Arduino/Genuino Uno"

Sketch uses 1,186 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
chmod: Unable to change file mode on /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: Read-only file system
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: Permission denied
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: exec: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: cannot execute: Undefined error: 0
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: exec: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: cannot execute: Undefined error: 0

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

It doesn't matter what i upload (tried to upload some of the examples).
As said i am very new, so if you need any more information to help me just ask.
Thanks in advance!

Please format your question appropriately. In this case the big block you copy-pasted here should be contained within a code block (the button with two curly brackets {})

Drag Arduino.app out of your ~/Downloads folder to /Applications or anywhere else that isn't where you downloads it to. The app is being subjected to Gatekeeper Path Randomization which means it is running on a read-only file system. The app is trying to chmod something inside the app bundle and thats not possible on a read-only file system.

Thank you! I didn't know that this was a thing ;)

Check your port to which your arduino is connected. The port name can be checked from Arduino IDE. Click Tools -> Port -> There you can find the port name.
Open Terminal and type the following command.
sudo chmod 777 /dev/port_name

After this try to Recompile/Upload the code again.

i ran sudo chmod 777 /dev/cu.usbmodem1411. Still same problem.

Are you sure? You are using correct port name?Try dmesg | grep tty
to list all Serial Device Converter

Try to run your Arduino IDE with super user privileges,  because the  compilation log shows most of the errors are related to inadequate rights of writing/executing on files.

I ran sudo /Users/madsankernielsen/Downloads/Arduino.app/Contents/MacOS/Arduino and now it won't even compile it. Am i doing it right?


text:
Arduino controlled remote for an rc car. What am I doing wrong?
I have an Osepp Mega 2560 (Arduino Compatible) which I'm trying to use to run a RC Car from the remote control.

Can someone please explain how do I need to connect the pins from Osepp to the remote board.
The setup (please look at image for bolded details):
 - Osepp 5v Power pin going to the Positive (see red wire)
 - Osepp GND pin going to the Negative (Black wire)
 - Osepp Pin 13 (pwm) going to the signal to drive forward (bottom of the board).
The Code
int led = 13;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
}

void loop() {

  digitalWrite(led, LOW);
  delay(10000);
  digitalWrite(led, HIGH);
  delay(10000);
}

The Problem
I expect that after 10 seconds the remote will start sending a signal to move forward.
In actuality the signal gets sent right away, even though the pin is set to LOW.
The "signal to drive forward" spot where I soldered a wire from pin 13 is where power gets sent once you press down the joystick (also highlighted in the pic) and complete the circuit.

FYI
I am not trying to do any modulation, pin 13 may have been a poor choice.
I do not have any kits nor manuals, just winging it
The joystick for the forward action is actually suppose to be top left(missing in this case but you can see the circuit) and not the one highlighted in the picture

So you have it wired, but you want to know how to create a PWM signal?

Yeah, this is a confusing question... please provide more detail about what your pin is connected to, include the code you think is driving that pin, why you think it should be PWM, and why you think it's not. If you're connected directly to a motor, PWM might act as a simple DC speed controller, but you're gonna need some code to do that, and the concept of ON and OFF and HIGH and LOW no longer apply. Makes me think you're using the wrong code.

Also, if you're working with a specific kit, please provide a link to that kit, and page numbers or something to indicate the step you're having trouble with, from the manual of said kit.

Thanks guys, I am writing up more details. Remember to look at the picture. On the step i mentioned "Osepp Pin 13 (pwm) going to the signal to drive forward"  In the picture you'll find the "signal to drive forward" mark on the circuit board where I'm connecting to

Why does it look like the top-left (button removed) pad is connected to the "move forward" pin. And from that, it looks like it gets pulled to ground when the button is pressed.

You're right, that is the pad for move forward. Any thoughts on how to connect it to the Arduino?

Totally the wrong code. Why did you think the "Blink" code would run an RC car? That code is for blinking an LED - that's what it does. It doesn't do something else. The "Blink" program does not send a PWM signal down the line. If your device expects a PWM signal, this code won't do anything reasonable.

OH also... this is more of a "project" than a "question" and it may be more appropriate to use the Arduino forum. http://forum.arduino.cc/

My logic here was:
The joystick completes that portion of the circuit when pressed so I measured how much power goes through the circuit into the microcontroller pin when the joystick is pressed. Pin 13 delivers roughly the same voltage when set to HIGH so I assumed that by 'enabling' the pin (setting OUTPUT = HIGH) you would deliver that much power. One would expect that. However, to my surprise, the power is always there regardless of the state of pin 13 (HIGH or LOW) so my question is why? and how can I control that?

Eh... well, you're getting confused pretty badly here. Power, voltage, and current don't really work that way. If you send too much current through your Arduino pin, it's gonna fry that pin and probably the ATmega chip too. We need to work this out on the forum, this isn't something we can give you a quick answer for. You need an intro to microcontroller electronics first. Have you done all the little projects in the starter kit? You really need to do those... I've been doing this stuff for 30 years and I loved this kit - https://www.youtube.com/watch?v=pf4qosqpv3A

If you go to the Arduino Forum, I will help you, along with the rest of the community. I've done videos to help people with things on there - that's how much we care.

ok I will check out the kit and then come back to update the question and perhaps move it to the forum if it's still unclear. Thanks

Added to the Arduino forum http://forum.arduino.cc/index.php?topic=241237.0      Thanks

As this has now been asked and discussed on the Arduino forum, and the original question is not very clear, I am going to close this question. I'm going to close this question. Thanks for your understanding and cooperation!


text:
Persistence of user input after reboot
I am creating an application where user input is required. After a user browses through available choices (via buttons and LCD) depending on the choice of the user a function is run from several available.
When the user reboots the Arduino, it starts from the default function, making the user reselect the choice they want..
Is there a way to have persistence of the choice of the user after a reboot?
So that, when a user makes a selection, after a reboot, the arduino will have this selection (=the function that corresponds to this selection) by default.
Maybe if the user input (the buttons) write to an EEPROM or something like this? So that the arduino reads the value from the component?
If such a solution exists, due to limitations i would like to have only one wire for communication with the device.
EDIT: I am using Arduino Due

Better than that: Zero wires.
The Arduino has EEPROM built in.

I forgot to mention i am using Arduino Due

The Arduino due has flash memory based EEPROM emulation built in.

I searched for it... Do you mean this: https://github.com/sebnil/DueFlashStorage

Ok, maybe the due doesn't have it as default (lazy buggers, all the other larger boards do), but yes that looks like it should plug the gaping hole Arduino left in the due.


text:
Running a 7 pin OLED with 4 pins (I2C)
I have an OLED with this 7 pin pinout:

I want to use an existing code i found that makes use of U8Glib.
But in the example, use uses 4 pins to control the OLED via I2C.
This is the pinout he uses:

Is it possible to control my OLED via 4 pins and use U8Glib to simplify my project by making use of the example code i found?
EDIT: Here is also a picture of the back of the OLED PCB that mentions how to use IIC but i do not understand it!

That looks like it may be an SPI interface, not I2C, so no. You can't.

Unless of course U8Glib has an SPI example for that board. I assume it's an SSD1306? Most small OLEDs are...

Looks configurable to I2C / 3-wire SPI / 4-wire SPI depending on the presence / absence of R1-R4.

This page has the answer to your questions. For reference:

Setting up SPI/I2C Connection with GMS096A OLED Module
Being a new entry to the market, only limited resources are available
  on this small piece of miracle (GMS096A). I2C/SPI configuration always
  demands helpful resources as in any case. For the SPI setup, the
  module comes in 4 wire SPI configuration by default and to make it
  work with the arduinos you can use these libraries from Adafruit.
For the I2C setup it demands a little bit of work on the module.
  Actually it was one of our customers who shared these simple
  configuration steps with us, start with resoldering the resistor from
  position R3 to R1 and then short the R8 resistor with some solder tin
  (0 Ohm resistor). The R6 and R7 pullup resistors are already soldered,
  nothing to do there. Once done, the module is ready for I2C
  communication! The CS Pin is not necessarily needed, so just connect
  it to GND. The DC Pin selects the address. For standard address wire
  it to GND. The RES-pin needs a low pulse at startup and high voltage
  during operation (as in SPI mode), a 100nF capacitor to GND and a 10k
  res to VCC would be ideal!

Your module might differ sightly. But you should be able to figure it out from there. The pulse on the RES-pin needed at startup took me a while to figure out!

Yes, it works IIC as described above, with my Arduino MEGA.
You can also connect RST Pin at Arduino RESET signal, so no need of extra R and C components

That is a SPI interface. Often the CS is missing, but you seem to have that pin. I suggest to start with the software PCI mode of the U8Glib.
This is the best explanation that I can find: Github: SSD1306 based OLED connected to Arduino
Would you consider using the newer U8g2 library ?
It is easier to use with Arduino boards that have more memory. But it has also the same mode for low memory usage, just like the U8Glib.

Is it possible to control my OLED via 4 pins and use U8Glib to simplify my project by making use of the example code i found?

i'm sure somewhere there is an i2c->spi bridge. if not, you can always code your arduino to behave like one.
short of that, you can simply code to control the board via spi.


text:
Bluetooth distorts analog read?
I'm working to make a simple pedometer with Arduino, and after managing to find an algorithm that correctly finds the steps, I added a bluetooth extension (the overly popular and cheap JY-MCU) to check the steps via bluetooth.
I am facing a strange issue, though: when the bluetooth device is powered and waiting for a connection (red led blinking) the analog read function that reads data from the accelerometer goes crazy (thus the pedometer finds a step each second or so). When the bluetooth is powered down or connected to a device such as a mobile phone this doesn't happen.
Did anyone have this problem before? What could be the issue? My setup is easy, you can see it on the image.

I had other sensors as well but since the problem stays even when there are only those two connected I posted the bare minimum setup.
At first I thought I could use some kind of pull-ups to stabilise the signal, but I really have no idea on where to tie them and if they can really be helpful at all...
Any help is appreciated.

Try placing them further apart. Also use two separate wires to power the two modules (which you are probably already doing). If all that fails, try powering the ADXL from 3.3v. If this fixes thing, it means there is some coupling issue.

Yes, the common red line of the drawing is in reality the long "+" line of the breadboard, and two different wires go to BT and ADXL. Powering either of the two with the 3.3v out doesn't help either (originally my idea was of powering the BT with one of the out pins because that way I could control when powering on and off the BT, but for the sake of resolving this issue I momentarily switched to the common rail of power).  The only "fix" is when I power the BT with an external battery (which, as you say, it means there are coupling issues)...

Try adding a small value cap between AREF and ground. Who knows.

Please add an analysis of the power budget. How much current can the 3.3V pin on the Uno supply? How much does the BT require (on peak)? Etc. You need to always do the numbers; hardware and software.

You can try decoupling the power for the bluetooth:

The resistor value should be tiny - 10Ω is a good value to use - don't go much higher than that.  The capacitor should be nice and big - I have shown 100µF, but bigger is better - whatever you have that's nice and big.  (Make sure you wire it the right way round - check which pin is marked as -)  You might also want to add a small capacitor (say 100nF) in parallel with the large one.

It seems it is not working. At first I thought it was, but I had some code wrong. I'll try again and keep you posted.

Decoupling should be the right solution because when I connect the bluetooth to an external battery it gives me no problem. I just have to figure out why I can't decouple it correctly!

What size components are you using? I only guessed the values in the drawing, it may take some adjustment. Try smaller resistor, or replace the resistor with an inductor.

I tried capacitors up to 1000micro, and the resistor as suggested 10 ohm. I'll see if at home I have some smaller resistors or an inductor

Just one question: I managed to find a 2200µF capacitor and tried that as well. But I noticed that it's a 6.3V capacitor. Could the voltage difference be an issue and the reason why decoupling does not work? Do I have to find a 5V one maybe?

@Luca No. You need a capacitor whose voltage is above the voltage you are using - 6.3V is perfect.  The voltage rating of a capacitor is the voltage above which it is liable to explode.

@Luca Oh, one other thing - the resistor and capacitor will cause a delay in the powering on of the bluetooth module. The bigger the capacitor the longer that delay will be - you may want to reduce the value of the resistor to compensate (but not too much or you will risk exceeding the USB inrush current rating) and/or add a delay to the start of your program to allow the capacitor to charge up.

Yes, I noticed the delay and I though that it would more or less be the usual 0.69RC, isn't it? I really don't care about the delay as long as I get it working... Which still doesn't, and I'm beginning to get a little frustrated because I'm sure that the capacitor charges since it powers the BT for some fraction of a second if I try to disconnect the circuit from the main power source...


text:
Issue with CD74HC4067 MUX on high values
I'm having a small issue with the CD74HC4067 multiplexer/demultiplexer: I am using it to receive data from an array of sensors (at the moment I have only 2, but in a near future they will grow). Specifically I have a light sensor and a sound sensor.
Mux output is connected to A0 since the readings I do are analog. The pins I use to switch the channels are A3 and A2 (when the other sensors will arrive also A1 will be dedicated to that).
My problem is that when switching between one channel and another, my readings highly fluctuate, but only when the reading value is > 500 or so, and I don't understand why. In a simple sketch I've tried adding some delay (40 msec) and the issue goes away. But in my project which is far more complex and uses also other analog channels I need a delay of ~1 second to get a correct reading, which is absolutely unacceptable since I need it to run in real-time(ish). I also tried using the digital pins to control the mux but to no avail. The only thing that seems to stabilize everything is connecting a capacitor between the MUX out and ground, and using a 20msec delay, but it only works for a bit.
I hope I've been clear enough and that someone can point me the right way!
EDIT:
Here is the schematic

(Error in the drawing: "temp" is actually a "light sensor" as in the bottom of the post...)
And my code:
#define MUX A0
#define S0 A2
#define S1 A3

void setup() {
  Serial.begin(9600);
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);

  selectMux(1);
}

void loop() {

  //selectMux(0);
  //Serial.println(analogRead(MUX));
  //selectMux(1);
  Serial.println(analogRead(MUX));

}

void selectMux(byte port) {
//  pinMode(MUX, mode);
  int r0 = bitRead(port, 0);
  int r1 = bitRead(port, 1);

  digitalWrite(S0, r0);
  digitalWrite(S1, r1);
  analogRead(MUX);
}

the analogRead(MUX) in the selectMux function was added because I read in a post that they suggested to do that in order to get a more accurate reading.
With this code only the results already fluctuate:
Output:
76
41
77
76
76
75
36
75
74
76
77
106
76
76
76
76

but it goes crazy when the input is higher, close to 5V:
Output:
948
780
340
948
948
635
437
949
948
499
551
949
950
396
684
950

If you enable the commented code that starts to switch the outputs it is even worse. As I said, adding delays helps, but in my final application I cannot afford to have 1s delays.
I also show that in the circuit there is a timer that uses other Analog pins, but in the code I didn't include that part. If you need I'll add that too.
Sound Sensor,
Light Sensor

It would be helpful to post your code, and a schematic, even if you just sketch it with pencil and scan it in. The code in particular I would be interested in. Please amend your post and include it. Reduce it to a  Minimal, Complete, and Verifiable example as far as possible. Thanks!

Ok, will do, thank you! At the moment I cannot post anything so I'll get back in a few hours! Cheers :)

@NickGammon added schematics and very basic code that runs with errors :)

I don't think you should leave s2 and s3 floating. Connect them to ground.

It worked! Thinking about it a floating pin does not mean nor 0 nor 1, so, yeah I was naive in leaving that detail out! Thanks a lot :)

@Gerben - maybe add that as an answer with some more info. Seems it worked.

I don't think you should leave s2 and s3 floating. A floating pin does not mean nor 0 nor 1.
Connect them both to ground.

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


text:
Unspecified running error while programing WeMos D1 in wireless mode
I've tried to program WeMos D1 directly by wireless connection. I've test my D1 so it had no problem. after setting SSID and Password I've programed it for wireless using. It ran well. as I want to programing thought wireless there was an Unspecified error for running python.exe !
java.io.IOException: Cannot run program "python.exe": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at processing.app.helpers.ProcessUtils.exec(ProcessUtils.java:26)
    at cc.arduino.packages.Uploader.executeUploadCommand(Uploader.java:129)
    at cc.arduino.packages.uploaders.GenericNetworkUploader.uploadUsingPreferences(GenericNetworkUploader.java:99)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.SketchController.upload(SketchController.java:709)
    at processing.app.SketchController.exportApplet(SketchController.java:682)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2190)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
    at java.lang.ProcessImpl.start(ProcessImpl.java:137)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 8 more
An error occurred while uploading the sketch

I've python on my PC  and it works. to clear my problem I've attached  the following gif

any help would be appreciated.

You might have Python installed, but can you run it?
Open a command window on you PC.  (Windows button R then CMD)
Then in that type python.
If python starts up then it should be working, but I suspect you will get an error saying:
'python' is not recognized as an internal or external command, operable program or batch file.
To fix this you need to edit you path and restart the IDE.  (How you edit you path depends on your version of Windows so you would be best searching for edit environment path and your version of windows and that should come back with an answer quickly.
Of course if its Linux/mac then it could still be the same issue.


text:
While condition with & bitwise of PINx read
I was looking into ATmega32u4 datasheet to configure the SPI, and there is initialization snippet for data transmission.
void SPI_MasterTransmit(char cData)
{
    /* Start transmission */
    SPDR = cData;
    /* Wait for transmission complete */
    while(!(SPSR & (1<<SPIF)));
}

What I didn't quite get is the last line of the snippet with the while condition to check the state of the SPIF bit in SPSR register.
What I think I understand that it means, if SPIF bit with the a conditional value of 1 which would be in the ALU for comparing it with the actual bit state in SPSR. If this is true with & bitwise operator which would be true if the actual bit in the SPSR is set with the given value (1 << SPIF).
My questions:

Am I understanding it right?
What this line actually means?
I have removed the semicolon at the end of the line and it compiled OK! Is what I did OK?

I prefer to write it like while(!(SPSR & (1<<SPIF))){}; (with curly braces). In essence it just wait till the SPIF bit in the SPSR register is set. Removing the semicolon probably only worked because it was the last line of the function.

It won't compile for me if I omit the last semicolon: “error: expected ‘;’ before ‘}’ token”.

I tried this one with the curly braces, and it didn't work actually. The one with only semicolon surprisingly work. Which is a new technique for me. I know also you can perform if condition with no curly braces and it would activate only the next line of code. So this while technique with or without curly braces is new to me. So yeah thanks :)

After some testing with a code with IO pins. I discovered that there is another command which would do the same as while (condition); which is if (condition){ } and if (condition) without curly braces. So the while with the semicolon and the if with the curly braces! OK sounds good to me now :) Thanks all for help.

SPI transmitt is started by writing one Byte into SPDR. And this code won't return from SPI_MasterTransmit function before it's complete. Transmitt completition is anounced by setting SPIF by hardware (and if SPI interrupt and global interrupts are enabled, it'll run also ISR and clear that flag).
If you write into SPDR before transmission is completed you'll corrupt current "transaction", so you have to wait until it's complete before another write.
Bitwise & is used for bit masking. Bits in the result are set if bits at corresponding positions in arguments are both set:
0b00110011
         &
0b00100001
        ==
0b00100001

So if bit at position SPIF is not set, it will loop again and when it's set, it exits the loop, as there is inverted logic.
( SPSR     & (1<<SPIF))                    !(SPRS &(1<<SPIF))
0b0xxxxxxx & 0b10000000 == 0b00000000  =>  !0b00000000 == true
0b1xxxxxxx & 0b10000000 == 0b10000000  =>  !0b10000000 == false

OK First, the SPIF would be set always whether SPIE is enabled or not. So, in this piece of code the while condition is at the end of the transmit function, would the while condition work the same whether the SPIE is set or not? If this it would work the same because it's connected with a bit mask of SPIF and SPSR. If the SPIE is enabled then the interrupt request would take another action other than while condition.

@PerchEagle Well, if SPIE and global interrupts are enabled, it might result into infinite loop or not executing ISR. Depends how ISRs are done in hardware when you clear that flag before entering ISR (few clock cycles). So if you have interrupt driven transmission, you can write it into the buffer and ISR will send it..

OK, so if I want an interrupt then I have to remove the while line of code and apply another code with enabling SPIE and ISR handling. Correct? So the technique here it that they don't require an interrupt for SPI TX completion so they only doing it by checking SPIF with requirement for ISR.

If you want interrupt driven SPI, you'll need buffer, buffer size, ISR handler that will send next character from buffer and decrements size and maybe CS pin number to release it at the transaction end. The first character must be sent in transfer request (which adds rest of the data into buffer and sets correct size)

OK I'm doing testing with IO pins all configured as outputs with one pull-up pin and drive the other two to high with testing different while & if code configurations: So, 1. while (condition); code >> drive o/p pins from low to high 2. while (condition){code} >> do the opposite drive them from high to low 3. if (condition) {code} >> drive high to low 4. if (!(condition)){code} >> drive low to high >>>> so the only two which works as I want are while (condition); code & if(!(condition)){code}, but I don't understand how they work?!

I think you should take a look to this tutorial.

OK thank you :) That's a good one I have to learn more later on that PDF. So, I have another question I don't know if it's suitable to post it here or in a new thread. Which is about SPI return on MISO. I read in a PDF file that that same SPI code provided in the datasheet, which is: void SPI_TX(char data){ SPDR = data; while (!(SPSR & 0x80)); <<< which has to end in this arrangement, and the author of the PDF file added a last line which is return SPDR as to be read on MISO } >> how this works? is it that SPI automatically receive on MISO after transmission completion?

The SPI is Full Duplex protocol and only the Master is allowed to send Clock signal. So, if the Master wants some data from the Slave, dummy bytes must be sent.

I'm sorry I forgot to mention that I'm applying SPI loopback technique to test SPI functionality. What I'm wondering about is if I apply loopback, then how it works, as the code shows that the author added the return SPDR at the end of TX function, would that actually works? when the MOSI is directly connected to MISO of the same board? Is SPI actually after you send data the MISO get active to receive data, when you actually didn't configure the SPI module to receive data while you're in Master Mode?

I mean if you're the master, how would you read the returned data coming from the slave on the master's MISO pin?

Interrupt signal from slave or polling on master.

I didn't understand how to work with SPI, so I'm posting another thread about how to use SPI for sending data from master and perform a simple blink on slave. Thank you very much :)


text:
clkI/O 256 & 1024 (From prescaler) not working with driving PWM on Nano board
I've been working with PWM in TIMER0 of my nano board.
So, it's working now and I know how to set OCR0A or OCR0B.
Then, I went to play with Clock Select Bits CS02 CS01 CS00 in TCCR0B.
0, 8 and 64 prescaler configurations worked as I also don't see the effect on the LED fade speed.
But the more problem I get is that 256 and 1024 prescaler don't work at all and the LED goes on all the time.
What is the problem?
The code:
void setup() {
    DDRD |= (1<<DDD6);
    TCCR0A |= 0xC1;
    TCCR0B |= 0x00; // this works for 0x01, 0x02, 0x03 only
    }

    void loop() {
    uint8_t i;
    for (i=0;i<256;i++)
    {
      OCR0A = i;
      _delay_ms(1);
    }
    }

regards,

Do you have the real code? And if you are using Arduino framework, don't forget Timer0 is used for counting millis(), so you might just messed up some delay time

Code added :) it's working with the delay as you mentioned that timer0 is used for counting millis, but I'm working with true C coding. Is it still used for _delay_ms and _delay_us? Thank you,

You have been waiting 4 or 16 times as long to try to see any change, right?

No, _delay_*() are implemented with assembly code loops (which means that F_CPU must be set correctly).

I was waiting 4 or 16 times for what exactly ?

The main problem is the prescaler on Timer0 is already configured to divide clock source by 64 CS01 and CS00 are set (0b00000011).
And you are using bitwise OR to "change" prescaler: TCCR0B |= 0x05; or TCCR0B |= 0x04;. But this'll result into the clock source 7 (0b00000111) - clock source is expected on T0 input counting on rising edge.

WOW :) you absolutely right. The bitwise OR was the problem. OK so when to use the bitwise OR when I'm testing different codes and when not to use it? I use it with DDRs PORTs which works well, so here it did a problem !! Thank you very much for the help 3>


text:
Questions about HMC5883L library
I'm studying the structures of libraries currently. I want to learn how good programmers write code, what are the strategies they follow, the art the programmer followed to develop the library. And how important the library should be written in the well arranged form.
But as I'm go back and forth into the library over and over, I really need to understand, the way the programmer followed, and the reasons behind the applied strategy.
The example I'm studying now is the HMC5883L and how the programmer used the Wire library to manage the developing the library. This should be quite easy for experienced programmers, but I'm really studying the concepts, strategies .. etc.
As I'm going over and over I have different questions, so to start this discussion I want to begin with this question about the programmer writing two very similar functions that pretty much do the same thing.
// Read byte to register
uint8_t HMC5883L::fastRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(HMC5883L_ADDRESS);
    #if ARDUINO >= 100
        Wire.write(reg);
    #else
        Wire.send(reg);
    #endif
    Wire.endTransmission();

    Wire.requestFrom(HMC5883L_ADDRESS, 1);
    #if ARDUINO >= 100
        value = Wire.read();
    #else
        value = Wire.receive();
    #endif
    Wire.endTransmission();

    return value;
}

// Read byte from register
uint8_t HMC5883L::readRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(HMC5883L_ADDRESS);
    #if ARDUINO >= 100
        Wire.write(reg);
    #else
        Wire.send(reg);
    #endif
    Wire.endTransmission();

    Wire.beginTransmission(HMC5883L_ADDRESS);
    Wire.requestFrom(HMC5883L_ADDRESS, 1);
    while(!Wire.available()) {};
    #if ARDUINO >= 100
        value = Wire.read();
    #else
        value = Wire.receive();
    #endif
    Wire.endTransmission();

    return value;
}

Update:
Actually, the programmer used the 1st version only in the HMC5883L.begin(); function, but why?
if ((fastRegister8(HMC5883L_REG_IDENT_A) != 0x48)
|| (fastRegister8(HMC5883L_REG_IDENT_B) != 0x34)
|| (fastRegister8(HMC5883L_REG_IDENT_C) != 0x33))
{
return false;
}

Everything else in the library used the 2nd version.
So, basically the two functions are to read a specified register in the HMC5883L, my questions:

what is the difference? I know that there's an extra care has been put into the second function, but why ?
Is it so important ?
Are there situations that require any version of the functions ?

There has never been a "fast" way to do i2c, it is a myth. There are many wrong ways to do i2c.

Yes, I'm still learning how i2c is actually working, and to deal with i2c chips.

TBH the second version of the function is trash. The first version is (almost) the right way to do it.  There's stuff in the second version that really shouldn't be there. There is absolutely no reason why the creator of the library created that second function.

It "waits" for data to be available, when that data will be available the moment requestFrom() completes - so is completely redundant
It makes a spurious beginTransmission() call right before the requestFrom() call. beginTransmission() is only for writing, not for reading. It's pointless there.

However:

Both functions do an endTransmission() after the receiveFrom(), which makes no sense - the endTransmission() goes to balance a beginTransmission() only - not a receiveFrom().  receiveFrom() is a completely self-contained function that needs no other handling.

This library is probably not a good one to study for learning how to use the Wire library. It contains code that indicates the author themselves didn't have a proper grasp of the workings of the library.

Thank you so much dude ! I mean you ARE the man seriously :) I'm really happy that my points of question are considerable and important. I would try to develop my library too, it's for me about grasping more and more skills, information and how to learn the art of programming. I need to forget about my old codes and libraries :)

But if I got some more questions, should I get back here. Or remove the choose the answer until I finish discussion on the topic?

If you have new questions, then ask new questions. Keep it "atomic" :)

all HMC5883L libraries for Arduino have it like this :-) (including Adafruit)

They all copied off each other then :)  I have a DTWI one for chipKIT that doesn't do it that way - but then DTWI doesn't work the same as Wire...

@Juraj Not all of them. This one has 19 stars and is very nice: https://github.com/sleemanj/HMC5883L_Simple

@Jot Thanks for the link :)

I really discovered just now how to read from a specific register from the HMC5883L, I thought I can read the 1st register and the automatic pointer of the chip would take me to the next one without ending the Wire transmission and starting a new one to read that register, but it turns out it actually that way, I have to do two completely separate wire transmission. One for specifying the register to be read and the second one for reading that register.

Correct. During initialization it is no problem to read or write a single byte. When x,y,z data is required while running, then it might be good to read those 6 bytes together.

There is no "fast" way to do i2c. If you already use the "fast" functions in your code, then you can make it a inline call to readRegister8.
The function below reads a byte from the HMC5883L.
When the HMC5883L is not connected, the Wire.read() returns -1. That will be converted to a return value of 0xFF.
// Read byte from register
uint8_t HMC5883L::readRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(HMC5883L_ADDRESS);
    Wire.write(reg);
    Wire.endTransmission();    // add parameter 'false' for repeated start

    Wire.requestFrom(HMC5883L_ADDRESS, 1);
    value = Wire.read();

    return value;
}

But doesn't it need Wire.endTransmission(); after value = Wire.read();?

No, never, only when writing data. See: https://www.arduino.cc/en/Reference/WireEndTransmission It is one of the bugs in the code that Majenko mentioned in his answer.

OK, I'm moving around the i2c area, done some work with the Wire library and tested some lines about reading each register. Next, I should do a similar robust i2c code that is working with similar management of data in the ISR and locking each mode until it's ready.

Yep, you're right, I should put false between the write / read operations. Found this one the link: **If true, endTransmission() sends a stop message after transmission, releasing the I2C bus.
If false, endTransmission() sends a restart message after transmission**


text:
Arduino + motor driver (L293D) power consumption
Please help me on this question.
Original question :
My chip consists of 1 arduino nano and  3 L293D motor driver. This chip is for controlling motors and other equipments. My question is about how to calculate power consumption of my chip. I searched for about voltage settings of arduiono nano and L293D motor driver, but there are many phusical thinks that i cannot understand. How many hours 2000 mah battery enough for.
Note :
Motors and other equipments will have own power supply. That i say it is just for Arduino Nano, Bluetoot adapter for arduino (HC-05) and 3 motor driver (L293D).

I cannot got power settings of L293D. I read technical specification but cannot understand

Yes i connect via power adapter. And it works fine. But it should be with battery not adapter. And I want to calculate which kind of battery i should use. How many Mah  battery is enoght for 3(for examle .. maybe 5 hours )  hours.
Note : I use 3 L293D and can control 6 motors with it

About motor specs i cannot say exactly. Bu i can say this is formula 1 car something like this with 4 AA battery

Did you even read the question? This is 1% about arduino  and 99% about general electonics... this question does not belong to arduino stack, why do you moderators keep moving everything with "Arduino" written on it?

To calculate L293D power usage, you need to lookup the datasheet and check the Voh and Vol. These are the High level voltage and Low level voltage.
On Texas Instruments datasheet, we have:

So you will lose about 1.4V when your output is -0.6A, and 1.2V when your output is 0.6A. If your motor uses 2 outputs (bi-directional) then you have to add the losses.
Then, to get the power dissipated on the power side of the L293D, you take this voltage drop and multiply by the motor´s current.
Example:
Lets say your motor is using 0.6Amps and your power source is 5V + 24V @ 25°C (just like in the datasheet).
The power loss in the L293D is aprox.: (1.4V + 1.2V) x 0.6A = 1,56W.
Since you´ve lost 2.6V in the L293D, your motor will use: (24V - 2.6V) x 0.6A = 12,84W.
To measure this directly on your real circuit, use a multimeter in Ampere mode to measure current, and Volt mode to measure the voltage on the motor terminals when it is on.
As for the arduino, your battery has 2000mAh and I assume it is a 7,4V battery. So it has 2000mAh x 7,4V = 14800mWh of energy stored in it.
If you are running your arduino at 5V, then: 14800mWh / 5V = 2960mAh at 5V.
Now let´s say your arduino and it´s modules, the L293D´s and the motors are using 500mA average, then your battery will last: 2960mAh / 500mA = 5.92 hours in theory.
Why "in theory"? because in real life it is impossible to extract all the energy from inside a battery. A minimum ammount of energy has to remain inside it and some power is lost when you extract it´s energy.
Of course, this is a very raw calculation. In reality, you have to calculate power used in every component. But by calculating the "big guns" first you can get an idea of where you stand.
Basic power loss calculation is done by multiplying voltage drop by the current in each circuit. Voltage drop is the difference between your volts before and after the component.


text:
Receiving and transmitting messages simultaneously
tldr; I am writing a mesh network software using arduinos. I need to wirelessly receive, process, and transmit data, all simultaneously. I am aware of protothreads library, and the other software solutions, such as using interrupts, however, I am using relatively high baud rates. Thus each nanosecond is of the essence. Does anyone have any other ideas for me to achieve this? my initial thought is to have 2 Arduinos functioning as a single node in the mesh. One will receive while the other transmits.
I am currently using these antennas to receive and send messages. I want to create a mesh network of Arduinos using these modules. I found several mesh libraries for Arduino, but none seem to quite do the task I need. So here is my plan which I will work through using an example. (This is a very naive explanation, and has flaws in it's implementation. This is just to give off the general idea).
Each Arduino will be connected to a receiver and a transmitter. Let's say I have just 4 nodes in the mesh.

Node #1 -> Address = 0xA031
Node #2 -> Address = 0xB042
Node #3 -> Address = 0xC053
Node #4 -> Address = 0xD064

I send a message to node A through USB. Let's say the message is "SOS!"
Node A will reconstruct the message in the following way so that the new message is "0xA031_SOS!"
Now, Node A will begin transmitting this message continually. Let's say only Node C picks up the message. Node C will pick up the message and perform the following checks. (I will have 2 queues. A receiving queue and a transmitting queue. So as soon as a node receives a message, it will be placed in the receiving queue. And then it will run the following checks before sending it to the transmitting queue.)

Is the address a recognized/valid address? Handle appropriately
Is the address of the received message the same as the node's own address?
If address is same, check if the message received is the same message being transmitted currently by itself. If so, discard the message and tell transmitter to stop transmitting that message(This means that the message was originally transmitted to another node and came back, which means, it doesn't need to be re-transmitted any more). If the address is not the same, then send the message to the transmission queue.

Now the transmission will be handled the following way.

Check if there is anything in the transmission queue. If there is, transmit this message continually until told not to.
If the transmitter is told to not transmit that message any longer, that message will be popped of the queue.

So what happens? Node A continually sends a message. Node C receives the message and re-transmits. Because Node C was able to pick up Node A's message, it is in range and Node A will pick up Node C's message. Now, Node A will check the address, and say "oh, this is the same address as me." Then it will check if the message being transmitted is the same as what was received. If so, then it will tell the transmission queue to no longer transmit that message. (This almost like a form of back propagation).
Now I realize there are a million ways to have collisions and infinite loops. I will be eventually writing a software to resolve these things. But I hope I am giving off the general idea of how the network will work.
My questions:

As is clear from my explanation, because I am receiving and transmitting simultaneously, is there a way for me to do multi-threading? I am aware of protothreads and the other things mentioned in this post. However, all of them only offer a software solution, and not a hardware solution. So does anyone have any ideas of how I'd work around this? My initial thought is to have each node be composed of 2 Arduinos. Any one have any other ideas?
Also, does anyone have a better idea of implementing the mesh to do what I want it to?

I know this is a very convoluted, hefty post. Please let me know what I should clarify. Thank you.

It is not clear from your explanation why you would want threads at all. void loop() { process_snd_queue(); process_rcv_queue(); }. As long as you do not use blocking calls (see Blink without delay), that should work just fine.

Well, I am constantly receiving, and at the same time, I am processing the received data and transmitting data. The arduino either receives or processes or transmits the data. But it's not able to do this simultaneously. This wouldn't be too much of a problem, but timing must be maintained given the high baud rate I am using.

I hope I'm not completely missing what you're suggesting.

The Arduino has a hardware UART which enables it to send, process and receive, all at the same time. If you take care not to fill the send buffer, then Serial.print() returns immediately, and you can do other stuff while the data is sent in the background. Receiving is also done on the background: just call Serial.available() from time to time to see if you have received something.

Here is my "receive" code: http://arduino.stackexchange.com/questions/17021/unable-to-tell-if-error-is-from-receiving-or-transmitting-end
Given this, and my above explanation, when I receive a message with a certain key, I want to send it to another queue that will transmit that data. Now, won't my buffer lose information by the time the information is processed, sent from one queue to another, then transmitted? Especially since the transmission happens continually until the receiver receives a certain key.

The collision is that, the receiver receives something, sends it to process bytes, then process bytes will send it to the transmission queue. Which might continually transmit a message until a certain key is received. But the program will never return to "read" command in the while loop if it is still transmitting. Thus, I am still not quite able to piece together how I would do what you are suggesting. Can you please elaborate? Sorry if I'm totally missing it.

You can just piece together your two setup() and two loop() functions. But since you are using SoftwareSerial, the performance will disappoint you.

There is no point in listening and sending at the same time. Since you are sending at the same frequency as you are receiving at. So if you listen while sending, you'd receive exactly what you are sending. Which is pointless!

You cannot do this simultanously Because all the arduino ucontroller works at 8 bit RISC architecture. May be you can do it faster bu using assembly language

Also wireless protocols is not full dublex cammunication.


text:
How close to 5 kHz can I set the PWM frequency on an UNO pin 11?
I'm rebuilding a laser CNC machine and using LaserWeb4 as the control interface and GRBL 1.1 as the low-level interface to the stepper motors, limit switches and the laser. I have all the motion sorted out and am working on the laser control.

Figure 1. The GRBL 1.1 pinout. Pin 11 is used for spindle (cutter) speed on a milling machine or laser power control on a laser cutter.
The machine is using a Synrad 48 Series laser module which requires a 5 kHz PWM frequency (page 45 - 46).
The GRBL 1.1 sketch can be configured for a variety of PWM frequencies. See cpu_map.h.
  // Prescaled, 8-bit Fast PWM mode.
  #define SPINDLE_TCCRA_INIT_MASK   ((1<<WGM20) | (1<<WGM21))  // Configures fast PWM mode.
  // #define SPINDLE_TCCRB_INIT_MASK   (1<<CS20)               // Disable prescaler -> 62.5kHz
  // #define SPINDLE_TCCRB_INIT_MASK   (1<<CS21)               // 1/8 prescaler -> 7.8kHz (Used in v0.9)
  // #define SPINDLE_TCCRB_INIT_MASK   ((1<<CS21) | (1<<CS20)) // 1/32 prescaler -> 1.96kHz
  #define SPINDLE_TCCRB_INIT_MASK      (1<<CS22)               // 1/64 prescaler -> 0.98kHz (J-tech laser)

  // NOTE: On the 328p, these must be the same as the SPINDLE_ENABLE settings.
  #define SPINDLE_PWM_DDR     DDRB
  #define SPINDLE_PWM_PORT  PORTB
  #define SPINDLE_PWM_BIT     3    // Uno Digital Pin 11

It seems that my options are 62.5 kHz, 7.8 kHz, 1.96 kHz or 0.98 kHz.
Why does it matter? Two excerpts from the Synrad manual:

Tickle frequencies [a 'keep-awake' signal at zero power] lower than 4.5 kHz may compromise laser performance, ..., and stress the RF [radio frequency] electronics thereby reducing long term reliability while tickle frequencies greater than 5 kHz may cause unintended lasing.
Because laser output follows PWM input with a rise and fall time constant of ~100 µs, the laser cannot precisely follow Command signal frequencies over t kHz with duty cycles greater than 50%.

Can anyone see a workaround for this within the constraints of the GRBL configuration?
I can only think of a hardware solution to filter the PWM out and run it through another device to convert the analog signal to a 5 kHz PWM.
Many thanks.

I'm trying to do the same thing and the answer to your question could save me a lot of time. Did you have to filter the PWM out and run it through another uno to convert the analog signal to a 5 kHz PWM?

No, you cannot have hardware PWM at 5 kHz on pin 11 of an Arduino
Uno. The closest you can get is 3.92 kHz. You get that by setting
the prescaler to 8 and configuring the timer for phase correct PWM,
instead of the fast PWM mode usually used by GRBL. Your options for
getting 5 kHz are to use either software PWM or change the pinout.
You can get a quite accurate 5 kHz PWM signal on pins 3, 9
and 10. You can do software PWM at 5 kHz on any pin, but this
is prone to have significant jitter, which your laser may well not like.

The simple way, which may interfere with the timing of your other digital outputs:  https://playground.arduino.cc/Code/PwmFrequency
Or, if you are willing to put the PWM output on pin 9/10 and manipulate the AVR registers directly:
Digital pins 9 (OC1A) and 10 (OC1B) are outputs of the AVR 16-bit timer (TIMER1) on 328p.  With those you can get a PWM signal at 5.000 kHz, but if you need reliability then an Arduino with external crystal resonator may be needed.   You will need to set the registers TCCR1A, TCCR1B and OCR1A,OCR1B,ICR1,TIFR1 appropriately, details can be found in the AVR datasheet.

The ceramic resonator of the Uno is reliable, if neither accurate nor stable.


text:
Problems connecting nodemcu esp8266 on my laptop
I have a new laptop and didn't run any development boards on it except some Arduino boards.
But now, I have only nodemcu esp8266 and maple mini boards and trying to connect them but I get error connection message.
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header
I tried to find solutions but apparently I'm stuck here and I can't do anything.
I tried to re-flash the nodemcu with the flasher but I can't get the addresses. This is what I got:

The flashing started but can't get the AP MAC and STA MAC. I don't know what is the problem now, I used to flash it before but on my old Dell laptop. I started to think that there are some problems with usb ports of my msi gaming laptop, they are 3.0, I think that could be a problem.
The board is recognized in device manager and in Arduino IDE COM ports.
My question is how to solve this problem ?

I have a problem connecting my dev boards with Arduino IDE. I don't know if it's a hardware or software problem.

I edited the post

Is the correct USB-to-Serial port driver installed correctly on your laptop? Do you use the correct COM port and the correct settings (baud rate, SPI mode) in the Flasher?

@StarCat Yep, I configured all these stuff, same COM ports and same baud rate. The driver is installed by default. I deleted it and installed it again. Same problem ! Really strange, it's working perfectly on my desktop which is not around right now.


text:
Pass templated function as attachInterrupt parameter
So I want to do something like this:
template<int PIN, int CHANNEL>
void initPin() {
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

template<int PIN, int CHANNEL>
void rising() {
    startTimes[CHANNEL] = micros();
    attachInterrupt(PIN, falling<PIN, CHANNEL>, FALLING);
}

template<int PIN, int CHANNEL>
void falling() {
    values[CHANNEL] = micros() - startTimes[CHANNEL];
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

but the compiler gives me this error
no matches converting function ‘rising’ to type ‘void (*)()’

Can I even do this, or do I have to write all the functions by myself?

Try this:
template<int PIN, int CHANNEL> void initPin() {
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

template<int PIN, int CHANNEL> void rising() {
    startTimes[CHANNEL] = micros();
    attachInterrupt(PIN, falling<PIN, CHANNEL>, FALLING);
}

template<int PIN, int CHANNEL> void falling() {
    values[CHANNEL] = micros() - startTimes[CHANNEL];
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

The problem is actually the Arduino preprocessor. It adds illegal forward declarations if template functions are formated as your original code.

Please have a look implementation
https://github.com/Yurik72/SimpleButton
There are implementation how to assign function with arguments to interrupt handler