text:
Generate 5VDC signal when external sensor input changes from high to low
I am new to arduino.  I have a project in which I need an arduino to generate a +5VDC  signal in response to a change of status, (high/5VDC To low/ground) from an external source.
The external source is a stand alone receiver/transmitter set which outputs +5VDC when the transmitter is out of range and ground when the transmitter is within range.
The goal is to have the arduino output +5VDC (triggering a series of events) only when the TX is within range of the RX (signal voltage is GRND vs. +5vDC).  The series of events are controlled via a stand alone event controller which is initiated by a +5VDC signal courtesy of the arduino.
I already have a RX/TX set which outputs +5VDC when the the TX is absent and GROUND when the TX is within range.  I also have the event controller.  I only need the arduino solution.
I have an arduino UNO but I am open to other option if needed.
Solution: give me +5VDC when signal voltage (from receiver) is low (ground).
If anyone could point me in the right direction it would be greatly appreciated.  This is my first arduino project so I have much to learn.
Best regards

This is literally the simplest Arduino program possible.  I can't believe you couldn't find an example of making one pin HIGH when another goes LOW.
void setup(){
  pinMode(yourInputPin, INPUT_PULLUP);
  pinMode(yourOutputPin, OUTPUT);
}

void loop(){
  if(digitalRead(yourInputPin) == LOW){
     digitalWrite(youOutputPin, HIGH);
  }
  else {
     digitalWrite(yourOutputPin, LOW);
  }
}

All you need to do is supply the appropriate pin numbers.

Why waste an Arduino on such a paltry job?  Here's a circuit that has just 3  components in it that does what you want:

simulate this circuit – Schematic created using CircuitLab
It's basically a NOT gate (you can use an actual NOT gate, like a 74HC04 if you like) where the output is the opposite of the input.  You could even remove R2 if you like - that just prevents the input floating when there's no valid signal detected.
This form of gate is called RTL - Resistor-Transistor Logic, and is one of the simplest logic gate arrangements there is.


text:
Serial.flush() in arduino
I am new to Arduino and I have the following:
int     delaynum;
char    cval[12];

void setup()
{
 Serial.begin(9600);
 Serial.print("Enter Number");
 Serial.flush();

 int i=0;
 while(i<12)
 {
  if(Serial.available()>0)
  {
    char ch=Serial.read();
    if(ch>='0'&&ch<='9')
    {
      cval[i]=ch;
      i++;
    }
    else
    {
      cval[i]=0;
      delaynum=atoi(cval);
      break;
    }
  }
 }
}
void loop()
{
   Serial.println(delaynum);
   exit(0);
}

The code output in virtual bread board:(i Entered 100)

But when i remove Serial.flush() The output like (i Entered 100)

I am Expecting the output:
Enter Number (I want to enter number 100 after the output)
100
Why the code not working ?
I am using Arduino IDE with virtual bread board(ATMega328p)

it is an error of the emulation. Serial.flush() only waits until the data are sent completely.

Not knowing what virtual breadboard does on a normal Arduino it would do the following:
Serial.flush() clears the buffer  and this needs some time normaly you wait minimum for around 100 ms to write/read to that buffer again. As your code runs in setup (so just once) the serial is not available as its still flushing and so your result.
As the name setup says this should only be used to setup HW/SW but not to run routines as you may get all sorts of weird results. If you use "\n" aka newline terminators in your communication you can go for them and flushing would be only necessary if the connection is interrupted and you have to resend data.
EDIT

Waits for the transmission of outgoing serial data to complete.

If you send a character, it is placed in a buffer for transmission. It takes time for each character to be sent because serial is slow. Once it is in the buffer, it will be sent automatically in the background while the program immediately moves on to the next statement. This is done so the program won't waste time waiting for characters to be sent.
flush() is a way to wait for it to be sent, instead of immediately moving on in the user program.
So after calling flush() you can be sure that all data has been sent, and the buffer is empty. So in your case where you placed it it makes no sense.

Can you explain in more detail and Arduino use same buffer for both input and output or serial.flush() flush both input and output buffers?

See my edit above. Please mark as accepted if its ok

So in your case where you placed it it makes no sense, why? Arduino does not wait in setup function and what is solution for this can you explain please i am new to this.

Please read on Arduino.cc the basic101 I am not gonna teach here we solve one problem at a time

somehow this answer doesn't say anything to answer the problem

I don't understand "As your code runs in setup (so just once) the serial is not available as its still flushing and so your result.". Why would Serial not be available?

I hate people just writing comments without enlighten us all with their wisdom His problem is when calling serial.flush before id serial.available in a setup routine it does not show any output in Android and he asked why? Serial flush takes time to complete and so the next step (if) is not processed what would be the case if it where in the loop (cause its comming back to the routine) every x ms. The answer is run code in loopor dont flush without delay in setup.

the if after flush is in a while loop which doesn't finish until 12 digits or a nondigit character is received. in very old Arduino core flush would be used to empty the receive buffer.

source: Stack Exchange

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

sort: votes


text:
LUFA with pro micro 3.3v 8mhz not working
I am trying to flash my pro micro 3.3v from sparkfun with a Lufa project to make it act as a pokken controller, i am using this project Github Project I have modified the makefile for 8mhz and set the bootstart pid, this has worked succesfuly on an arduino uno r3, with the same project. When i make the project it works fine then I run make avrdude, and it flashes succesfully. the problem though is the pro micro does not show up as a pokken controller as it should. I then tryed it on my switch to no avail. Here is the make file I am using
#
#             LUFA Library
#     Copyright (C) Dean Camera, 2014.
#
#  dean [at] fourwalledcubicle [dot] com
#           www.lufa-lib.org
#
# --------------------------------------
#         LUFA Project Makefile.
# --------------------------------------

# Run "make help" for target help.
PID          = 0x9203
BOOT_START   = 0x9203
ARDUINO_MODEL_PID = 0x9203
MCU          = atmega32u4
ARCH         = AVR8
F_CPU        = 8000000
F_USB        = $(F_CPU)
OPTIMIZATION = s
TARGET       = Joystick
SRC          = $(TARGET).c Descriptors.c $(LUFA_SRC_USB) $(LUFA_SRC_SERIAL)
LUFA_PATH    = ./lufa/LUFA
CC_FLAGS     = -DUSE_LUFA_CONFIG_HEADER -IConfig/
LD_FLAGS     =
AVRDUDE_PROGRAMMER = avr109 # Add this
AVRDUDE_PORT = COM5 # And this too (use your correct COM port)
MCU_AVRDUDE = atmega32u4
MCU_DFU = atmega32u4

# Default target
all:

# Include LUFA build script makefiles
include $(LUFA_PATH)/Build/lufa_core.mk
include $(LUFA_PATH)/Build/lufa_sources.mk
include $(LUFA_PATH)/Build/lufa_build.mk
include $(LUFA_PATH)/Build/lufa_cppcheck.mk
include $(LUFA_PATH)/Build/lufa_doxygen.mk
include $(LUFA_PATH)/Build/lufa_dfu.mk
include $(LUFA_PATH)/Build/lufa_hid.mk
include $(LUFA_PATH)/Build/lufa_avrdude.mk
include $(LUFA_PATH)/Build/lufa_atprogram.mk

Any Help would be appreciated

go back to the beginning ... configure the arduino as a usb keyboard ... that will confirm that your hardware and software works

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


text:
How to get full response json SIM900 + Arduino?
  void toSerial(int delay_ms)
  {
    delay(delay_ms);

    while(mySerial.available())
    {
       Serial.write(mySerial.read());
    }
  }

  Serial.begin(9600);
  mySerial.begin(9600);

  mySerial.println("AT+HTTPINIT");
  toSerial(500);

  mySerial.println("AT+HTTPPARA=\"CID\", 1");
  toSerial(500);

  mySerial.println("AT+HTTPPARA=\"URL\", \"www.example.test\"");
  toSerial(500);

  mySerial.println("AT+HTTPPARA=\"CONTENT\", \"application/json\"");
  toSerial(500);

  mySerial.println("AT+HTTPACTION=0");
  toSerial(4000);

  mySerial.println("AT+HTTPREAD");
  delay(3000);

  while(mySerial.available())
  {
    Serial.write(mySerial.read());
  }

  Serial.println("");
  mySerial.println("AT+HTTPTERM");
  toSerial(500);

Result:
AT+HTTPREAD

+HTTPREAD:39
{"pinRed":0,"pinGreen":1,"pinYello

I expect messages:
{"pinRed":0,"pinGreen":1,"pinYellow":0}

Simple, reading serial data is way faster than it comes in.  So you read everything out of the buffer and cleared it so that available returned zero before everything got there.  You can check that available gives you a large enough number so that you know the whole message is there before you start reading or you can parse your message to see if it is all there before you move on.  Had you come back later and read some more on the next loop you would have seen ":0} before the next message.  It just got there after you stopped reading.

hey how did you finally make it? could you post the final code? I've been despairing of the detail for days. I would be very grateful! Greetings from Germany

Okay, I've found a solution. To start with, you need to download the server response length and loop according to the response length.


text:
turning positional servo motor more then 180 degrees
My RC servo motor is capable of turning more then 180 degrees(around 200 degrees) when I physically turn it, but when I use my code it only turns 180.
Is there a way to code it so that it turns to 200 instead of 180?

what code are you talking about?

First some basics to clear definitions:
A Servo Motor does not normally spin a full 360 degree rotation. Instead it is limited to a range of 180, 270 or 90 degrees depending on the make or type. A control signal is sent to the servo to position the shaft at the desired angle.

Conventional Servo Motor Timing

In a conventional analog servo motor a PWM signal with a period of 20 ms is used to control the motors. A signal of 20 ms has a frequency of 50 Hz.
The width of the pulse is varied between 1 and 2 ms to control the motor shaft position.

A pulse width of 1.5ms will cause the servo shaft to rest in the 90 degree position, the center of its travel.
A pulse width of 1ms will cause the servo shaft to rest at the 0 degree position.
A pulse width of 2ms will cause the servo shaft to rest in the 180 degree position.

Varying the pulse width between 1ms and 2ms will move the servo shaft through the full 180 degrees of its travel. You can bring it to rest at any angle you desire by adjusting the pulse width accordingly.
So if your servo is a 270 degree servo (like the domanrc DM-S0903MD or DS3218 270 Degree Digital RC Servo) the standard sweep sketch (Arduino Servo library) will let your servo sweep from 0-270 even if in the *.ino its myservo.write(180); So to simply test you could use write(map(desired_angle, 0, 270, 0, 180))
If you want to control it more precicly you use microseconds.
servo.attach(5,500,2500)
servo.writeMicroseconds(1500);

AND you have to use an extra power supply for 270 degree servos, the 5V from Arduino want make them move or only in a jittering way of.
If you just have a "defect" 180 degree servo turning to lets say 190 degree for some reason, you might try the microsecond method playing around with the values in attach, also use an extra power supply, but for real over 180 degree action get a 270 degree servo.

Just because a servo can manually be turned more than 180 degrees doesn't mean that it should be turned more than 180 degrees.
Most servos will include a certain amount of leeway in their design to help reduce damage from external forces, but the internal design will be geared1 towards operating over a 180 degree range.
While it may be possible to "overdrive" the motor by changing the PWM timing signals (see the Servo attach() reference page) doing so may end up damaging the servo itself.

1: Pun intended


text:
Bicycle Tail Light project
For my college course we currently have to carry out a project of our own choice.
I chose to make a Tail light system, with strobing indicators, fog-light and brake-light.
The lighting uses Neopixel strips and rings, with the indicator sections consisting of 2 neopixel strip 6 (in parallel); the fog light using a neopixel jewel; and the brake light using a neopixel ring 16.
The indicators need to strobe outward from the centre of the device (in the desired direction, left/right) based on a button input. The fog-light should turn on when the device is activated by switch, and the brake-light will turn on when receiving an input from another button.
I've only ever coded using Python during GCSE and can't wrap my head around Arduino code. Currently using tinkercad for creating this as I don't have any arduino kit, and don't want to spend out the money on unneeded components.
Any help is appreciated, and if a link to the tinkercad circuit would be useful let me know.

https://arduino.stackexchange.com/tour

If you want to program your project in Python you should add the Python tag to your question.

I don't want to code in python, just stating what prior coding knowledge I have. I know python is probably not the best coding tool for this.

Break down your project into steps, both hardware and software, and tackle a step at a time.
First do a block diagram of the system, showing the different components, the layout of the control buttons, etc.
Then map out the desired behavior, perhaps using a flowchart. What should it do when you first turn it on? How will it respond to different button inputs? Will it continue to flash in the current pattern indefinitely until there's another input? Will there be a cancel button?
Then read up on how to power and control NeoPixel LEDs. I believe they use I2C? Are there any NeoPixel libraries you can use?
You might then try using a circuit simulator to create a virtual prototype of your circuit. Figure out how big a battery & voltage regulator you're going to need. (If you're running off of batteries you should use a switching or "buck" type voltage regulator rather than a linear voltage regulator since they are much more efficient. Just make sure you pick a regulator that can provide enough current for all your LEDs plus your Arduino, with a little extra left over.))
Once you get a virtual circuit working, it's time to use real hardware.
For a bike tail-light, you should think about how to make it weather-proof. are there waterproof enclosures you can use? What about waterproof NeoPixels? If there are no waterproof NeoPixels, what about waterproof enclosures with clear covers?
Buy the Arduino you're going to use, and at least a few of your NeoPixels. Work out how to control and flash a single LED. Then gradually add complexity to your project until you get it working.


text:
generating signal of 3 phase UPS PWM by SVM
Is there a realization code for 3-phase UPS inverter by Arduino?  I need implementation for SVM by voltage and current feedback.

you can write your own code


text:
Connect multiple pins to same VCC using breadboard
Ok so I am pretty green as far as AVR programming is concerned so bear with me.
I am doing a project with an ATmega32 MCU on a dev board which has 4 VCC pins.
The project includes a GPS, SD card and a TFT display. Currently, the GPS and SD card take up 2 out of the 4 VCC pins for powering themselves up. I have two free left.
The display controller I have is the SSD1289:

I've connected it to my MCU, the VCC pin on the display took up one more VCC pin so I have one VCC left.
I've been reading up and I've found that the LED_A and RD pins need to be connected to 3.3V, that is VCC.
The LED_A pin should also have a resistor on the line connecting it to VCC.
First question - can someone confirm this is the way to connect it?
Second question - Is it possible to, for example, connect the VCC and RD pins of the display to the same VCC using a breadboard? So then I have one VCC left to connect to LED_A pin through a resistor? I don't know if multiple pins can share the same VCC. Will the voltage drop if I connect two pins to it?
Is this safe to do?

can you connect two garden sprinklers to one water supply? http://hyperphysics.phy-astr.gsu.edu/hbase/electric/watcir.html

You have basic misconceptions there:

Vcc is the power input (!) for the Atmega, not an output to provide current to other parts. Your power supply (whatever you use as one) should be connected to every Vcc pin at the same time. Sure, the Vcc pins are internally connected, but the Atmega has multiple of them, so that the needed current does not have to flow through a single pin. Also you don't want to draw the current for peripherals through the Atmega chip itself (which would happen, when you connect the power source to one of them and the peripherals to another). So every device in your circuit, including the Atmega, has it's own Vcc pin, which needs to be connected directly to the power supply. That is ok and correct, as long as the power supply can provide enough current for all components. If it doesn't, you need to buy a power supply, that can.
When connecting device to one pin, the number of devices is not imporant. The current draw is what is important. For example let's take simple digital output pin of the Atmega. It can provide up to 20mA (recommended value; max. 40mA for a short time). We must no exceed that value. So we can connect 1 device, that draws 20mA, or 2 devices, that draw 10mA each. Or 100 devices, which draw 0.2mA each. The number is not important, only the total power draw. The current will drop, when you draw more current, that the source can provide. In that case often the source will be damaged or at least go into thermal emergency shutdown (as for the voltage regulator of a genuine Arduino).

So the Todo for you: Connect every Vcc pin, that you have, directly with the power source.

Thanks for the answer! But I think you may be wrong here with 1)
Here is the datasheet for my board: https://docdro.id/YoZ3ZNp
It says the 4 VCC pins are power output.

Hmm, but those VCC pins are no GPIOs and therefore the 20mA limit does not apply. I assume, the motivation behind breaking out 4 VCC pins is that they can be used to power external devices. The current rating for dupont pin headers is in the order of some amps, so they are not the limit and as the atmega doesn't source the current on the VCC pins, it should be fine to connect even power lines to the remaining VCC pins.

@Machi, why is the link to the datasheet included as an afterthought? ... that kind of information should be included in the question when you write the question  ... chrisl's answer to your question is correct and it remains correct unless you edit your question

Sorry, should've included it right away. Thought it was clear what I was asking from the get go.
Anyways this answers my question now so thanks everybody!


text:
Using Arduino with through beam sensor on combine harvester
I have a project where I'm trying to capture the output from a through beam sensor (infra red) installed on a combine harvester. I'm not much of an electronics wiz but was hoping it was going to be simple to capture the output from this sensor whilst not interfering with the operation of the sensor as far as the combine harvesters electronics were concerned.
The receiver component of the sensor has 3 wires, ground, 12v supply and output (sensor) lead. If the receiver can see the transmitter the voltage on the sensor wire is 5v when it cant see the transmitter its voltage is 1.5v. Strangely if I remove the sensors from the combine and power them on the test bench, the sensor will pass the powered voltage i.e if supplied with 12v then the receiver will pass 12v on the sensor wire if it can see the transmitter. I think the combine electronics are doing some trickery way beyond my understanding BUT that's fine, all I want to do is capture the pulse from the sensor and pass it to an Arduino without interfering with the combines electronics.
I have tried a couple of setups to no avail this is my last attempt but I cant get a signal from the sensor. I'm not sure the diode (D1) is required but as I had it I added it. In a test environment I can add 5v through R2 and the PC817 triggers and I pick a pulse up on the Arduino. All grounds are linked and the Arduino is powered from the 12v coming from the ecu.

simulate this circuit – Schematic created using CircuitLab
Is there a clever bit of circuit or component which I can use to steal the pulse from the through beam whilst not interfering with its operation as far as the combines systems are concerned?
Any help appreciated with regards to how to properly design a circuit and how to make this work. I have been reading about op amps but not sure that will sort the problem.

The diode should not be needed, since the optocoupler has already an LED on that side incorporated, which is also a diode. Are you sure, that the signal pin can provide the needed current for the optocoupler? The resistor would cap the current at about 18mA, but can the signal pin provide that? You write, that the Arduino is powered from the Combine ECU and the grounds are also connected. Why do you want to use an optocoupler then? For keeping the voltage down a 5V zener diode and a resistor in series would be easier I think.

Thanks chrisl. To be honest I don't have a clue whether the signal pin can supply the power. I suspect not as I cant get any reading. Would the zenor diode circuit take less power? you wouldn't have a basic schematic on how to wire one up so I could give it a go?


text:
Vin & VU pins of NodeMCU V3
Can we use the vin pin of the lolin v3 nodeMCU as a 5V supply. If yes, i checked mine with a multimeter. At max, it gives a voltage of 2V. Is my pin blown out? Also, can use the VU pin as a 5V supply? Will using it cause any problems to my laptop's USB port? Can somebody help me out?
I need 5V to drive a relay using the v3

In addition to the voltage, you need to think about how much current you’ll need.  That’s the bigger driver of whether or not you can use  pin as a source.

no, but you can use the same pin on an Amica nodemcu (which all seem to use a cp2102 instead of ch340), that's connected to 5v on the usb through a diode that handles about 400ma safely. for this reason alone (powering 5v periphreals while running from usb power), i never buy the the larger lolin boards, except accidentally when listings are deceptive.

So the Vin of V3 doesn't support 5V output?

On the NodeMCU “v3” (and only on the v3) there’s a pin called VU (Vusb) that is connected to the +5V on the USB bus of the NodeMCU socket. This pin can be used to feed external components when it’s connected to USB, within the limits of the USB power supply it’s connected to.
The Vin pin (which is available on all NodeMCUs (and not just the v3) is a +5V power input which can be used to power the NodeMCU if it is not connected to USB. It can not be used as an output and it needs a stabilized supply.

The previous versions do give 5V from the Vin pin. I've driven sensors using them. The V3 also has been used for the same. I was informed by my employer.

Strictly speaking, the Vin pin is less than 5v because it steps down to about 4.76V because of a Schottky diode (see circuit diagram)

The VU is useful for example to power 5 V relay modules, which at 3.3V, usually work but are slower and less reliable.

Oh my god. Where is this info mentioned? I was about to return my LEDS/controller thinking they are defective or something. Then I saw this answer!


text:
Bluetooth Module 4.0 BLE
I'm trying to read data sent from my phone to arduino via HM-10 Bluetooth Module. I downloaded the app, I paired the module to phone but I can't read data.
If I just upload a blank sketch to arduino and open Serial Monitor, if I sent "1" from phone, it appears on the monitor, it's ok. But if I write Serial.begin(9600) in setup loop then noting happens and I can't see anymore the data from phone and Serial.read() is useless. Can you help me?
This don't work:
char incomingValue = 0;
int doorPin = 13;
void setup() {
  Serial.begin(9600);
  pinMode(doorPin, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    incomingValue = Serial.read();
    Serial.print("\n");
    if (incomingValue == '1') {
      digitalWrite(doorPin, HIGH);
    } else {
      digitalWrite(doorPin, LOW);
    }
  }
}

And with this I cand see to the Serial Monitor what I'm sending from phone but I can't read the character.
char incomingValue = 0;
int doorPin = 13;
void setup() {
 // Serial.begin(9600);
  pinMode(doorPin, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    incomingValue = Serial.read();
    Serial.print("\n");
    if (incomingValue == '1') {
      digitalWrite(doorPin, HIGH);
    } else {
      digitalWrite(doorPin, LOW);
    }
  }
}

Have you connected HM-10 RX to Arduino RX and HM-10 TX to Arduino TX? If yes, try to swap these two, vonnecting RX to TX and vice versa

I swapped thep and now I can't even connect my phone to the module.

I managed to reconnect the module to phone but with HM-10 RX to Arduino RX and HM-10 TX to Arduino TX, vice versa doesn't work.

how is the module connected to the arduino? ... you do not have any code that talks to the BT module ... it appears that you connected to pins D0 and D1, which makes the module connected directly to the serial converter chip ... the data you are seeing on the serial monitor is not passing through the arduino sketch

My module's pins are connected like this:

VCC -> 5V arduino
GND -> GND arduino
RX -> Digital Pin 0 (RX)
-TX -> Digital Pin 1 (TX). How can I make the data pass through the arduino sketch?

I tried this code but still no success: https://create.arduino.cc/projecthub/electropeak/getting-started-with-hc-05-bluetooth-module-arduino-e0ca81

Which one did you try from there? I have seen 3 different codes there

use software serial ... https://www.arduino.cc/en/Tutorial/SoftwareSerialExample


text:
Is it possible to upload an arduino sketch through the serial port (RX) instead of USB
In another words, is it possible to develop a custom bootloader so sketches can be uploaded via serial connection made using the RX/TX pins and not via the USB connector (I am using Pro Micro boards)?
Thanks!

This is definitely possible. Bootloader is just a program which can communicate whatever hardware is available and write memory and jump to it.

This should be possible by adapting the serial bootloader typically used on the ATmega328p (etc) to your ATmega32u4.  The details of doing so however do not really fit in a question on a Stack Exchange site unless you explain a specific difficulty.  Make sure to do some searching, it is quite possible someone has already done this project.  Also consider if switching to an Arduino type board that simply has an ATmega328p (especially a compact one without a 2nd chip as a USB bridge, though you can bypass that) might be the simplest route to fill your need.

No need to have a specific bootloader. The basic bootloader can do that (in Arduino that's the case so I hope this answer will apply in your case. But if not, the principle is certainly the same).
Once you perform a reset on the board, the bootloader look at the serial port during a short time. If something come, it checks if it's an hex file and if yes it send it to flash. The USB just use the RX input.
So you can send data using a direct connection or using for example a Bluetooh like HC-05. I do that for some project in order to update via Android: the Android app send an order to the Arduino, through Bluetooth.
Receiving this, the Arduino RESET itself, and then the Android App send immediatly data.
On Arduino side: connect for example A0 to RESET PIN and perform a digitalWrite(PIN_RESET,HIGH);
Have also a look at Reset an Arduino Uno in code
After the RESET, the board will reply with 0x14 0x10 (so it send this to TX and so if you have a bluetooh module, you'll received than on your Android App (eg))
You must then send  0x50 0x20 to the board to tell it you enter programming mode.
Then send 0x75 0x20 to get the id of the board in order to be sure you will send the HEX file for the right hardware.
You will receive 0x14 XXX 0x10 where XXX = id of the board
Then you can send the HEX file.
For that, you will send it by blocks of 128 bytes
So start by dividing the HEX to know the number of blocks then loop against this  number:
Start at ADR=0 (adresse dest in flash) and send:
For each block:
1) Send 0x55, low byte of ADR, high byte of ADR, 0x20
2) check reply (must be 0x14 0x10)
3) Send the 128 bytes: 0x64, 0x00, 0x80, 0x46 then the 128 bytes and finish by 0x20 (0x80 is the size)
4) check reply (must be 0x14 0x10)
5) update ADR. Take care: ADR is a word pointer (2 bytes). So ADR = ADR+0X40
Loop on num of blocks
Finish the job by sending 0x51 0x20 (exit programing mode)
Some details:

0x46 before the 128 bytes tells you want to write in flash. Other codes are available eg for checking, getting data etc..

It seems mandatory to send each time 128 bytes. So if your last block is smaller, you need to add some '\0' to get a total of 128. I've been unable to get good results trying to change the 0x80 value and send less bytes. :(

It's not very easy and need tests to get a good code but that really fine to be able to have an Arduino the user can update.
Hope this will help.

Yes, there is an Optiboot fork supporting ATmega32U4 supporting hardware UART to upload Arduino sketches.
Also, a detailed instructable post explaining how to use it with Arduino Pro Micro.

Yes. You can develop a bootloader for the ATmega32u4 that will receive firmware over any interface (UART, SPI, I2C etc.).
Loading via UART is a solved problem. Look for the AVR109 bootloader.


text:
Macbook Pro CH340 Nano 14201 error
I'm using a MacBook Pro Mojave 10.14.6 to code genuine Arduinos. Been working with multiple Uno R3s, no issue. Got a genuine Nano and get the following error: ser_open(): can't open device "/dev/cu.usbmodem14201": No such file or directory
The USB cable I'm using works fine with a cheap Chinese Uno clone, so there are data pins in the cable.
I followed instructions to delete the kext file, rebooted, installed CH341SER_MAC file and rebooted. Still getting the error message. I notice that others have asked this question; where are the answers? Thanks in advance.

What triggered this error message?

Also, you shouldn't need a CH34x driver. A genuine Arduino would have an FTDI chip, for which MacOS has the driver built-in.

The error message was triggered when I attempted to upload a simple sketch to make the LED blink on and off, to test the Nano. It is absolutely a genuine Arduino; that's the only thing I buy, in support of the Arduino ecosystem. Got it from Amazon, sealed OE box. I also bought 4 Unos at the same time, all of them work fine with the same sketch. My kid bought a cheap Chinese knock-off for school which doesn't always work perfectly (which is another reason why I buy genuine only), but has the same USB cable connector as the Nano. So the cable isn't the problem. Software is fine, cable is fine.

What was the actual action that triggered the message, e.g. connecting the Nano to the Mac? Selecting the port in the IDE's 'Tools' menu? Clicking 'Upload'? You're using the physically same cable for either Nano and one nano works but the other doesn't? Have you tried a cable swap anyway (since your success with the Nano clone was intermittent)?

What was the actual action that triggered the message, e.g. connecting the Nano to the Mac? "The error message was triggered when I attempted to upload a simple sketch to make the LED blink on and off"    You're using the physically same cable for either Nano and one nano works but the other doesn't? "No, the Chinese knock off is a Uno clone that uses an USB-C connector, same as the Nano.", Have you tried a cable swap anyway (since your success with the Nano clone was intermittent)? "Not a nano clone, it's an Uno, and I don't have a second cable that is reliably data and charging capability."

The Chinese Uno clone that doesn't always work perfectly relates to its inability to keep time to within 0.5%, it restarts whenever it is reconnected to the computer, and it sometimes hangs/crashes when running a sketch where a genuine Uno will function perfectly. Hence, I only buy genuine. I'd have to buy another cable, since I don't have devices that use USB-B and-C cables.

Sorry, the connector used is a USB Mini-B by both the Chinese Uno clone and the Nano -- my bad that I didn't have the nomenclature straight. In any case, I'll have to buy another cable, since I don't have anything that uses the Mini-B.

Timekeeping isn't exact with any of the boards, though .05% - just over 7 minutes/day - doesn't sound like too high an expectation.
Restarting when you connect it to your computer is by design and doesn't indicate a fault. Opening the IDE's terminal or connecting another terminal program to a connected and running Arduino will - and is supposed to - reset it. Here is a forum discussion on how to disable the auto-reset function (Uno-specific) if you want to. Note that it involves modifying the board.
It's quite possible that this one board has a fault, though it still could be the cable. A couple of swaps should confirm it one way or the other.
I'm still not clear on where the error message,

ser_open(): can't open device "/dev/cu.usbmodem14201"

came from, but I'm guess it's from AVRdude, the uploader application on your Mac, and still I'm wondering if the correct port is selected in the IDE's Tools | Port menu? For some reason, a USB device called "cu.usbmodem14201" is expected but not found. Since neither the Mac nor the IDE inherently knows this name - a USB device announces its name when you connect it - could this selection be left over from having previously used the genuine Arduino? Another reason to check the Ports menu. Also note that the Ports menu doesn't update its list spontaneously - only when you open it (and maybe only when you open the top-level, Tools, menu; I don't remember exactly).
Update:

The regular Arduino at 0.5% is pretty crude, I'd pay more for a more
  accurate crystal, but I was able to develop a sketch that adjusts for
  the Arduino's inaccuracy.

You could try putting the Arduino in an "oven" - and I emphasize the quotes. This is not a heating chamber per-se but a temperature controlled chamber. If you're getting good results by adjusting the count, adding the oven should get you even better results, especially as the seasons change and if that makes enough difference where you are.

I'll be damned, I went to Tools/Ports and selected "dev/cu.usbserial-AK069QY4 and uploaded a sketch successfully.  Regarding the timekeeping, 0.05% doesn't cut it for my application, I'm looking for better than 1 second in 24 hours, which is 1/86,400, or 0.0012%. The regular Arduino at 0.5% is pretty crude, I'd pay more for a more accurate crystal, but I was able to develop a sketch that adjusts for the Arduino's inaccuracy. Anyhow, thanks for pointing me in the right way. :)

You're welcome. If the answer solved your problem, please select it so. It will keep it from falling into the barrel of presumed unanswered, but abandoned, questions that like the phoenix, keep rising from their ashes (auto-reposted).


text:
antenna of the HC-06 bluetooth module
Does the Bluetooth module HC-06 contains a built in antenna similar to HC-05 ?
and if so, then what is the benefit from using antenna?

Sure it also has a build in antenna. Mainly the HC-06 is just a HC-05 with different firmware. What do you mean with "benefit from using antenna"? As it is build in, you don't have a choice. Also every RF device needs some kind of antenna, or it just won't work

thank you @chrisl !


text:
HC-05 master and slave
I have a silly question that came to my mind
when communicating between HC-05 and A smartphone, the smartphone is considered as the master,
and the HC-05 is considered a slave.
master will send data to the slave and then the slave will send these data to the MCU.
my question here is that, what is the MCU considered if it is not a master or slave?
if I got something wrong, I'll be glad if you correct it for me.
thank you

What do you mean by "not a master or a slave"? Bluetooth always has a master and a slave. When should the HC-05 ever be none of that?

HC-05 <=> MCU is a serial connection without any master/slave protocol, handshake or whatever.

if MCU is in serial communication with HC-05, then both of them are considered a slave ? @chrisl

You have a misconception about the interfaces involved. Actually we have 2 different interfaces here: Bluetooth and Serial (UART). The HC-05 is a Bluetooth Serial bridge.
The Bluetooth interface has a fixed concept of master and slave. Every connection needs to have only 1 single master. This concept applies only to the communication between HC-05 and the smartphone. It has nothing to do with the MCU itself, because the MCU does not do any Bluetooth communication.
The second interface is the Serial (UART) interface between the HC-05 and the MCU. For this interface there is no concept of master/slave, because it is not needed. Either of them can send independently on their corresponding TX pin and can receive on their RX pin.
These are two totally independent and different communication interfaces. The HC-05 just forwards data between the interfaces.

very clear now thank you !


text:
HC-05 TX,RX divider rule
I'm using the HC-05 Bluetooth module but I'm confused about the TX,RX pins.
I want to know when should I connect the RX to a divider circuit to convert 5v to 3.3v.
Because while searching, I saw both of the following:

either RX is connected to TX of the UNO and TX is connected to RX of the UNO without a divider circuit.
or RX is connected to a divider circuit and then connected to any digital pin , TX is connected to any digital pin as well.

So can you give me a thought about both the situations?
my thought is that only digital pins needs a divider rule, but the TX,RX pins can be connected directly and operates without any problems but if so, then what's the difference between both??
Note that I'm using HC-05 to turn on a LED.
Hope to see some good explanation that suits a new Arduino learner.
Thank you..

You need a logic level translator of some form (such as a resistive divider) if the Arduino runs at 5V. If it's a 3.3V Arduino then you don't need one since the logic levels will match.
You connect to the TX and RX pins (or TX1/RX1 etc) of the Arduino if you want to use a hardware UART (Serial, Serial1, etc). You connect to any pins you like (with certain exceptions for the Mega) if you use SoftwareSerial instead of a hardware UART.

While you should use a voltage divider on the Arduino TX --> BT RX signal, you honestly don't need to. Many people, including myself, have used HC-05s without voltage dividers and haven't let "the magic smoke" out of the device. Adding a voltage divider may, though, may increase the lifespan of the HC-05.


text:
Hardware/software serial for HC-05
can anyone please tell me the whole difference between hardware and software serial for the HC-05.
I read UART,USB cable, serial and I was like really confused
so what is the difference and advantages between both?
thank you...

Hardware vs Software Serial: Most microcontrollers/Arduinos have at least 1 hardware Serial interface. That means, that for this Serial interface the actual communication protocol (the transmission and receiving of the actual data) is implemented in dedicated hardware inside the microcontroller (which also means there are fixed pins, where you can connect to them on the board). That way you don't need code for doing the complex communication protocol. Instead the main CPU is only involved to handle the received and to-be-transmitted data, which need to be placed in a buffer register. The dedicated hardware then automatically sends and received the data.
As the number of hardware Serial interfaces is limited and fixed for the Arduino board/microcontroller, it happens, that you need more Serial interfaces, than you have in hardware on your board/in your microcontroller. Then you can use SoftwareSerial. That is a library, which handles the complete communication protocol in software, by directly setting and reading the electrical pin states according to the protocol. The advantage is, that you can use this on any digital pins for such an interface. Disadvantage is, that doing such things in software is complex. You can only listen on 1 SoftwareSerial interface at a time and the baudrate is limited (depending on the actual used microcontroller, e.g. it's frequency).
UART vs Serial: UART is the technical term for the used communication interface. Serial is an Arduino term, which is not used that way in other contexts. The real interface type is UART and the Arduino framework just names that Serial to make it simpler.
Connecting over USB cable or pins: Let's take the Arduino Uno as example. It has 1 hardware serial interface. This interface is connected to the pins 0 and 1 (RX and TX), but also internally to an extra chip. That chip handles the USB connection and behaves as a USB-Serial bridge. When communicating with the Serial Monitor in the Arduino IDE, you are actually using this USB-Serial bridge to talk to the microcontroller on the Arduino. But you could also use the RX/TX pins to do that.

Hardware serial uses pins 0/1 on the Uno. You can't change those pins. Those pins are also the pins that are used to communicate with your computer. You can use hardware serial on those pins to communicate with the HC-05 only if you don't want to communicate with your computer.
SoftwareSerial can be used on any pins so can be used at the same time as the hardware serial for communicating with your computer. However SoftwareSerial is somewhat limited in what it can do.
Bigger boards (such as the Mega) usually have more than one hardware serial port. These are connected to the TX1/RX1, TX2/RX2 etc pins. These are the preferred method of connecting to external serial devices since they work more reliably that SoftwareSerial and concurrently with the computer's USB connection.


text:
Counting to 1000 In Both cores execution time problem in esp32?
I am trying to count to 1000 with single core and dual core with esp32 but the output(run time) dose not make sense, the time which takes a single core should be doubled compared to dual core in theory right?
Here is the code
TaskHandle_t Task1;
TaskHandle_t Task2;
SemaphoreHandle_t baton;

int i = 0;
long l;

void setup() {

  Serial.begin(115200);
  pinMode(2, OUTPUT);
  pinMode(4, OUTPUT);

  baton = xSemaphoreCreateMutex();
  l = millis();
  xTaskCreatePinnedToCore(
    Task1code, /* Function to implement the task */
    "Task1", /* Name of the task */
    10000,  /* Stack size in words */
    NULL,  /* Task input parameter */
    1,  /* Priority of the task */
    &Task1,  /* Task handle. */
    0); /* Core where the task should run */

//single core or dual core execution

//  xTaskCreatePinnedToCore(
//    Task2code, /* Function to implement the task */
//    "Task2", /* Name of the task */
//    10000,  /* Stack size in words */
//    NULL,  /* Task input parameter */
//    1,  /* Priority of the task */
//    &Task2,  /* Task handle. */
//    1); /* Core where the task should run */

}
void Task1code( void * parameter) {
  while (true) {
    xSemaphoreTake(baton, portMAX_DELAY);
    xSemaphoreGive(baton);
    delay(1);// I don't understand in here without this command output result is worse
    i++;
    if (i == 1000) {
      l = millis()-1;
      Serial.print("Done ");
      Serial.print(xPortGetCoreID());
      Serial.print(" ");
      Serial.println(l);

    }if(i>1000){
      vTaskDelete(Task1);
    }
  }
}
void Task2code( void * parameter) {
  while (true) {
    xSemaphoreTake(baton, portMAX_DELAY);
    xSemaphoreGive(baton);
    delay(1);// I don't understand in here without this command output result is worse
    i++;
    if (i == 1000) {
      l = millis()-1;
      Serial.print("Done ");
      Serial.print(xPortGetCoreID());
      Serial.print(" ");
      Serial.println(l);
    }if(i>1000){
      vTaskDelete(Task2);
    }
  }
}
void loop() {

}

The output I get for runtime
Single core :- 1033 ms
Dual core :- 701 ms

Without delay(1); command the result is even more obvious
Single core :- 39 ms
Dual core :- 40 ms

How can I make my algorithm show that single core takes twice time as dual core execution time I wan't both cores to work parallel not one after the other.

Only one task can be updating i at once. Without delay the act of doing the counting is negligible. It's the semaphore that is giving you any results at all.

For multiple cores to provide any advantage, they must be able to work independently. If they require shared access to a resource - i in your experiment - only one core can actually be contributing to the job at any one time. But because there are multiple, they have the additional bookkeeping to negotiate access to the shared resource. Thus the total job takes longer than it would take one core with complete access to the resource and no overhead to manage access, to do the job by itself.

Thanks this helped me

Your must use the semaphore to protect the read/write access to i
(Only one task is allowed to modify the variable at a time)
xSemaphoreTake(baton, portMAX_DELAY);
i = i + 1;
xSemaphoreGive(baton);

Additionally you should combine your if clauses. If both tasks increment iit could happen, that it will never has the value 1000for the second task.

But it did not speed up the execution time? Here is the updated code as you asked https://hastebin.com/ajileyiqud.cpp

Right now (without the delay) you couldn't speed up the execution time with a second task. Only one task is allowed to access iat a time and so the other task has to wait and could do nothing.
If you gives the task something to do (the delay) you should se the difference.

I don't understand how to get advantage of the dual cores it has?


text:
Button example: resistor vs wire
I am playing with this basic example:
Arduino: Button

There're a lot of existing questions about why to connect button to the ground. I get the idea more or less. Is done to avoid "noise" during reading the input value.
However, what I don't understand is why to use resistor instead of a wire? If I remove resistor and put the wire instead the example stops working. Could someone explain me this?

If you remove the resistor and put a wire then when you press the button you have a dead short to ground.  That's sometimes a little more exciting as it tends to cause smoke and sometimes even fire.  But it tends to be a one-shot experiment with most Arduino.

There are no existing questions about why to put the resistor there.  It's all well known and been done that way for decades stuff.  Without it the pin is floating when the button isn't pressed.  It isn't connected to 5V and it isn't connected to ground.  So it reads whatever voltage it wants based on the noise it picks up.  With the resistor, when the button isn't pressed it is connected to ground and therefore reads LOW reliably.  It's no mystery and there's no debate about it anywhere except among those who don't know what they talk about.


text:
Interleave disassembly + source with avr-objdump
I have a C program for the attiny85, that I want to disassemble and display with interleaved source code.
Here's my program:
test.c
#include <avr/io.h>
int main() {
    for(int i=0; i<100; i++) {
        PORTB=i;
    }
}

Here's how I compile it: avr-gcc -g -O0 -mmcu=attiny85 -o test.elf test.c
Finally, I generate the disassembly with interleaved source-code with the command: avr-objdump -S -D test.elf
The disassembly of the text section shows the following disassembly without interleaved source code:
00000030 <main>:
  30:   cf 93           push    r28
  32:   df 93           push    r29
  34:   00 d0           rcall   .+0             ; 0x36 <main+0x6>
  36:   cd b7           in      r28, 0x3d       ; 61
  38:   de b7           in      r29, 0x3e       ; 62
  3a:   1a 82           std     Y+2, r1 ; 0x02
  3c:   19 82           std     Y+1, r1 ; 0x01
  3e:   0a c0           rjmp    .+20            ; 0x54 <__SREG__+0x15>
  40:   88 e3           ldi     r24, 0x38       ; 56
  42:   90 e0           ldi     r25, 0x00       ; 0
  44:   29 81           ldd     r18, Y+1        ; 0x01
  46:   fc 01           movw    r30, r24
  48:   20 83           st      Z, r18
  4a:   89 81           ldd     r24, Y+1        ; 0x01
  4c:   9a 81           ldd     r25, Y+2        ; 0x02
  4e:   01 96           adiw    r24, 0x01       ; 1
  50:   9a 83           std     Y+2, r25        ; 0x02
  52:   89 83           std     Y+1, r24        ; 0x01
  54:   89 81           ldd     r24, Y+1        ; 0x01
  56:   9a 81           ldd     r25, Y+2        ; 0x02
  58:   84 36           cpi     r24, 0x64       ; 100
  5a:   91 05           cpc     r25, r1
  5c:   8c f3           brlt    .-30            ; 0x40 <__SREG__+0x1>
  5e:   80 e0           ldi     r24, 0x00       ; 0
  60:   90 e0           ldi     r25, 0x00       ; 0
  62:   0f 90           pop     r0
  64:   0f 90           pop     r0
  66:   df 91           pop     r29
  68:   cf 91           pop     r28
  6a:   08 95           ret

The disassembly makes somewhat sense, only that I miss the interleaved source code.
Interestingly enough, the output also includes a stab section, where I also find the main segment disassembled:
#include <avr/io.h>

int main() {
  30:   20 00           .word   0x0020  ; ????
  32:   00 00           nop
  34:   80 00           .word   0x0080  ; ????
  36:   00 00           nop
  38:   00 00           nop
    for(int i=0; i<100; i++) {
  3a:   00 00           nop
  3c:   40 00           .word   0x0040  ; ????
  3e:   00 00           nop
        PORTB=i;
  40:   80 00           .word   0x0080  ; ????
  42:   00 00           nop
  44:   00 00           nop
  46:   00 00           nop
  48:   5a 00           .word   0x005a  ; ????
    for(int i=0; i<100; i++) {
  4a:   00 00           nop
  4c:   80 00           .word   0x0080  ; ????
  4e:   00 00           nop
  50:   00 00           nop
  52:   00 00           nop
  54:   91 00           .word   0x0091  ; ????
  56:   00 00           nop
  58:   80 00           .word   0x0080  ; ????
  5a:   00 00           nop
  5c:   00 00           nop
  5e:   00 00           nop
  60:   b7 00           .word   0x00b7  ; ????
    }

}

Now the output includes source code, but the disassembly is wrong.
How do I get an output were both is correct: the disassembled instructions and the interleaved source-code?
(avr-gcc (GCC) 9.3.0. Interleave Assembly and Source for avr-objdump does not seem to have the problem, although he's using the same compiler flags...)

The .stabs section contains debugging info, not actual code. There is no
point in trying to “disassemble” it. The -D option of avr-objdump
means “disassemble everything, whether or not you believe it's machine
code”. Not what you want. For your purpose, -S should be enough.
I do not know why your main() is displayed without source code. I
tried your exact same program with the exact same commands and I do see
the source interleaved with the assembly. I am using avr-gcc 5.4.0 and
avr-objdump 2.26.20160125 as shipped on Ubuntu Eoan.

Thanks. Indeed, if I downgrade the compiler to 5.4.0 it works as well. I'll try to pinpoint the version that introduced the problem and report a bug once I'm able to reproduce it in a clean environment.


text:
Need help with idea before I buy parts. Want to use arduino to act as the button on a TRRS wire to answer and hang up calls
I intend to buy CH340G USB Microcontroller Board Arduino UNO R3 ATmega328P Development Module
I want to use it and a MOSFET or whatever needed to act as a button for a TRRS wire I already have home made to act as a call button. I know it has to be 0ohm when activated but im not sure if this can be done and with what and how.
I was hoping to have a key on my computer activate the code from the arduino which I dont mind figuring out later but I just need to get an idea on what to use for the button and how I would activate it after wiring.

most (all?) MOSFETs have a diode across source to drain, so that won't work very well with an AC signal like music. You could use a reed relay. The only other non-polar switch i know if is a CDS, but those might have too high a resistance here.

Its not being used for music just to activate like if I took a standard momentary push button from mic to gnd on the TRRS plug. But I wanna do it from Arduino so I can control it on hotkey or mouse button.

you could likely use an nchan fet wired source to gnd, drain to the other side of the button, whatever that's connected to.

Better to use an opto isolator or a small reed relay to keep everything isolated.

If you are trying to answer phone calls, bear in mind that the ring signal is something like 90VAC. (For historical reasons it is enough voltage and current tp ring an electromechanical bell. I've gotten a pretty unpleasant shock before when I was working on phone wiring when a call came in.
That's a problem for 2 reasons: It's too much voltage for all CMOS circuits and most transistors, and transistors can't switch AC. You should isolate the TRRS pins from your digital circuitry, and use a "digital" relay to close the circuit.

DuncanC: This is for a Cell Phone TRRS 3.5mm Audio cable. I dont think its rated that high..
@Majenko: That actually looks like a neat idea. I just need to figure out how that works with a switch that should be off to start.

a reed relay has normally open contacts

For this a reed relay would be my ideal choice. When you're working with audio signals adding anything in there that's not 100% passive could corrupt the audio signal.


text:
Why am I only seeing 1.3V on an analog pin that has been set to high using digitalWrite?
I have run into a bit of trouble with a sewable electronics project. I am trying to power a SparkFun 7-Segment Serial Display from one of the analog ports of a ATmega328 board. I realize this is unconventional, but I designed the circuit to not require any crossed connections to make the sewing a bit easier, and that was the only way to do it. The display wouldn't light up, and after some debugging with a multi-meter it turned out that the analog pin I was using (A3) was only at 1.3V despite a digitalWrite command. I tested the same command on one of the other analog pins (A0) and it produced 5V as expeced. When I bridge the VCC pin and A3, everything works fine. When I set A0 to 5V , and bridge it with A3, the output voltage drops to 1.8V relative to GND.
The really weird thing is that just running the example code from the sparkfun website without any modifications still somehow results in a \~1.2V reading from A3 to GND. I have no clue what is going on here. Usually I would disconnect the display from A3 and keep testing, but I am trying to avoid it. Troubleshooting is difficult as I had to clip the excess tails to prevent short circuits making me extremely reluctant to disconnect anything until I have figured out what the problem is, as the thread is very hard to work with, and it took the project on the order of 60 man-hours to get where it is. I was hoping someone here might know what is going on, or point me in the right direction.

You should measure required current first. There is possibility the A3 output driver is already destroyed. I'd expect it needs over 100mA if you lit everything on.

The doc says it should not draw more than 14.1 mA @ 5 V.

The sample code you mention uses Hardware SPI, with fixed pins. Check the desired digitalWrite separately and if it shows your atmega328 still alive, you can post your actual problem here.

I am using the I2C example code. What are you looking for me to check? I can get the atmega in the lillipad to control the other pins just fine.

The supply current is without including the LEDs. That's just for the ATMega328P on the board. You can add up to 24mA for the LEDs (with 1kΩ resistors on the board and 2V forward voltage for the LEDs, and multiplexed in groups of 8) depending on the number of LEDs turned on at any one time.  Yo A3 pin is daid!  You should never try and power anything like that from an IO pin.

As I said, I don't have a choice without crossing wires. Where would I find the actual maximum draw?

"I don't have a choice without crossing wires." You don't have a choice period. If you draw more than 14 mA from the pin, you will overload it and possibly burn it out. If you tried to power a 7 segment serial display from an analog pin on your Arduino you very likely fried the pin, and possibly the whole board.

A single LED will draw up to 20mA. (or more for a high current LED. A 7-segment display will draw 7x4 times that. If it's multiplexed, it might only light one digit at a time, so only 7 times the single LED current. Plus the 14 mA for the microcontroller on that unit adds up to way, waaaay more than you can draw from any one output pin on an Arduino.


text:
Is it required to delete variables before going to sleep?
This tutorial shows how to put the arduino to sleep and use a watchdog to wake up at intervals:
https://youtu.be/urLSDi7SD8M
I been studding c++ and as I am getting better I am instantiating objects with the new keyword. I have learned that if you create something with the new keyword you are responsible for deleting it from memory when you no longer needed. But I do not know if this applies when you put arduino to sleep.
Anyways my question is in the comments of the code:
Foo * someObject;

void setup()
{
    someObject = new Foo(arg1, arg2, ..); // crete an instance of someObject
   // init pins etc..
}

void loop()
{
     if(button1Pressed())
     {

          // **** DO I HAVE TO DELETE OBJECTS BEFORE GOING TO SLEEP? Do I need this line? ****
          delete someObject;

          gotToSleepAndWakeUpIn4Seconds() ;  // places arduino in sleep mode and wakes up again in 4 seconds

          int x = 0; // this line never executes arduino is on sleep mode and will wake up again in 4 seconds
     }

     // more code
     if(something)
        someObject->executeFunction1();

     // etc...
     // ....
}

No you don’t.  You just have to free it before you try to use that memory for anything else.  Really on a microcontroller I would create the object in a smaller scope and try to do everything in my power to avoid having to use new or any other form of dynamic allocation.  There are usually better ways around it in this kind of environment.  Very different from writing code to run on a PC.

You have probably learnt that objects created with new are stored in
the heap, while globals are stored in the .data and .bss sections, and
locals on the stack¹. This distinction, however, only exists in the
software. At the hardware level, .data, .bss, heap and stack are just
arbitrary portions of the RAM.
Think of what would happen if the RAM was erased, or somehow corrupted,
when the microcontroller sleeps. Not only would that affect the
heap-based objects, but also every variable in the program. And even the
return address from the call to gotToSleepAndWakeUpIn4Seconds() would
be lost, so the CPU would not know where to resume execution when it
wakes up. The only reasonable thing to do at wakeup would then be to
restart the program from scratch. And this is actually what happens when
you reset the microcontroller².
But a sleep is not a reset. The contents of the RAM is preserved while
sleeping. This means that the whole state of the program is preserved:
locals, globals and heap-based objects. No need to delete and re-create
stuff.
As a side note, if you can allocate memory statically, this is usually
better than dynamic allocation, ans you avoid the risk of heap
fragmentation:
Foo someObject(arg1, arg2, ..);  // static global instance

void loop()
{
    // Some code, then,

    if (something)
        someObject.executeFunction1();
}

Notes:
¹ As an optimization, locals of the current stack frame may be in CPU
registers, but this doesn't change the conclusion.
² On AVR, a warm reset doesn't loose the RAM, but it is then
reinitialized by the C runtime. A cold reset (power-cycle) does loose
the RAM.


text:
Custom build of arduino on a pcb
I am running my Arduino based from the ATMEGA328P-PU chip from a 4v battery with this setup:

Everything works great and now I will like to make my project permanent building a custom PCB from easyeda.com. Anyways this question is not about how to create the custom PCB I have already made one and it works great. This is the PCB that I created:

Because I liked it so much now I want to build it even better. For example now I will like to combine the crystal with the 22pf ceramic capacitors into one small part.
Question
Can I use ----THIS---- part instead of the basic 22pf capacitor and the big 16Mhz crystal? In other words I want to replace the left picture with the right picture:

If its possible to use part 7325-1600A2210-00 then where can I find information on what pins to connect to the atmega328 chip and what pins to connect to ground? 7325-1600A2210-00 has 4 pins. To me it makes sense to connect 2 of the pins to pins 9 and 10 and the other 2 pins to ground. Will this work?

Can I use ----THIS---- part instead of the basic 22pf capacitor and the big 16Mhz crystal?

No. That is just a crystal. You still need the capacitors.  If you want a single device then you need a ceramic resonator.
Also you're lacking any decoupling capacitors in your circuit. You may find it works for now, but it will become flaky when you start getting it to do things.


text:
Placing decoupling capacitors when building an Arduino PCB with Atmega328-PU
I have previously asked this question:
Custom build of arduino on a pcb
And thanks to the answer by Majenco I have learned that my circuit works a lot better when adding a capacitor. For example I am using the NRF24L01 and it is much more stable when using a capacitor. I am placing the capacitor for now next to the power supply like this:

Right now I am running this on a breadboard. The Atmega328 chip is very cheap compared to the arduino uno board; therefore, I will like to continue building my projects based on the atmega328P-PU chip.
Anyways before printing the PCB based on the Atmega328P-PU chip, where should I place the capacitors in order to reduce the most noise? The capacitors are very cheap and making one good design will enable me for all my future designs to be based from this one.
From researching on the internet I see a lot of different examples. Everyone uses different capacitance sizes. For example I have found this:

I got that from this link: https://www.autodesk.com/products/eagle/blog/what-are-decoupling-capacitors/
On other places they say to place the capacitance closest to the pins such as from this video. If that is true should I just place one capacitor on pins 7 and 8. Lastly the other capacitor on pins 20 and 22?
I do not mind soldering extra pins knowing my circuit will have the best performance.

There is a reason that many chip has VCC and GND next to each other or nearby. You should place the capacitors close to those pins, for both VCC and AVCC. Read the datasheet as it provide much more information.

The Autodesk link explains it very well.
You should place small/fast decoupling capacitors (0.1uF) close to the power pins of your on-board ICs to deal with local spikes in power consumption of those devices.
Place a larger/slower decoupling capacitor (1uF or larger, depending on many factors such as distance of the power supply from the board and expected power consumption) somewhere on the board to deal with varying loads and ripples in your power supply.
This has been common practice at least since I’ve started with electronics about 40 years ago (and probably much longer).


text:
Using different processors when it comes to arduino
I decided to learn Arduino in this quarantine so I am still a newbie when it comes to micro controllers. Basically I been doing all my projects based on the ATMEGA328P-PU:

I even converted my breadboard designs to custom PCBs like this one:

I am running out of Atmega328P-PU processors and I am about to buy more. But instead of going with the traditional Atmega328P should I buy other processors?
This are my alternatives:

They all are about the same price. For example the ESP32 is 10 times faster and it was a lot more sram and pins. Anyways this are my questions:

Why do people buy the Atmega328P when there are faster and more powerfull processors for the same price?

I been saving a lot of money by buying the Atmega328P processor by itself and then building Arduino using the crystal, ceramic capacitors etc. There are so many tutorials on how to build that such as on THIS LINK and many more. But how can I build an ESP32 running arduino code on a breadboard? I have not been able to find that tutorial. All the tutorials I find use the ESP32 already soldered to a PCB. I want to build my custom PCB using a ESP32 for example. Where can I find that tutorial?

If I decide to buy the ESP32 or ESP8266 should I build my code using the arduino IDE? I will have to add stuff to arduino IDE so it works with the ESP32. What are the benefits of using other IDEs?

I am thinking about the ESP32 and ESP8266 because I see a lot of people using them on the internet and they are much more powerfull than the Atmega328P for the same price. What other processors do you guys recommend?

did you see Teensy 4?

Forget the esp8266. The IO is to restrictive. ESP32 if far far better.

I love the 8266, mostly because of the price and the esp-01's size. ESP's don't really do breadboards. If you want small and cheap, look for "wroom esp32" modules, but keep in mind the pin spacing is unlike breadboards. I use 10cm M+F dupont cables to run from MCU pins to breadboards. The nodeMCU boards have so many vcc+gnd pins that I can often "dead bug" sensors and outputs w/o a breadboard or pcb using F+F dupont cables. I would look into the "blue pill" arm boards, which now have official arduino support. Lastly, there's a way to run a 328 w/o a crystal, at 8Mhz, might interest you.

For learning it really doesn't matter much of which MCU to choose from. For actually embedded project development, it really depends on what you want to do with your dev board. I thought that I would just offers some of my thoughts and experiences here as a reference, there is no right or wrong answers. I'm sure many people have their own favourites and considerations when picking their MCU.

Why do people buy the Atmega328P when there are faster and more powerfull processors for the same price?

ATmega328p get popular for its long history (it is 2-decades old) and Arduino, personally I feel that there are better MCU with compatible features, memory size, etc. even within the AVR series to replace ATmega328p, I actually developed an ATtiny3217-based Arduino board last month, it is cheaper (on chip BOM cost) and it does not need crystal for running at 20MHz with decent accuracy, it offers almost similar I/O pins, memory size, UART/I2C/SPI as ATmega328, but it is a much modern chip with many features that are not available in ATmega328 (such as DAC, touch support, event system, etc.). ATmega3208/4809 is another interesting candidate for my next project.

All the tutorials I find use the ESP32 already soldered to a PCB. I want to build my custom PCB using a ESP32 for example. Where can I find that tutorial?

ESP32 (and ESP8266 like ESP-12F as well) come with a compact form factor that is ready to be integrated into your design, most of the design needs are USB-interface, power supply and some peripheral (such as auto-reset circuitry, power and blinking LEDs, etc.). You can take a look at Adafruit HUZZAH ESP8266 which is basically based upon an ESP-12E module with added circuit for reset, voltage regulator.

If I decide to buy the ESP32 or ESP8266 should I build my code using the arduino IDE? I will have to add stuff to arduino IDE so it works with the ESP32. What are the benefits of using other IDEs?

Arduino IDE is not the only IDE for programming an Arduino, PlatformIO is one of the alternatives IDE for Arduino programming, one of the main benefits is better project and dependency(libraries) management and the flexibility on compiling/building process (e.g. pull in the floating point supports on AVR chips). Take a look at these two YouTube videos to see how it looks like and how to set it up:

A Better Arduino IDE – Getting Started with PlatformIO
PlatformIO – Using External Libraries

I am thinking about the ESP32 and ESP8266... What other processors do you guys recommend?

As I mentioned at the beginning, it really depend on your selection criteria. ESP8266 and ESP32 is generally the choice for its WiFi capability, however, you won't chose ESP8266 for anything related to ADC because it has only one ADC with a reference voltage of 1v. ESP32 looks great for for its faster CPU, it however generated a lot of noise when you want to reading sensor data even though it offers 12-bit ADC resolution versus 10-bit in ATmega328p. Its ADC also has non-linear issue on some of the old batch of ESP32 chips.
On the question of "what other processors do you guys recommend"? If no requirements for wireless connectivity, I personally like STM32F103 Blue Pill, for its better ADC (12-bit), more memory, and multiple UARTs, and cheap but there are things that you need to be aware of (such as fake STM32 chip and design faults).
Whatever you decided for your next choice of MCU, I'm sure it won't be your last one, as your experience grow and your project get more complex, you will know that there is no perfect MCU that fit it all.

Sometimes faster and more powerful is not needed. If you just needed a simple timer, and it needed to be battery operated, a processor like the ATmega328 would be the better choice. It really depends on the application.

The ESP32 is a great device. But the A/D converter on it is less than stellar. It is not as consistent compared to the A/D in the Atmega328P.

The ESP32 is more fussy about the power supply requirements compared to the Atmega328P. Lots of people get themselves into trouble when they use poor design practices with the ESP32/ESP8266 modules. Poor practices that worked well enough for lower power and lower speed processors like the Atmega328P. Most people don't bother with reading the datasheet for the processors. They just try and copy stuff they fine on the Internet. And the Internet is full of poor quality information by people who don't really understand much of what they are working with.

If you want to start using the ESP32, then do yourself a favor and buy a working board with a power supply and not just buy a module. It will save you many hours of grief.

The Arduino IDE makes it easy to get stuff working. There also is Python, but it is less popular. There is a lot more information available for the Arduino IDE, and available libraries. And that makes development a lot easier. There are other ways, but the learning curve is much steeper.

The "Blue Pill" STM32F103C8T6 based board is a lot of capability for little money. The CPU runs on 3.3 volts like the ESP devices. It has gain a lot of popularity in the last few years but there isn't as much information as for the Atmega328P.

The STM32F103C8T6 and the ESP devices are 3.3 volt based designs. And they require 3.3 volt devices to interact with. There are some devices that are mostly 5 volt only devices. Like a character LCD. It is easier to interface that to a 5 volt processor.
There is lots that I could still say but it would take hours. But what you should do before deciding on a part is to decide what the needs of the project are. That will often guide you towards the part you should use.
One more note. The ESP devices are running a lot of code on top of the Setup and Loop functions. There is lots of stuff going on in the background to support the WiFi capability. And you don't have the kind of control that you could have with a non-ESP device. But if you want that part then you need to accept that limitation.


text:
Cannot program two arduinos at the same time because they both use the same COM port
I am not able to program my second arduino because they both use the same com port. In other words this picture says it all:

In order to upload my sketch I have to disconnect one arduino. How can I tell windows to use a different COM port?
It will be nice if I do not have to disconnect one arduino evey time I want to upload a sketch. I already restarted my computer and I get the same problem.

Can't you just choose another port in the port properties? It's been a while since I futzed in windows device manager...

That's the answer thanks Majenko

Never in my life have I seen that Windows allocates the same COM port number to two different devices.. weird

@MaximilianGerhardt The only explanation I can think of is that the two UARTs are completely identical and windows can't tell them apart at all.  Counterfeit FTDI chips are known to clone hardware serial numbers.  Windows also usually remembers the COM number a device had when it was last seen on a particular USB port, but it usually assigns a different COM number by default even for the same device if you plug it into two different USB ports.  It could be that a cloned serial combined with a first-plug while the device['s clone] being already plugged in led to this COM port doppelganger...

@J... the cloning thing makes a lot of sense. I just recalled only one of my Arduinos would change port numbers when connected to different ports, and I thought that was the dead one. It also happened to be original.

I did not knew I could change the port on windows. This is how I did it thanks to @Majenko's comment.


text:
Cannot enable watchdog timer when using Arduino 8mhz bootloader
I am running my Arduino projects like this:

My goal is to have this project run at 8mhz so that (1) battery last longer and (2) so that I am following the specs. I was able to burn a 8mhz bootloader to my Atmega328 chip thanks to this video: https://www.youtube.com/watch?v=fzZ2TR_mwgs
After following the video I am able to run sketches at 8mhz and they consume less current. But my original project crashes to the point where I have to burn a bootloader again. Even if I press the reset button it will not become responsive. I have discovered that this line of code is the one that makes my atmega328 chip unresponsive:
wdt_enable(WDTO_4S);  // #include <avr/wdt.h>

I find out about that because removing that line made my project work. That line enables waking up after 4 seconds. So I basically perform some work and go to sleep for 4 seconds. I then repeat the same steps forever in order to save battery.  So before going to sleep I execute this:
// wake up from sleep after 4 seconds
wdt_enable(WDTO_4S);

// go to deep sleep
if (true)
{
    // BIG difference when in sleep
    // Diable ADC (analog to digital converter)
    ADCSRA &= ~(1 << 7);

    SMCR |= (1 << 2); // power down mode
    SMCR |= 1;        // enable sleep;

    // BOD DISABLE (big difference when in sleep only)
    MCUCR |= (3 << 5);                      // set both BODS and BODSE at the same time
    MCUCR = (MCUCR & ~(1 << 5)) | (1 << 6); // then set the BODS bit and clear the BOSE bit at the same time

    __asm__ __volatile__("sleep");
}

// this line will not execute....

Anyways how could I solve this problem? Should I keep the original project and just replace the crystal to  8mhz? I will then have to keep in mind that all delays will be half the speed correct?

Try power cycling the UNO when the boards stops responding. That should reset the watchdog settings. Just pressing reset doesn't disable the watchdog, as far as I know.
The bootloader doesn't know you enabled the watchdog, and if it takes more that 4 seconds, you get stuck in an infinite loop. You could try using the optiboot bootloader instead. That one resets the watchdog when it runs.
Thirdly, you could enable the watchdog interrupt. If you do that the MCU will still wake up after 4 seconds of sleep, but it will resume you code, instead of doing a reset. Doing this will make it so the bootloader only runs once.

Your delays are probably what is killing you. If you have delays longer than the WDT time that will cause a WDT timeout. Remember the Delay function does nothing but burn time, nothing else is processed. Go to the Millis or something like that as recommended many times in the Arduino forums.


text:
Animation of led strip with ESP32 does not work when WiFi is in use
I am using the ESP32 for a simple project. I know how to animate an led strip using atmega328p with arduino but when I animate it on the ESP32 it does not work that great. It will be nice if I can use the same ESP32 to run my entire project without having to include another MCU. Has someone managed to be able to animate an led strip meanwhile using wifi on the ESP32 ?
This is the code I use to animate an LED stip meanwhile using wifi. I wrote this code myself so maybe I am doing something wrong. It works better than any of the libraries I have found online. The library that works best is esp32WS2811-master. But still this code works better than that library in my case.
#include <Arduino.h>
#include "WiFi.h"
#include <Adafruit_NeoPixel.h>

// we will runt the task that animates led strip on a separate core of arduino
TaskHandle_t Task1;

// where led pin is connected and number of leds to animate
#define PIN 32
#define NUM_LEDS 80

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

// mutex that helps enter critical sections meanwhile we animate led strip
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;

// it will run on core 0 of esp32. Responsible for animating led strip.
void loop2(void *parameter)
{
   uint32_t _color = strip.Color(0, 0, 0);

   for (;;) // infinite loop
   {
      _color = strip.Color(0, 0, 255);

      // animation 1
      for (uint16_t i = 0; i < strip.numPixels(); i++)
      {
         strip.setPixelColor(i, _color);

         //portDISABLE_INTERRUPTS();      // arternative to portENTER_CRITICAL
         portENTER_CRITICAL(&mux);        /* start critical section */

         strip.show();

         //portENABLE_INTERRUPTS();       // alternative to portEXIT_CRITICAL
         portEXIT_CRITICAL(&mux);         /* end critical section */

         vTaskDelay(15);                  // one tick delay (15ms) in between reads for stability
      }

      // animation 2
      _color = strip.Color(0, 255, 0);
      for (uint16_t i = 0; i < strip.numPixels(); i++)
      {
         strip.setPixelColor(i, _color);

         //portDISABLE_INTERRUPTS();      // arternative to portENTER_CRITICAL
         portENTER_CRITICAL(&mux);        /* start critical section */

         strip.show();

         //portENABLE_INTERRUPTS();       // alternative to portEXIT_CRITICAL
         portEXIT_CRITICAL(&mux);         /* end critical section */

         vTaskDelay(15);                  // one tick delay (15ms) in between reads for stability
      }
   }
}

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

   // disabling wifi helps but we need it
   // WiFi.mode(WIFI_OFF);

   // init led strip
   strip.begin();
   strip.setBrightness(4);
   strip.show(); // Initialize all pixels to 'off'

   // create a task that runs on core 0 of esp32
   xTaskCreatePinnedToCore(
       loop2,
       "Task_1",
       1000,
       NULL,
       2, // priority of 0 is the lowest.
       &Task1,
       0 // use core 0. Core 1 is the default core
   );

   // continue running code on default core 1 of esp32

   // Set WiFi to station mode and disconnect from an AP if it was previously connected
   WiFi.mode(WIFI_STA);
   WiFi.disconnect();

   Serial.println("Setup done");
}

// on main loop scan network just to show how led strip does not work great when wifi is in use
// This code I copied and pasted from the WiFi examples of the esp32
void loop()
{
   Serial.println("scan start");

   // WiFi.scanNetworks will return the number of networks found
   int n = WiFi.scanNetworks();
   Serial.println("scan done");
   if (n == 0)
   {
      Serial.println("no networks found");
   }
   else
   {
      Serial.print(n);
      Serial.println(" networks found");
      for (int i = 0; i < n; ++i)
      {
         // Print SSID and RSSI for each network found
         Serial.print(i + 1);
         Serial.print(": ");
         Serial.print(WiFi.SSID(i));
         Serial.print(" (");
         Serial.print(WiFi.RSSI(i));
         Serial.print(")");
         Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");
         delay(10);
      }
   }
   Serial.println("");

   // wait 5 seconds for next network scan
   auto end = millis() + (unsigned long)5000;
   while(millis() < end)  {
      vTaskDelay(1);
   }

}

When I run this code the first led flickers. The other LEDs animate great 99.99% of the time. When I disable WiFi this code works great. I still need portENTER_CRITICAL(&mux); or portDISABLE_INTERRUPTS(); for it to work even if I disable WiFi. Has anyone managed to be able to animate an led-strip with the ESP-32 successfully meanwhile using WiFi?
If I am required to use a separate micro controller which one do you guys recommend? The ATtiny85?

it's not the wifi, it's your delay calls and while statements that are stopping the show.

The delay is part of the animation. If I disable the wifi the animation works great @dandavis. I need to animate one led every 15 milliseconds.

well, I know that i can push rgb values over wifi to an esp32 at 30FPS on a 64 pixel strip. If wifi blocked this would look really jerky, but it doesn't, except for occasional hiccups which fix themselves. I didn't even mess with interrupts or explicit flow control. Make your animation routine async (think blink w/o delay) to allow more than one thing at once to happen. For me, this required rewriting the adafruit lib to move the loops into stand-alone callable functions that did a single iteration worth of work at the right time, as determined by the loop()'s logic and millis().

Doesn't all the WiFi management software run on core 0? If you run on core 1 does it improve?

@danvis are you using an addressable led strip?  are you animating your LED by changing the color of one led at a time? If I use a none addressable led strip it works.

@Majenko if I use core 1 it works better. I just get some flickering once every 5 seconds. But the LEDs animate great its just the flickering that I have to somehow figure out how to solve.

I used the FastLed library and it works now. For some reason the adafruit library only works when I am not using the WiFi. This code works:
#include "Arduino.h"
#include <FastLED.h>
#include "WiFi.h"

// we will runt the task that animates led strip on a separate core of arduino
TaskHandle_t Task1;

#define LED_PIN 32
#define NUM_LEDS 108
#define BRIGHTNESS 10
#define LED_TYPE WS2811
#define COLOR_ORDER GRB
CRGB leds[NUM_LEDS];

#define UPDATES_PER_SECOND 100

// scan the network every 5 seconds
void loop2(void *parameter)
{
    for (;;)
    {
        Serial.println("scan start");

        // WiFi.scanNetworks will return the number of networks found
        int n = WiFi.scanNetworks();
        Serial.println("scan done");
        if (n == 0)
        {
            Serial.println("no networks found");
        }
        else
        {
            Serial.print(n);
            Serial.println(" networks found");
            for (int i = 0; i < n; ++i)
            {
                // Print SSID and RSSI for each network found
                Serial.print(i + 1);
                Serial.print(": ");
                Serial.print(WiFi.SSID(i));
                Serial.print(" (");
                Serial.print(WiFi.RSSI(i));
                Serial.print(")");
                Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");
                delay(10);
            }
        }
        Serial.println("");

        vTaskDelay(5000);
    }
}

void setup()
{

    Serial.begin(115200);

    delay(1000); // power-up safety delay
    FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
    FastLED.setBrightness(BRIGHTNESS);

    // Set WiFi to station mode and disconnect from an AP if it was previously connected
    WiFi.mode(WIFI_STA);
    WiFi.disconnect();

    // create a task that runs on core 0 of esp32
    xTaskCreatePinnedToCore(
        loop2,
        "Task_1",
        1000,
        NULL,
        2, // priority of 0 is the lowest.
        &Task1,
        1 // use core 0. Core 1 is the default core
    );

    Serial.println("Setup done");
}

void loop()
{

    // red
    for (int i = 0; i < NUM_LEDS; i++)
    {
        leds[i] = 0xFF0000;
        FastLED.show();
        FastLED.delay(25);
    }

    // green
    for (int i = 0; i < NUM_LEDS; i++)
    {
        leds[i] = 0x00FF00;
        FastLED.show();
        FastLED.delay(25);
    }

    // blue
    for (int i = 0; i < NUM_LEDS; i++)
    {
        leds[i] = 0x0000FF;
        FastLED.show();
        FastLED.delay(25);
    }

    // rgb red green blue

    //ChangePalettePeriodically();
    //FillLEDsFromPaletteColors( startIndex);
}

Please accept your own answer so it doesn't pop up over and over again


text:
How can arduino read a frequency higher than 16Mhz?
I will like to understand how does Arduino measure a frequency. Also how does my voltmeter can measure a frequency as well. Since I am a beginner on using microcontroler I would read a frequency like this:
void loop()
{
    while(digitalRead(myPin)==HIGH)
    {
       // pin is high
    }
    // measure time using millis (this is the time the pin was high)

    while(digitalRead(myPin)==LOW)
    {
       // pin is low
    }
    // measure time using millis (this is the time the pin was low)

}

With this code it makes sense to me how to measure a frequency and a duty cycle. The problem with this code is that it will probably be very slow and I it will probably read frequencies up to 100Hz and less.
So my questions are:

How can arduino read frequencies higher than 100Hz? How does it achieve that?
I Googled arduino's frequency and it shows to be 16MHz. That means arudino can read frequencies up to 16Mhz? Ethernet cables specifically CAT5 has a frequency of 100MHz. That means that it sends signals 100,000,000 in one second! How could Arduino send that many signals in one second if I where to buy a Ethernet shield such as this one?

you can use a digital counter IC to scale down the frequency into something Arduino can handle. Feeding a square wave to an 8-bit counter will make bit 8 oscillate at exactly 1/256th the frequency of the square wave.

How can arduino read frequencies higher than 100Hz? How does it achieve that?

Interrupts (if you want to do it in software) or a magical piece of hardware called the Input Compare peripheral that is built into most MCUs.

I Googled arduino's frequency and it shows to be 16MHz. That means arudino can read frequencies up to 16Mhz?

No, that is the speed the CPU operates at. The maximum frequency signal it can read is usually below that (for SPI it's half that, 8MHz, for example).

Ethernet cables specifically CAT5 has a frequency of 100MHz. That means that it sends signals 100,000,000 in one second! How could Arduino send that many signals in one second if I where to buy a Ethernet shield such as this one?

It doesn't. The shield does. The Arduino just tells the shield what to do, and the chip on the shield does it.

I would not use millis() to measure the period of a signal unless my
program had to deal with extremely low frequencies. And by extremely low
I mean below 1 mHz (one millihertz). For frequencies above
1 mHz, the pseudo-code you show would work just as well or better
using micros().
As the frequency goes up, you will start to look at more fancy options
for measuring it. You could for example count the rising edges from an
interrupt and measure the duration of many (not just one) periods with
micros(). This should work up to a few hundred kHz. For faster
frequencies you can use a hardware timer configured as a counter, and
measure the time it takes to overflow. This should be good for
frequencies up to almost half the CPU frequency (8 MHz).
And for the Ethernet signals, see Majenko's answer.


text:
HC-05 Stuck in slave loop mode (loopback)
got my HC-05 today and accidently set the AT+ROLE=2(slave loop) and now I can't get out of it! Anything I send it just resends it back to me, even commands like AT+RESET and AT+ORGL, they just get returned. I can't figure out how to put the device back in slave mode, your help would be highly appreciated!

H., you have to connect the module in the natural configuration mode to receive AT commands by default, which it is at 38400 Baud. Try sending AT with the arduino console (with carreturn and new line control). If this works then send AT+MODE=0.
Also, from here, you can send AT+ORGL to set original from factory. I usually use a CP2102 usb-serial interface with the hc-05 module, and the YAT serial terminal program from windows, because it is comfortable for me. Greetings. jvarl.


text:
How do I know if I need to use a resistor in a circuit?
I have been trying to find answers on Google to this question but cannot seem to find any answers that actually pertain to what I am wanting to know.  I would consider myself a beginner in the area of electronics having some experience but not understanding how everything comes together outside of the some of the basics.  What I am wondering is this; How can I tell if I need to use a resistor in a circuit?  More specifically, When I am hooking sensors up to an Arduino, how can I determine if I need resistors in the circuit?  Anywhere I look I typically see the default LED/Resistor example but that is not helpful.  It doesn't explain how Arduino/Raspberry PI modules and sensors fit into the equation.  I know the data sheets for the various modules/sensors explain how much current is needed/used by the device but how do I take that and apply it to an Arduino circuit?  Thanks in advance.

the answer it ... it depends. resistors are used to limit current mostly, so it depends if the sensor needs this (and on which pins). The best way is to read into the datasheet, there are mostly examples shown for a typical circuit.

From the specifications of the sensor, you know the maximum current the sensor should be allowed to draw. Suppose you need to put 5v across the sensor.
Then write down Ohm's law: E = IR (the voltage across a component is given by the product of its resistance and the current through it. You need to know the value of a resistor to put in series with the sensor to limit the current to that maximum value or less. So solve Ohms law for resistance (R) of voltage (E):
R = E/I or 5v / maximum current.
That gives you the values of a series resistor to limit the current to the maximum, assuming the sensor has no (or very little) internal resistance of its own.
Or let's look at an LED, where the spec sheet gives you both the maximum current and the internal voltage drop (called "forward voltage"). If you don't need the LED to run at full power (and you probably don't), it will last longer if you limit it to less than that, so let's take 75% as a working figure and calculate the serial resistor to give 75% of maximum current. Red LEDs typically have 2v forward voltage and 15 milliamps max current (but don't build for "typical" parts - build for the part you have). We'll assume a 5v power supply:
R = E/I = (5v - 2v) / (.015 X 0.75)  = 3 / .01125 = 266 Ohms.
So we'd pick an available resistor value close to 266 Ohms (no need to be exact here - we've already left a safety factor by reducing the current 25%).
If you calculate the voltage (again, using Ohm's law) across the 266 (or whatever you used) Ohm resistor, you'll find a voltage drop of about 3v, and adding the LED's forward voltage of 2V, you'll get the power-supply voltage of 5v.

simulate this circuit – Schematic created using CircuitLab
Update:

Why do we need a resistor on an LED which draws 15mA of current which
the Arduino can supply nicely, but we don't on a sensor like the
HC-SR04 which draws 15mA of current?

It's about the behavior of the component or module itself, and that needs a datasheet for the component and spec-sheet for the module. An LED has a forward voltage drop but otherwise looks like a nearly short circuit, so it requires a resistor to protect it from over-current. A module often provides some circuitry around the component to help the user integrate into their project. Of course, how much help it provide is up to the designer. One module may offer nothing more then breadboard-compatible pins where another one - for the same device - may have power-conditioning or power supply components, 3.3v <-> 5v logic-level shifters, and protective circuitry to help protect an expensive component from misuse.
Why does this component need a resistor and another one doesn't? It's up to the electrical behavior of those components. Here's a trivial, but I hope illustrative example:

The device on the left might be considered an LED module, compared to the one on the right which is just an LED. Obviously, all I've done is to solder a current limiting resistor in place on one leg to make a ready-to-go breadboard LED. It is designed for 5v circuits; putting it in a 12v circuit would fry the LED. Here is where I (as the "module designer") used the LED's datasheet to know what circuitry it needed to protect it, and as the "consumer", would need to consult the spec sheet for the module to know how to apply it. If I were selling these things, they'd come with a Spec Sheet: "Only use this LED module in 5v or less applications."]  Hmph - pretty trivial example, but you get the idea.

Thanks for the response.  I think I understand the part of ohms law, however, Where my confusion has been coming in is, we put a resistor on an LED but some of the 'starter' kit tutorials like the ones from SparkFun use different sensor modules such as the HC-SR04 Ultrasonic Sensor, without putting resitors into the circuit.  That is what I don't understand.  Why do we need a resistor on an LED which draws 15mA of current which the Arduino can supply nicely, but we don't on a sensor like the HC-SR04 which draws 15mA of current?  What determines I need a resistor here but not there?

Also, do modules and sensors work differently in determining the need for resistors?  I notice that some modules have resistors built into them.  Does that mean I don't need to add a resistor into the circuit from my Arduino to my module?

The HC-SR04 is an entire module with lots of components on it. It is, itself, an entire circuit.  The LED is a single component. It needs other components with it to make it a circuit. One of those is the resistor.

How can I tell if I need to use a resistor in a circuit?

You can tell because the circuit includes a resistor.
If a circuit needs a resistor the circuit diagram will include a resistor. If it doesn't, then it won't.
The circuit for connecting an LED to an Arduino consists of an Arduino, an LED and a resistor.  Because of that you know it needs a resistor. Because it says it needs a resistor.
A resistor drops a certain voltage across it when a specific current flows through it (Read up on Ohm's Law...). If you need to drop a specific voltage with a specific known current, or if you need to cause a specific current to flow with a fixed voltage, then you use a resistor for that job.
You don't just throw resistors willy-nilly into every circuit you make simply because you see one being used with an LED.
If a device says it runs off 5V and uses 300mA current then you know that you need to hook it up to a power source that is 5V. You also know that the module will use up to 300mA of current from that source, so your source has to be capable of providing at least that much current.