text:
Minimum value I2C-pull up resistor for arduino
I'm trying to determine the minimum value of pull resistor for Arduino Uno
The datasheets says for arduino; VOL = 0,4 for IOL = 20 mA. (VDD = 5V)
For formula for calculation of minimal pull-up is: Rmin=Vcc−0.4V/20mA = 4,6V / 20mA = 230 ohms.
But I saw that people use 0,4V for 3mA. Than the minimal value is 1,6K ohms.
So whats the minimum value of pull-up for arduino?
(also my slave has 0,4 Vol for 20 mA IOL)

I don't follow what you're asking. What's this "0,4 Vol" and what relevance does 20mA have to anything?

They come from the datasheet of arduino UNO

I get the feeling you are regurgitating values you read without understanding what they mean and the context they are used in. I still don't know what this "0,4 Vol" is.

And the concept of "minimum pullup" for I2C is meaningless.

Please check: http://www.ti.com/lit/an/slva689/slva689.pdf. I need to determine the minimum pull-up value. The maximum pull up value depends on the max bus capacitance

Why do you think you need to go to such lengths? Just stick to the recommended range of pullups unless you have a specific reason for using something else (2.2k - 4.7k).

My capacitance is high. About 800pf. I need to reduce the pull-ups

You need to do the same calculation for all the devices on the I2C bus.

What is the slave? Another Arduino uno? Just one slave?

The full datasheet of the atmega328p can be found here: https://www.microchip.com/wwwproducts/en/ATmega328P.
It is called "ATmega328/P AVR MCU with picoPower Technology Data Sheet".
In section "32.7 Two-Wire Serial Interface Characteristics" in table 32-10 on page 372 it shows different voltage levels for the input.
On page 110 it says: "When the TWEN bit in TWCR is set (one) to enable the 2-wire Serial Interface, pin PC4 is disconnected from the port and becomes the Serial Data I/O pin for the 2-wire Serial Interface. In this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation".
I wrote here before that the i2c (the twi hardware inside the microcontroller) did not use the digital pin hardware. However, the i2c pins can still sink a lot of current. Thanks to @Berkay for noticing the same behaviour of the sink current as a normal digital pin.
According to the datasheet the atmega328p of the Arduino uno might not use the digital pin hardware for i2c. It is not known if the same mosfet circuit is used with the same (large) sink current. Perhaps the chip uses a similar mosfet circuit with added slew rate for the output and added spike filter for the input. Perhaps the same mosfet of the digital pin is used after all.
In the Arduino sketch, calling Wire.begin turns on the dedicated i2c hardware in the atmega328p chip. The sink current and voltage levels are according to the i2c specifications.
As you can see in the i2c tutorial by Nick Gammon, the Arduino can sink more than 3 mA.
When the pullup resistors are too low, for example for a sink current of 4 mA, the Arduino uno can handle that, but the slave might not.
When all the pullup resistors are combined, the required sink current can be calculated. The maximum is 3 mA to meet the i2c specifications. To compensate for wire capacitance the i2c bus speed can be lowered.
The i2c bus is not ment to go into a cable, it is not ment for long wires. A cat6 cable is 46 pF/m. That means your 800 pF is for 17 meters cable? That is not what the i2c bus is for. It is for 17 centimeters. The rule of thumb is maximum 50 cm for a normal 100 kHz to 400 kHz i2c bus.

I think you’re not right. The arduino i2c pins can sink up to 20 mA with max VOL 1V. Thats also what you see in the link. Arduino can easy sink 10 mA

This means that the images you see in the link; confirm that arduino is just using digital pin hardware for I2C

By sinking 10 mA, the 'low level' lift till 0,5V. That's acceptable according the I2C spec. (VIL is 1,5V for communication). Pull-up R is about 500 ohms

@Berkay thanks, I have changed my answer a lot. According to the datasheet the digital pin is disconnected. But that can be done before the output stage. However, a i2c bus is for a maximum sink current of 3 mA. You should fix your problem in an other way, perhaps with RS485.

I2c 3ma is a typical value for most of i2c devices. There are some devices who can sink much more like 20mA. Why should i use 3mA  for my calculations then?

It’s the driver of device that need to sink this current. There are plenty of buffers who sinks 30ma for i2c

Also like you see here; http://www.gammon.com.au/forum/?id=10896&reply=5#reply5 It's not a problem to sink 5mA to 10mA

This comes from official spec: "If higher drive devices like the PCA96xx Fast-mode Plus or the P82B bus buffers are
used, the higher strength output drivers sink more current which results in considerably
faster edge rates, or, looked at another way, allows a higher bus capacitance. Refer to
individual component data sheets for actual output drive capability" https://www.nxp.com/docs/en/user-guide/UM10204.pdf P56

The Arduino uno can only do normal 100 kHz to 400 kHz i2c bus. It does not have those extras with higher strength. It is not just the driver that needs to sink the current, the sda and scl are two-way signals. Most sensors do not mess with scl, but an Arduino board as a slave does keep the scl low for clock pulse stretching. Please modify your question and add a lot more information about your project. You need something else to communicate through that long cable that you don't tell us about.

I dont have long cable (max 2m) but a lot of devices. The frequency is 100 kHz. I dont want to go faster. I just wanted to say, like you see in the gammon link, the arduino can sink much more than 3mA. Also my slaves can sink much more. In that case, there is no need to limit your pull-up resistor for 3mA. I can use much lower pull-up for highter current, and for more capacitance.

Like you see here: https://www.nxp.com/docs/en/user-guide/UM10204.pdf P47; also 6mA can be used for 400 kHz. You can lower this frequency to 100kHz and still use 6mA.

@Berkay thanks, do I have to change my answer? Can you tell what devices are they? How many devices? Is that a single cable of max 2 meters or 2 meters to every device? Do the devices have so much capacitance, that is very weird. I still would like to know so much more. The 3 mA is specified as a minimum, but some sensors can not do more, because 3 mA is all that is needed to meet the i2c specifications. Therefor a normal i2c bus is stuck to 3 mA maximum. With processors as i2c slaves, you can go for a higher sink current.

Thanks for your answer. No you don't need to change anything. Classic devices are indeed max 3 mA, but there are plenty of devices with higher capability. I will accept your answer. Have a good day!

I assume you want to work out the minimum value for a pullup resistor that will give a voltage below VIL for an IO pin in open-drain mode.
That is not a simple task, chiefly because you don't know the ON resistance (RDSON) of the low-side MOSFET in the chip.
It's possible to come up with a rough estimate (see here) though.
With VIL of 1.5V and maximum current of 40mA that's an estimated theoretical resistance of 1.5/0.04 = 37.5Ω.
Note: this is just an estimate based on the absolute maximum and DC Characteristics values from the datasheet.
So if we take that value as actually true you can work out the upper half of a voltage divider that would result in 1.5V coming out. There's two ways of doing that - using the resistance or using the current.
Taking the resistance R1=R2(Vin/Vout-1), 37.5 x (5/1.5-1) = 87.5Ω.
If you want to do it with the current (40mA "absolute maximum"), then R=V/I = (5-1.5) / 0.04 = 87.5Ω.
However, that comes with a big caveat.  The IO pin, while it can, for short periods, sink 40mA, it's not designed to do that for long periods. For that 25mA is the recommended maximum. So a resistor should be chosen that keeps the current below 25mA.
Assuming 37.5Ω for the MOSFET resistance, and 25mA through it, that gives a voltage drop across it of 0.94V (well below VIL). The upper resistor in that divider would then be (5-0.94)/0.025=162.5Ω
So to sum up:

The absolute minimum resistor would be 87.5Ω
The recommended minimum resistor would be 162.5Ω
The resistor you would choose to use would bear no real relationship to those values since you would normally choose something more sensible, like 3.3kΩ unless you wanted to run the I2C bus at insanely high speeds or with massive load capacitances.

You really don't need to know the theoretical minimum. You know the maximum already, and all you really need to know is "is the value I'd like to use safe for the IO pin" - i.e., does it draw less than 20mA?
For that you can ignore all the other values. All you care about is your resistance, the Vcc voltage, and the resultant current.
For instance, for a 900Ω resistor with 5V across it you get 5.6mA. You know for a fact that you can never have more than 5.6mA regardless of the resistance of the MOSFET - it can only go down from there.
5.6mA is below the recommended maximum of 20mA, so you're perfectly safe with that resistor.

Thanks but in the I2C-spec, they do the calculations with VOL and IOL. and not VIL.

http://www.ti.com/lit/an/slva689/slva689.pdf

VOL is only quoted at 20mA (I should have used 20mA above not 25, but that's a minor difference). You notice the figure of 0.9 for VOL in the datasheet is the same (near enough) as the final value I calculated above (0.94)...?

The official datahseet, does the calculation not with RDSON. But just simple by VOL and IOL

All are related.

It really doesn't matter what the minimum is, anyway, because you'd be insane to go so low. You should be focussing more on what the maximum is for your capacitance.

Also that is a TI document which assumes values quoted from a TI device's datasheet.

My capacitance is 800pf. So in standard modus, my MAX resistance is about 1.5K. I wanted to use something like 900 ohms

What frequency are you running the bus at?

Standard, so 100 kHz

I make it 1475.27kΩ maximum. A quick test: ignoring the IO pin's values completely, does your chosen resistor value with 5V across it result in less current than the IO pin can handle? I=V/R=5/900=5.6mA - so yes, 900Ω is fine for the IO pin.

But is it stable? I mean, is the drop over the "transistor in the I/O" low enough?

Since it's way below 20mA the answer is yes. Otherwise 20mA would not be 20mA.

The drop needs to be less than 0,4-0,5 volts

The drop doesn't "need" to be anything. The drop is a function of the current through the MOSFET. At 20mA the datasheet states that is no more than 0.9V. So at 5.6mA it will be considerably lower.

If it needs to be anything, it needs to be below lowest VIL for the peripherals.

And where are you getting this 0.4-0.5v range from anyway?

For reliable transfer; it needs to be below VIL. This is 0.3*VDD or 1,5. It suggested that this needs to be lower than 0,5V ( taking 1V margin)

That's a massive margin. A little overly cautious I would say. However, if 20mA is 0.9V, then 5.6mA is 0.9*(5.6/20)=0.25V. More than enough margin for anyone.


text:
Powering servos with external source
I understand why servos and motors require an external power source when run from the Uno, but I've seen a lot of tutorials (for example, this one), where the servo is connected directly to the Arduino's 5V port. I did this, and I think it fried my servo. This is also the method shown on the official Arduino tutorials for Knob and Sweep. In fact, the knob tutorial was the first and last tutorial I tried with my servo -- after trying it, the servo didn't work.
It went like this:
1) Try sweep code without using external supply. Works fine.
2) Try knob code without using external supply. Servo hums without moving and heats up (a lot).
Why do tutorials say to do this if it's not advisable?

"I think it fried my servo". servo? not Arduino?

The servo no longer works, but I’ve used the same Arduino to power other things, including other servos on a separate power supply (now that I know).

Did it die immediately or work for a bit and then die?  Is it possible that you got a bad servo?  I've occasionally gotten one dead servo in the few batches I've ordered.

It went like this:

Try sweep code without using external supply. Works fine.
Try knob code without using external supply. Servo hums without moving and heats up (a lot).

Hmm...I'll add that to the original question.

Mhh, are you sure, that you connected everything correctly? I thought long about this and I see only 2 reasons, that it would heat up like this: 1. You have corrupt hardware or 2. You connected something wrong (like for example wrong polarity). Are you sure that everything is connected in the right way?

Most likely you fried the voltage regulator or the diode on your Arduino board (depending in which power source you used), because the servo has drawn too much current.
Many Arduino Kits or Starter Packs come with really small servos. These do not need much power (especially when no mechanical load is attached to them), so you can power them directly from the 5V pin. Greater/stronger Servos draw much more current and cannot be safely run in the 5V pin.
Many tutorials show this, because it is an easy start for a beginner. And with the right servo it works. More sophisticated cases are not covered there.
EDIT:
Since your Arduino works fine, the voltage regulator and/or the diode should be fine. I tested the Knob example on my Arduino Nano, while powering the servo on the Arduinos 5V pin (and the Arduino is powered over USB). When the Servo is moving, you can see that there is a significant power draw (The power LED gets a bit dimmer), but not so much, that it would be a problem for the Arduino or USB port. Also the example code works as it should, without the servo heating up. I also used a SG90 Micro Servo (9g, by Tower Pro; same as in the tutorial you linked). I also tried the same with an external power source (5V from a powerful USB charger). It still works as intended, but with more power, since the servo now can draw much more current to produce a higher thrust.
So the only thing, I can think of for your problem is, that you either have corrupt hardware, or you have connected it wrong (for example wrong polarity). My Servo has the same color coding for the wires as in the tutorial you linked. Brown is ground, Red is 5V Vcc and Yellow is for the pulse signal.

it’s a small SG90 hobby servo, came with the starter kit I bought. How can I test the voltage regulator and diode on the Arduino?

@Jim421616 did you use an external power supply when powering the UNO and the servo? If the answer is no, then you haven't fried the regulator. If you did, attach it again and then measure if on the +5V pin you actually have 5V. if you haven't (the USB needs to be disconnected, only the power supply needs to be connected), then the onboard regulator is fried. If you have, try connecting the "fried" servo to the external power supply you have (it should be a 5V power supply). If it moves or becomes stiffer, it works, otherwse it doesn't

source: Stack Exchange

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

sort: votes


text:
Can you help me figure out why my arduino code is not working
The code is made to sense were an object is and send out
int const trigPin = 10;
int const echoPin = 9;
int const buzzPin = 1;
int const LED1 = 2;
int const LED2 = 3;
int const LED3 = 4;
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzPin, OUTPUT);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
}
void loop()
{
int duration, distance;
digitalWrite(trigPin, HIGH);
delay(1);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//                                      Go
distance = (duration/2) / 29.1;
if (distance <= 1000 && distance >=0) {
digitalWrite(LED1, HIGH);
} else {
digitalWrite(buzzPin, LOW);
digitalWrite(LED1, LOW);
}
delay(60);
}
//                                      SLOW
if (distance <= 50 && distance >=0) {
digitalWrite(LED2, HIGH);
} else {
digitalWrite(buzzPin, LOW);
digitalWrite(LED2, LOW);
}
delay(60);
}
//                                      STOP
if (distance <= 50 && distance >=0) {
digitalWrite(buzzPin, HIGH);
digitalWrite(LED3, HIGH);
} else {
digitalWrite(buzzPin, LOW);
digitalWrite(LED3, LOW);
}
delay(60);
}

and send out ... send out what to where?

to an LED and or Buzzer sorry I did right it in but for some reason it was cut off

Try adding in some serial output at important code-parts. If you see that these are getting printed you can be sure that the code gets executed until that point. If it doesn't get executed it could also be a problem with the wiring so be sure to check that everythign is set up properly.
At this part:
...
void loop()
{
int duration, distance;
digitalWrite(trigPin, HIGH);
delay(1);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//                                      Go
distance = (duration/2) / 29.1;
...

You are trying to divide an integer (wich can only hold whole numbers) with a real number. Please make sure to use a data type wich can hold more fine-grained results like double or float.
To set up a serial interface you have to add Serial.begin(9600) to you code in the setup() function. Then when you write Serial.println("Your debugging message here") it should be visible in the serial monitor after compiling. (Arduino IDE->Tools->Serial Monitor)

It's not so easy to debug code if you can't compile it at all. Maybe, at some point, he finds out why is everyone using code indentation (and sometimes even C++ Core Guidelines)

I just wanting to know but what would a debugging message be or look like because I am sort of new to Arduino and don't now about too much.

You just write as message whatever helps you. You could for example write as message:
Serial Port Started;
Sensor triggered;
Entering while loop.
It's really just up to you. Whatever helps you figuring out where your arduino is moving arround in your code right now

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


text:
More about Problems with using esp8266
I'm running a project under https://www.youtube.com/watch?v=2AL7HfiRlp4&t=23s
I encounter a problem with "deadly error: ESP8266WiFi.h: No such file or directory", the code indicates '' #include  ''.
I read a conversation between John Romkey and Thonka on July 5th '18. I've deleted all libraries that mention esp8266, esp32 and wifi. But from the conversation I don't know what libraries I have to use now? I use the following code:
/*
 * Mert Arduino and Tech - YouTube
 * WiFi Robot controlled by Phone (WiFibot/Android/IoT/ESP8266)
 * NodeMCU ESP8266 Tutorial 03
 * Please Subscribe for Support - https://goo.gl/RLT6DT
 */

/* include library */
#include <ESP8266WiFi.h>

/*
 * If you have no idea about this library, you can watch the tutorial below
 * NodeMCU ESP8266 Tutorial 01: Programming NodeMCU ESP-12E Using Arduino IDE
 * https://youtu.be/NtyFx1frYB0
 */

/* define port */
WiFiClient client;
WiFiServer server(80);

/* WIFI settings */
const char* ssid = "YOUR SSID";
const char* password = "YOUR PASSWORD";

/* data received from application */
String  data ="";

/* define L298N or L293D motor control pins */
int leftMotorForward = 2;     /* GPIO2(D4) -> IN3   */
int rightMotorForward = 15;   /* GPIO15(D8) -> IN1  */
int leftMotorBackward = 0;    /* GPIO0(D3) -> IN4   */
int rightMotorBackward = 13;  /* GPIO13(D7) -> IN2  */

/* define L298N or L293D enable pins */
int rightMotorENB = 14; /* GPIO14(D5) -> Motor-A Enable */
int leftMotorENB = 12;  /* GPIO12(D6) -> Motor-B Enable */

void setup()
{
  /* initialize motor control pins as output */
  pinMode(leftMotorForward, OUTPUT);
  pinMode(rightMotorForward, OUTPUT);
  pinMode(leftMotorBackward, OUTPUT);
  pinMode(rightMotorBackward, OUTPUT);

  /* initialize motor enable pins as output */
  pinMode(leftMotorENB, OUTPUT);
  pinMode(rightMotorENB, OUTPUT);

  /* start server communication */
  server.begin();
}

void loop()
{
    /* If the server available, run the "checkClient" function */
    client = server.available();
    if (!client) return;
    data = checkClient ();

/************************ Run function according to incoming data from application *************************/

    /* If the incoming data is "forward", run the "MotorForward" function */
    if (data == "forward") MotorForward();
    /* If the incoming data is "backward", run the "MotorBackward" function */
    else if (data == "backward") MotorBackward();
    /* If the incoming data is "left", run the "TurnLeft" function */
    else if (data == "left") TurnLeft();
    /* If the incoming data is "right", run the "TurnRight" function */
    else if (data == "right") TurnRight();
    /* If the incoming data is "stop", run the "MotorStop" function */
    else if (data == "stop") MotorStop();
}

/********************************************* FORWARD *****************************************************/
void MotorForward(void)
{
  digitalWrite(leftMotorENB,HIGH);
  digitalWrite(rightMotorENB,HIGH);
  digitalWrite(leftMotorForward,HIGH);
  digitalWrite(rightMotorForward,HIGH);
  digitalWrite(leftMotorBackward,LOW);
  digitalWrite(rightMotorBackward,LOW);
}

/********************************************* BACKWARD *****************************************************/
void MotorBackward(void)
{
  digitalWrite(leftMotorENB,HIGH);
  digitalWrite(rightMotorENB,HIGH);
  digitalWrite(leftMotorBackward,HIGH);
  digitalWrite(rightMotorBackward,HIGH);
  digitalWrite(leftMotorForward,LOW);
  digitalWrite(rightMotorForward,LOW);
}

/********************************************* TURN LEFT *****************************************************/
void TurnLeft(void)
{
  digitalWrite(leftMotorENB,HIGH);
  digitalWrite(rightMotorENB,HIGH);
  digitalWrite(leftMotorForward,LOW);
  digitalWrite(rightMotorForward,HIGH);
  digitalWrite(rightMotorBackward,LOW);
  digitalWrite(leftMotorBackward,HIGH);
}

/********************************************* TURN RIGHT *****************************************************/
void TurnRight(void)
{
  digitalWrite(leftMotorENB,HIGH);
  digitalWrite(rightMotorENB,HIGH);
  digitalWrite(leftMotorForward,HIGH);
  digitalWrite(rightMotorForward,LOW);
  digitalWrite(rightMotorBackward,HIGH);
  digitalWrite(leftMotorBackward,LOW);
}

/********************************************* STOP *****************************************************/
void MotorStop(void)
{
  digitalWrite(leftMotorENB,LOW);
  digitalWrite(rightMotorENB,LOW);
  digitalWrite(leftMotorForward,LOW);
  digitalWrite(leftMotorBackward,LOW);
  digitalWrite(rightMotorForward,LOW);
  digitalWrite(rightMotorBackward,LOW);
}

/********************************** RECEIVE DATA FROM the APP ******************************************/
String checkClient (void)
{
  while(!client.available()) delay(1);
  String request = client.readStringUntil('\r');
  request.remove(0, 5);
  request.remove(request.length()-9,9);
  return request;
}

install esp8266 boards package https://github.com/esp8266/Arduino#installing-with-boards-manager

I installed it. Anyway #include <ESP8266WiFi.h>. ''ESP8266WiFi.h:No such file or directory''

did you select an esp8266 board in tools menu?

yes, many boards

reinstall esp8266 boards package

OK!!! I was a bad installer

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


text:
STM32Ethernet UDP misses some packets
Using STM32Duino on Nucleo F429ZI:
#include <LwIP.h>
#include <STM32Ethernet.h>
#define UDP_TX_PACKET_MAX_SIZE 512
#include <EthernetUdp.h>

IPAddress remoteIP;
unsigned int remotePort;

EthernetUDP Udp;
uint8_t packetBuffer[UDP_TX_PACKET_MAX_SIZE];

void setup()
{
  Serial.begin(115200);
  IPAddress localIP = /***/;
  IPAddress netmask = /***/;
  IPAddress dns = /***/;
  IPAddress gateway = /***/;

  Ethernet.begin(localIP, netmask, dns, gateway);
  uint8_t *mac = Ethernet.macAddress();

  int port = 8888;
  Udp.begin(port);
}

void loop()
{
  processUDPMessage();
}

void processUDPMessage(void)
{
  while (int size = Udp.parsePacket())
  {
    if (size > 0) parsePacket(size);
  }
}

void parsePacket(int size)
{
  remoteIP = Udp.remoteIP();
  remotePort = Udp.remotePort();

  Udp.read(packetBuffer, size);
  Serial.println((char *) packetBuffer);
}

If I received at least 4 packets at the same time, one of them is not received. Each packet is less than 50 byte long.
Is there anything I could do to improve the reliability of my code?

are you sure it is STM32duino by Roger Clark and not STM32 by STM? does STM32Duino  support F4 and STM32Ethernet? the experts are here https://www.stm32duino.com

The STM32 Core is by STM, the STM32duino STM32Ethernet library is by "Various" and STM32duino LwIP is by Adam Dunkels.

UDP is, by definition, unreliable. If you want more reliability then use TCP.

@Majenko, sorry I don't agree. This is a problem in my code, not in the UDP protocol. I use it since 10 years and I never missed a packet. Here I miss packets every time they are sent. It's a different thing :)

@Mark My point is: that UDP is not a reliable protocol ("reliable" has a specific meaning in networking). That means that the protocol that you design with it must be tolerant of dropped packets. Yes, there may well be problems with your code or with the IP stack in use, but if you designed your protocol properly then it shouldn't care that you lost some packets.

Yes, but this is the second step in my opinion. At first my code should work at least in a predictable environment.


text:
Uno WiFi Dev Ed - Example Sketch with UnoWiFiDevEdSerial1.h library by Juraj errors on compile
Example sketch does not compile, error message
'static void WiFiClass::init()' is private within this context
IDE 1.8.13
Board Uno WiFi Dev Ed.
I have been using this board for several years uploading to Thingspeak using UnoWiFiDevEd.h using Ciao.
Now I am trying to use the UnoWiFiDevEdSerial1.h library but I can't even compile the example code below. Any suggestions?
/*
WiFiLink example: WebClient
https://github.com/jandrassy/arduino-library-wifilink
*/
#include <UnoWiFiDevEdSerial1.h>
#include <WiFiLink.h>
char server[] = "arduino.cc";
boolean sendRequest = true;
WiFiClient client;
void setup() {
Serial.begin(115200);
Serial1.begin(115200);
Serial1.resetESP();
delay(3000); //wait while WiFiLink firmware connects to WiFi with Web Panel settings
WiFi.init(&Serial1);
while (WiFi.status() != WL_CONNECTED) {
delay(10);
}
Serial.println("You're connected to the network");
printWifiStatus();
Serial.println();
}
void loop() {
if (sendRequest) {
/Users/mack/Documents/Arduino/UnoWiFiLink_DevEd/UnoWiFiLink_DevEd.ino: In function 'void setup()':
UnoWiFiLink_DevEd:21:8: error: 'static void WiFiClass::init()' is private within this context
WiFi.init(&Serial1);
^~~~
In file included from /Users/mack/Documents/Arduino/UnoWiFiLink_DevEd/UnoWiFiLink_DevEd.ino:7:0:
/Users/mack/Documents/Arduino/libraries/WiFi_Link/src/WiFiLink.h:44:17: note: declared private here
static void init();
^~~~
UnoWiFiLink_DevEd:21:21: error: no matching function for call to 'WiFiClass::init(UnoWiFiDevEdSerial1*)'
WiFi.init(&Serial1);
^
In file included from /Users/mack/Documents/Arduino/UnoWiFiLink_DevEd/UnoWiFiLink_DevEd.ino:7:0:
/Users/mack/Documents/Arduino/libraries/WiFi_Link/src/WiFiLink.h:44:17: note: candidate: static void WiFiClass::init()
static void init();
^~~~
/Users/mack/Documents/Arduino/libraries/WiFi_Link/src/WiFiLink.h:44:17: note:   candidate expects 0 arguments, 1 provided
Using library Uno_WiFi_Developer_Edition_Serial1 at version 1.0.4 in folder: /Users/mack/Documents/Arduino/libraries/Uno_WiFi_Developer_Edition_Serial1
Using library WiFi_Link at version 1.0.1 in folder: /Users/mack/Documents/Arduino/libraries/WiFi_Link
Using library Wire at version 1.0 in folder: /private/var/folders/5v/dc3kh_4136g2j560dgjg3vww0000gn/T/AppTranslocation/E151A1AA-2F37-45B4-9B3C-A69070247D9C/d/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/Wire
exit status 1
'static void WiFiClass::init()' is private within this context

@Juraj ping - sounds like one for you...

you have the Library Manager version of the WiFiLink library. it doesn't allow to specify a Serial interface and has SC converter library included. use the version from the GitHub repo you linked. did you change the firmware?

it is documented here: https://github.com/jandrassy/arduino-library-wifilink#install-this-library


text:
arduino didn't working properly
 arduino didn't working properly. When i using a alarm program on pin 6 and a blinking led on pin 2 alarm sound beeps once and then goes down but when using only alarm program it works perfectly. I see that arduino can handle one pin perfectly but when it comes to use two pins together it can't handle properly
float sinVal;
int toneVal;
void setup(){
                pinMode(7, OUTPUT);
                pinMode(2, OUTPUT);
}
void loop(){
                for(int x=0; x<180; x++)
                                { //convert angle of sinusoidal to radian measure
                                sinVal = (sin(x*(3.1412/180)));
                                //generate sound of different frequencies by sinusoidal value
                                toneVal = 2000+(int(sinVal*1000));
                                //Set a frequency for Pin-out 8
                                tone(7, toneVal);
                                delay(2); }
                digitalWrite(2, HIGH);
                delay(100);
                digitalWrite(2, LOW);
                delay(200);
}

please format your code properly .... highlight the code and click on the {} icon

How did you manage to get a tone playing with such a big speaker? I thought hooking up such a low impedance load would fry the pin it's connected to.

You need to learn the basics of electroncis before you start hooking random things up like that. That circuit is completely incorrect and most likely will damage the Arduino. Start by reading tutorials, and don't randomly miss out components just cus you don't fancy using them.

with this wiring setting pin 2 HIGH shorts pin 2 to ground and Arduino dies. you must use a resistor in series with LED. and better use one with the speaker too.

I'm not sure but its your power supply. I suggest to used another power supply on your arduino. Use 9V battery and connect it to Vin(+) and GND(-) and test if there is an improvement.

to burn pin 2 for sure?

No. I’m sure you are using Arduino Nano. Vin is on pin 30. And the official website state the Arduino deals 7-12v. Input Voltage (recommended): 7-12 V
Input Voltage (limits): 6-20 V

the LED on the photo shorts pin 2 to ground

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


text:
ESP8266 MQTT client error
#include <PubSubClient.h>
#include <ESP8266WiFi.h>

//EDIT THESE LINES TO MATCH YOUR SETUP
#define MQTT_SERVER "YOUR.MQTT.SERVER.IP"
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

//LED on ESP8266 GPIO2
const int lightPin = 2;

char* lightTopic = "/test/light1";

WiFiClient wifiClient;
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void setup() {
    //initialize the light as an output and set to LOW (off)
    pinMode(lightPin, OUTPUT);
    digitalWrite(lightPin, LOW);

    //start the serial line for debugging
    Serial.begin(115200);
    delay(100);

    //start wifi subsystem
    WiFi.begin(ssid, password);
    //attempt to connect to the WIFI network and then connect to the MQTT server
    reconnect();

    //wait a bit before starting the main loop
        delay(2000);
}

void loop(){

    //reconnect if connection is lost
    if (!client.connected() && WiFi.status() == 3) {reconnect();}

    //maintain MQTT connection
    client.loop();

    //MUST delay to allow ESP8266 WIFI functions to run
    delay(10);
}

void callback(char* topic, byte* payload, unsigned int length) {

    //convert topic to string to make it easier to work with
    String topicStr = topic;

    //Print out some debugging info
    Serial.println("Callback update.");
    Serial.print("Topic: ");
    Serial.println(topicStr);

    //turn the light on if the payload is '1' and publish to the MQTT server a confirmation message
    if(payload[0] == '1'){
        digitalWrite(lightPin, HIGH);
        client.publish("/test/confirm", "Light On");

    }

    //turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0'){
        digitalWrite(lightPin, LOW);
        client.publish("/test/confirm", "Light Off");
    }

}

void reconnect() {

    //attempt to connect to the wifi if connection is lost
    if(WiFi.status() != WL_CONNECTED){
        //debug printing
        Serial.print("Connecting to ");
        Serial.println(ssid);

        //loop while we wait for connection
        while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(".");
        }

        //print out some more debug once connected
        Serial.println("");
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
    }

    //make sure we are connected to WIFI before attemping to reconnect to MQTT
    if(WiFi.status() == WL_CONNECTED){
    // Loop until we're reconnected to the MQTT server
        while (!client.connected()) {
            Serial.print("Attempting MQTT connection...");

            // Generate client name based on MAC address and last 8 bits of microsecond counter
            String clientName;
            clientName += "esp8266-";
            uint8_t mac[6];
            WiFi.macAddress(mac);
            clientName += macToStr(mac);

            //if connected, subscribe to the topic(s) we want to be notified about
            if (client.connect((char*) clientName.c_str())) {
                Serial.print("\tMTQQ Connected");
                client.subscribe(lightTopic);
            }

            //otherwise print failed for debugging
            else{Serial.println("\tFailed."); abort();}
        }
    }
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);

    if (i < 5){
      result += ':';
    }
  }

  return result;
}

The error is 'callback' was not declared in this scope

it is a know bug in Arduino toolchain. copy the callback function before the first use. before client declaration.

@Juraj I've changed it, but I found the same error

update the code in the question

have you tried adding void callback(char* topic, byte* payload, unsigned int length); (exactly that one line with ; at the end) before PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

@Juraj - that's not a bug, that's how C++ rolls - you can't "reference" a function in code before you "declare" it - also, moving callback will mean the callback function will try to "reference" client before it is declared, so, similar (but not exactly the same) error will occur - declaring the function callback before client will fix the issue

@JaromandaX, but this is Arduino .ino and the arduino tool generates the declarations

No, it doesn't. If it did there'd be no error

@JaromandaX in .ino functions can be used before definition without previous declaration. only functions used before setup() are not found. it is a bug of ino to c++ conversion

I apologise for my misinformation in that case - I've always treated .ino as c++ :p

In C++, you can't use or reference a function before it is declared, that's not Arduino specific, it's how C++ "works"
Moving the callback function above the client declaration won't help, because the callback function references client
The only solution is to declare the callback function before it is referenced in client initialisation, but have the definition of callback after
i.e. add one line
WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int length); // add this in your code
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

Nothing else needs to be changed
Please excuse some terminology mistakes above - it's been a long time since I learned C/C++, while I know how to use it, I don't always know how to describe it :p

apprently there's some bug in the toolchain - see the comments in the question. However, this is still a valid solution, I guess it works around the bug

The difference is "declaration" vs "definition". Readers should take note of the differences, though they appear somewhat similar. Declaration must occur before (nearer to the start of a source file) use.


text:
Did I kill my ESP8266?
So I've been playing with the esp8266 controller lately and today my Usb Host Mini came in that I wanted to connect. So for this I followed the following tutorial https://www.hackster.io/139994/plug-any-usb-device-on-an-esp8266-e0ca8a
The only thing is that I didn't do the following, because I wanted to see that it actually wouldn't work without damaging the Usb Host Mini.

Now I am wondering, because I didn't do that, and just went on with the wiring, did I actually kill my ESP8266 now? Whenever I remove all the wires, and just connect the ESP8266 to my computer, it just won't show up in the ports.
If I did kill it, what did I actually do here? Did I allow 5V to run through the board and did I fry it that way? If I would've actually made the cut shown above, would it have lived? (Because I think what the cut does, is it stops the 5V from going through the circuit.)

Did you connect 5V power source and 3.3V power source to the ESP8266?

@FilipFranik Yes I did indeed

Well if it doesn't work then it doesn't work so a safe bet is that chip is damaged.
I found this document. It states:

VBUS pad and jumber can be used to provide 5V to VBUS. By default VBUS is connected to 3.3V; certain USB devices may have issue with
this.

So I deduce that this is connected directly to 3.3V rail of the chip. Providing 5V without opening the jumper (cutting the trace) is the same as putting 5V at the 3.3V pin.

3.3V. Power pin of the shield. Do not supply 5V to this pin - MAX3421E won't be able to detect devices on VBUS and may also be
damaged!

Apparently the "proper" way of doing things is to actually unsolder that jumper or cut the trace.
Sorry.

Hmm alright that's a bummer, would this also mean that I killed my Usb Host Mini? Or did I just kill the esp8266? I'll find out tomorrow, once I get a new esp8266, but I thought maybe you know. It would suck if I had to buy another Usb Host Mini, since they're quite expensive.

I'm pretty sure that the chip on the mini is fried (if it wasn't then PC would detect an unknown device plugged in) The USB Host Mini  clone is just 4 USD on Aliexpress with free shipping.


text:
Why does Arduino IDE recommend storing 0-255 numbers in "byte" instead of "char"?
I bumped into byte datatype recently. My knowledge of C/C++ is shallow, but I know char and I couldn't find much on byte in C++ docs. I looked it up in the Arduino docs:

It’s recommended to only use char for storing characters. For an
  unsigned, one-byte (8 bit) data type, use the byte data type.

Is byte datatype a solely Arduino construct? If so, why is it recommended over char? Both are 8-bit so why would it make any difference?

char is configured as signed in compiler setting of Arduino Arduino cores

Whenever I make something bigger than just 50 lines, I always use the most specific types like: uint8_t, int8_t, uint16_t, int16_t, uint32_t and int32_t to know exactly what is signed or unsigned and if it is 8, 16 or 32 bits. And I use char for characters, and bool for booleans. In this case you never have to think what fits (or should fit) in a variable.

Is byte datatype a solely Arduino construct?

Yes. Much of the Arduino "language" is "bent" to look like Java, since it originated from Processing, which is Java. So we have data types the "look like" Java ones, including "byte" for "unsigned char" and "boolean" for "bool".

If so, why is it recommended over char?

Personally I don't ever recommend using it, since it's non-standard. Instead you should use uint8_t which is essentially the same thing, but portable.
It is recommended to use "hard signedness" data types for portability.  The problem with char is that whether it is signed or not is entirely down to the compiler implementation. Some systems have it as signed, some as unsigned. By using byte (or better, uint8_t) you are always going to get an unsigned 8-bit value.
For just storing of binary data it doesn't really make any difference, but when it comes to doing mathematics with the stored data you may find you suddenly have negative values when you don't want negative values (a char might be storing your number as -128 to +127, not 0 to 255).

Great explanation. I will stick to specific unit8_t in the future and will go back and refactor my "chars". I prefer to stick to C/C++ syntax than to wander into Java and have another language to be shallow at.

Is byte datatype a solely Arduino construct?

Yes. Much of the Arduino "language" is "bent" to look like Java, ...

While the rest of the answer is of merit; No, byte is a fundamental unit of storage at the hardware level. The word was coined in the 1950s at IBM and defines a collection of bits. You will find byte defined in many programming languages, it is not just an Arduino, or Java, thing. You will, for example, find it in C++ when

working with some hardware interfaces (dis-allowing implicit conversions to other types, which prevents accidental misuse and improves code safety);

using bitwise operations (convenient for low-level manipulations);

or representing raw data memory (std::byte conveys that you are working with raw bytes rather than characters or integers).

Still, the suggestions by Majenko and DataFiddler are valid with Arduino.

Just a little add-on to Majenko's answer:
If a function has a char* parameter, it's usually expecting a zero-terminated text.
If a function has a byte* parameter, it's usually any binary data, eventually containing '\0' bytes. The buffer size needs to be an additional parameter in this case.
If there's nothing else to consider, why not use that for your variable definition too:
Use char only if it contains an 8bit character. Or something like char text[]="hello";
For binary data it might be relevant if it's signed (int8_t) or unsigned (uint8_t).

"usually" implies of course that you should read the doc.


text:
Do i must have capacitors when using L7805CV voltage regulator?
I am creating a small waterpump (5v) controled by arduino.
And i want to reduce voltage from 9v to 5v.
Do i must use capacitors when using L7805CV voltage regulator?

I fear this is not the right place to ask an electronics question. I suggest to ask on  https://electronics.stackexchange.com/ [electronics engineering]. As far as I know the capacitors are necessary to prevent  the 7805  from getting unstable.

@PeterPaulKiefer: I'm new here, but since this question involves details that are peculiar to Arduino (ref this answer), it seems to me that this is the right place.

@Seamus The question does not contain any reference to an Arduino in the title not in the text. There is a picture schematic and a UNO tag. But in the comments to the answer you cited the OP states that he/she uses an ESP32.  The question is about electronics; "should I use capacitors on a L7805CV?". I did not vote to close it, I just advised the OP to ask in a forum where the probability of getting a good answer is higher. But that's obsolete now, as there is a usable answer.

Look at the datasheet:
https://datasheet.octopart.com/L7805CV-STMicroelectronics-datasheet-7264666.pdf
It's not necessary but I advise to use capacitors on the inputs aswell as on the outputs. It will improve stability.
Another thing: the regulator could get quite warm, depending on how much current the motor consumes.
Why don't you use a 5V power supply? You could power the Arduino with it aswell.
At your schematic you are feeding 9V into the Vin pin of the Arduino, this might be a bad idea (I'm not 100% sure), but I think it bypasses the regulator on the Arduino -> it will kill your Arduino.

The Vin pin is connected to the voltage regulator on the Arduino Uno. It is meant to be provided by a higher voltage, so 9V is ok (as long as the OP doesn't draw too much current through the Arduino). But you are right: Using directly a 5V power supply would save you the voltage regulators.

Alright. I  was not sure if the Vin bypasses the onboard regulator or not.

VIN only bypasses the diode that is in series with the barrel jack.

I think @chrisl 's parenthetical note is the key point here. If the power to drive the motor is the 5V supply regulated on the Arduino, then this is most likely a bad idea. The motor should be powered directly from a regulated supply, and not through the Arduino.

@Seamus The motor is not powered through the Arduino but through extra regulator. Thats ok as long as the regulator can provide the needed current. But as both Arduino and motor run on 5V, the OP could simply use directly a 5V power supply.

That would be the easiest solution.

im using esp32 and by this documentation https://docs.zerynth.com/latest/official/board.zerynth.esp32_devkitc/docs/index.html ...it says the Input Voltage is: 7-12V


text:
Can the Arduino Eclipse plugin v2.2 be used with Arduino 1.5.8?
It keeps giving me this warning:

You are using a version of the Arduino IDE that is newer than available at the release of this plugin.`

Does this means I need to use a night build?

V2.2 is pretty old by now.
As far as I recall it should work fine.
V2.2 of the Arduino eclipse plugin should work fine with the Arduino IDE version 1.5.8.
What that phrase wants to say is: the plugin V2.2 was released before Arduino IDE 1.5.8 was released; as such the code can not make a statement on the compatibility.
But again V2.2 is old. We hope to release V3.0 end of February 2016

Doesn't the warning just mean that Eclipse might be old, not the Arduino IDE? Getting a nightly build of the IDE would make things worse, wouldn't it?

Hi Nick.
IMHO The writer is referring to using the nightly of the arduino eclipse plugin (which is currently at V3) and not the "hourly" of the arduino IDE.
Note that the stable release of the arduino plugin is 2.4.

To clarify your answer it should work fine - do you mean the nightly build, or that V2.2 should work fine?

V2.2 of the arduino eclipse plugin should work fine with the arduino IDE version 1.5.8. As the statement says: the plugin V2.2 was released before arduino IDE 1.5.8 was released as such I could not make a statement on the compatibilty. But again V2.2 is old. We hope to release V3.0 this week

@jantje Could you please include more details to your answer, it's fairly short right now.


text:
Arduino can't see any library I have installed for nrf905?
nrf905\
nRF905-All-In-One-Shield\
RadioHead-master\
RadioHead\
None any of them are compiled with their examples without getting errors.
Error message:
nRF905_RX.ino:4:20: fatal error: NRF905.h: No such file or directory
compilation terminated.
Error compiling.

Libraries used:
Elechouse
RadioHead Github
RadioHead Doxygen
zkemble/nRF905

Which Arduino? What version of the IDE? Where did you get those libraries from? (link). What error messages? Try to give a bit more detail.

actally I have the same problem in 1.5.2 and 1.6.5
the links are : https://github.com/elechouse/nRF905
https://github.com/PaulStoffregen/RadioHead
http://www.airspayce.com/mikem/arduino/RadioHead/
https://github.com/zkemble/nRF905
I intend to connect it with arduino uno when the code will be verified  correctly .

the error message is : NRF905.h : No such file or directory compilation terminated

@SalamEtaiwi - where have you put the libraries?

in the libraries folder at arduino  folder  that I use

no error when using examples of this library "RadioHead"  after added it to the library folder , but when trying of another examples there are  errors .

@SalamEtaiwi - I have tried to compile the one from elechouse and that one gives continuous errors, even if the ide is given the exact location, it will throw more errors. If the radiohead one works why not just use it?

@RSM I will try it , I just was confused why not  all  of them work right !
thanks for reply

@SalamEtaiwi - I have just got the zkemble one to compile, which didn't before.

@RSM so is there  error ?

I am writing an answer to explain as  I have all the libraries compiling

about zkemble one after I add the library I  create a new folder called "src" and place the .cpp and .h files into the new folder . as he explain when I emailed him . but still have problem with "nRF905_config.h" it appears now in the error message

I shall explain the problem in the answer as I also tried that and the same result happened

thanks for continuity in this ,,
for correction I used 1.5.8 and 1.6.5 not 1.5.2

@Salam - Let us know if you get it working ;)

The errors you were getting when you compiled was because if the libraries were extracted straight to the Arduino library folder from the .zip, the file path becomes too long for the compiler to find it.
So what you need to do is to create a new folder in the libraries folder for each library.
Note: you cannot do the standard libraryName\src\foo.cpp as this seems to give errors for these libraries (in that it does not find them).
What you need to do is to make a file in the libraries directory; for the zkemble one you can create a main folder called nRF905, then take the files under nRF905/arduino/nRF905 from github and place them in the folder created earlier. It should look like this:

You should repeat this for the Elechouse one as well as it solved the problem too. i.e.

C:\\...\libraries\NRF\examples\
C:\\...\libraries\NRF\NRF905.cpp
C:\\...\libraries\NRF\NRF905.h
C:\\...\libraries\NRF\keywords.txt

Also of importance is that once you have the library from Elechouse compiling you need to open up the .cpp file and go to line 16, where there is
PROGMEM unsigned int freq_tab[10] = {

and to this add const, like so:
PROGMEM const unsigned int freq_tab[10] = {

thanks alot I did what you said ,actually most of the examples give no errors , but there are others give anyway I am now satisfy with this and I tried with a couple of a code (transmitte and recieve ) no errers was in transmite one and the serial monitor showed the right things but the problem was in the recieving side , the Rx led didnt lighting on ’ and not any data in the serial monitor. these are the codes ( transmitte , recieve):

sorry , it cant be sending , but they are the examples from "RadioHead" library ,, nrf905_client ,,, nrf905_server ...

@Salam - first off, glad it worked.  I would recommend posting a new question here. And then I would recommend you open an issue on the RadioHead github page so you can bring it to the attention of the libraries author, he might also be able to give you a accurate answer. I am also on a phone at the moment so can't do much.

I will do that in sha`a Allah .. thanks again ^^


text:
Suggestions for latest ESP8266 WiFi module
I am having problems with the ESP8266-01 I bought. It works at only 115200 baud rate and it gives many problems when programming with Arduino Uno. I got it flashed to 9600 baud rate, but still many times it becomes unreliable.
I have seen many videos online that has the ESP8266 that works at 9600 by default.
Could someone please tell me where I can buy the latest ESP8266 that runs at 9600 baud rate by default?

No, I'm afraid we can't, since we're not ESP8266 salesmen.
However, I would seriously recommend not using an Arduino to communicate with the ESP8266 but instead to program the ESP8266 directly so you don't have any communication worries.  If you want to add an Arduino into the mix at a later date for its enhanced IO capabilities, then feel free to do so - where you can then implement your own serial protocol at whatever baud rate you like (or other protocol even - SPI? I2C?).
All you need is:

The Arduino core for the ESP8266: https://github.com/esp8266/Arduino
Some form of USB serial adapter (eg FT232 breakout board).

The controller chip on the ESP8266 is considerably more powerful than the Arduino's chip, and the fact that many people insist on using the ESP8266 as a slave device to the lower powered Arduino always seems completely backward to me.
If you want an easier board to program that messing with breakout boards you can do a lot worse than investing in a NodeMCU board. Make sure you go for the version 1 not the version 0.9 since the version 1 has a slightly more enhanced chip on it with more IO facilities than the version 0.9.

Thank you @majenko. But I m not that much of an electrical guy. I want to do a project on home automation. I learned to control the relays using arduino. Now I want to control my arduino remotely so that I could control relays with arduino easily. That's why I am using esp8266 with arduino. But I am having lot of problems with baud rate and serialsoftware. Could you please give me a solution for this?

Or could you provide me a link where I could download the latest firmware of esp8266 and flash it to use at 9600 baud rate easily

I have. Ditch the Arduino and get a NodeMCU. With the Arduino core installed it's exactly like working with the Arduino. Same language. Just a lot easier to work with for WiFi.

My mom will burn me. I bought lot of electronic equipments online. Or could you give me link of the latest firmware bin file for esp8266. Please. @majenko

I don't know a link for that kind of thing. This is an Arduino site not an ESP8266 site. Maybe you should ask for that link on an ESP8266 site, or ask google for it.

Thank you for your comments. @majenko. I will try my best.

The ESP8266 has 3 SPI slave selects, but note that one of them is used for the off-board flash that contains the firmware, and not all modules make SPI available externally. UART is the way to go, since it is available on most if not all modules.

@IgnacioVazquez-Abrams I use my ICSC library on the ESP modules for serial communication. Works well and is very easy to use.

@Majenko I think often Arduino is used as master because it has lower power consumption in the lowest sleep modes: it can send ESP8266 into the power down most of the time, and therefore save battery. For example https://openhomeautomation.net/esp8266-battery/ If you have only ESP8266, can you wake it up from deepsleep from the uploaded firmware?

Here's the other bit of it that most people don't understand on their first try.
Everything that plugs into an arduino is not a slave device.
In this case both this module and the hc-05 and hc-06 are standalone and actually HAVE THEIR OWN SOFTWARE on them. These chips are fully functional without arduino and you can send commands to them directly or by using the arduino as a dummy chip.
So at the end of the day to get your project working you should interface with the device directly instead of passing it through arduino.
Your device most likely isn't busted so don't worry about constantly flashing between versions. You probably just need to configure it using AT+ commands.
Here is a pdf of AT+ commands
Download pdf
This is a quickstart guide that includes pictures and order of commands. Don't fry your boards.
Download pdf
After that's done serialCommand amd software serial are pretty easy to use. Look at the serialCommand examples to see how it's done.
SoftwareSerial example using serialCommand

The problem is that you need another device to send the AT commands, and they need to be sent each time the device is powered on. This is why reprogramming the device to work completely standalone is a better solution.

Why do they need to be sent every time? Shouldn't it be able to function on it's own from stock? the whole point behind AT commands is that you can initialize it so it can function as needed, and not need to set things such as the baud rate and the name every time it's reset.

If I'm wrong that's fine, I just don't understand why you would need to do that every time. I have worked on other AT devices like bluetooth and it seems to hold up just fine after initialization.

Those devices have a firmware which is programmed to store settings on the module itself. The AT firmware for the ESP8266 for the most part is not.

Looks like I'm going to toy with it this week. I'll get back to you


text:
Arduino U8glib: how to display text?
I have a Nokia 5110 screen using u8gliv. I have it displaying an image and I can get it to display text:
   u8g.setFont(u8g_font_osb18);
   u8g.drawStr(0, 20, "PRESS START");

The problem is that this font size is way too big. How can I make it smaller? Do I have to use different fonts? If so how do I do that?

Can somebody explain me how to download a font and upload then to m

Just choose a smaller font. You know, I showed you the documentation earlier. You really should read it, because it contains all the information you need.
For instance, here is the section on the available fonts: https://code.google.com/p/u8glib/wiki/fontgroup - each section contains a link to download the font group which of course you will need to do before you can use it.
You might find something like:
u8g.setFont(u8g_font_fixed_v0);

more to your liking. And don't forget to download it via the link above first.

sorry, I did read it but I couldent find much on font size

It took me 5 seconds - click the setFont link, then the see here for an overview link, then select a group and see what looks nice. They are real size.


text:
Arduino in-built LED is not turning off
I have an Arduino Uno whose LED, which is connected to  pin 13, is not turning off and it always stays on, and it annoys me.

Touching any exposed pins turns off the LED after removing my hands from the pins it turns back on slowly.
However it works perfectly with the programs. This program does turn the LED off and it stays that way while the program is running.
void loop() {
  digitalWrite(13, LOW);
}

When I upload other programs that don't use pin 13 then it stays on again. How can I fix this?

When i want to use pin 13 only then i set it as output else its not even defined any where in the code

See: Uno pin 13 LED mysteriously always ON at 0.14V unless pinMode OUTPUT

If you don't tell it to turn off, it behaves "as it wants". If you don't write a 0 on its pin, how can you force it to stay shut down?
If you want it to be in an off state, force it: in your setup function write
pinMode(13, OUTPUT);
digitalWrite(13, LOW);

No need to refresh it every loop, just in the setup.

Yeah i know. that was the example i am giving to tell it behaves that way when the pin is not defined/set. Means i have not set pinMode(13,OUTUPT/INPUT); and still it stays on.. but when i do define it with pinmode than it works the way it supposed to work

Yes, that's because if you want the board to do (or not to do) something you have to explicitely say it. Otherwise you will have a behavior that can change between runs

i have another arduio uno who doesn't behave like this one.. its led stays off.

Again, " you have to explicitely say it. Otherwise you will have a behavior that can change between runs". If you don't tell it to pull it down, it will be in a floating state. Floating means that no one knows what state it will have. So pull it down. Or solder a resistor (any value above 10k are fine) between the 13 pad and ground. Or place a resistor of the same value in the header between pin 13 and ground. But you have to set a value

You could try to actually remove the LED with a soldering pen... I haven't tried it however, so you could end up disabling pin 13 (or worst).

That's my last option..

As I referred to in my comment on the question ( http://arduino.stackexchange.com/questions/17675/uno-pin-13-led-mysteriously-always-on-at-0-14v-unless-pinmode-output ) this behaviour is normal because of the op-amp they use to drive the LED. The output state is undefined if the pin is configured as an input, and the op-amp may or may not turn on the LED. To be sure, configure the pin as an output. Soldering a resistor or removing the LED seems an overkill. Define the pin as an output if it is not used for anything else, and write LOW to it.

@AkashKumar you could just put a small square of electrical tape over it, which is also temporary. Don't overthink it!


text:
Updated Arduino IDE and Arduino not working
I've had the 1.0.5 IDE on my PC, which worked great. Now I've just decided to update to 1.6.6. After some stupid Java errors and trial and error, I got it to work.
I recompiled my project. Massive errors. Fixed the errors and compiled again.
It stated "Uploading..." That took much longer than before, but I saw the "This takes xxx memory and xxx bytes on the device" yadi yadi ya.
I decided to unplug the Arduino, swap some jumpers and reconnect it (as I've always done). Only this time - I hear 3 beeps from my PC (the sound you hear with broken USB devices). The COM port is no longer recognized.
How do  I fix this? Did that IDE upgrade just brick my Arduino?

Lol, thanks. I might be on to something here though, hang on...

Allright, seems to be fixed. After a 3rd reinstall it seems like its fixed. I reinstalled the whole package, including the drivers, and now it seems to recognize the device again.
Also the compiling now stops properly when done and shows "upload complete".

Please accept your answer so that the question shows as resolved.  In the past we'd probably have just closed the question as "too localized" however that no longer seems to be an option, with the result that the question gets pointlessly churned up now and then.

Hey, sorry yeah I forgot about doing it. Its not possible to accept as a solution immediately, I had to wait a day or 2, but didn't put it in my calendar :) Thanks for the heads up.


text:
Errors reading fixed-length control strings over serial
I am sending a short 12-char control string over serial with Python and Debian Jessie.
It works, but sometimes chars are added or skipped randomly. Here it is an extract of the Arduino code:
void setup() {
  matrix.begin();
  matrix.setTextWrap(true);
  matrix.setFont(&TomThumb);
  matrix.fillScreen(matrix.Color333(0, 1, 1));
  matrix.swapBuffers(false);
  Serial.begin(115200);
}

void loop() {
  char c = 0; // serial char buffer
  byte i = 0; // string counter (reused multiple times)
  // read the equalizer control string
  delay(1);
  if (Serial.available() > 0) {
    turnmatrixoff();
    String control_str = Serial.readStringUntil('\n');
    Serial.println((control_str));
    draw_equalizer(control_str.c_str());
  }

Here is the log of the strings echoed back from the Arduino:
10563942332
00863931110
00773940100
0000974940100
00763940100
10693931211
00593950100
00544840100
00464950100
1050000
004549310744940100
00664961211
00694941111
10784951100
0
00593931100
00373931100
00483920100
00583720110
10473510000
000332710000
00252710000
00142510000
00122620000
002510000
003310100
00334520110
00343520100
00244720100
00355820110
00343611110
10144621210
00424921210
10343921210
00233811310

As you can see, some strings are truncated or padded (they all should be of the same size).
I've tried coding a char-by-char read function but the results were even worse:
char c = 0; // serial char buffer
byte i = 0;

while (Serial.available() > 0) {
  delay(1);  //small delay to allow input buffer to fill
  c = Serial.read();
  if (c == '\n' || i >= EQUALIZER_STR_SIZE - 1) {
    // finished reading the string
    equalizer_str[i] = 0; // terminate the string
    Serial.println(equalizer_str); // debug echo
    draw_equalizer(equalizer_str);
    break;
  } else {
    // append to the string
    equalizer_str[i] = c;
    i += 1;
  }
}

EDIT: here it is the full python script.
Decreasing the baud rate to 9600 seems to fix the issue, but the matrix updates too slowly this way.
Maybe I could use some other serial port initialization trick to prevent buffer overflows?
UPDATE:
I've found another way to reduce the serial traffic by increasing the audio capture chunk. For some reason this way the errors are gone completely.
Here it is a video of the code finally running fine.

Change delay(1);  //small delay to allow input buffer to fill to delay(1); //small delay to allow input buffer to overflow. There is never any excuse for using a delay while reading serial.

do you mean i should remove the delay?

Absolutely. You might like to read this too: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

just tried removing the delay, i still get the truncated strings...

Also you should be aware that there is no handshaking on Arduino serial. If you don't read the data faster than you send it you will overflow. If you need to, slow down your sending with a delay in the python code.

in the python code i have a sleep(0.001). I've tried increasing the delay but it does not fix the problem (it also makes the matrix refreshing too slowly).

removing even the delay before if (Serial.available() almost fixed the issue!

A baudrate of 9600 delays the Python script, so the Arduino can keep up with the incoming data. The Arduino Leonardo/Micro or Arduino Due and M0 can use a CDC SerialUSB port to computer. That is faster than 115200 baud. You probably need a M0+ or M3 processor anyway because it seems that your Arduino is too slow. Are the turnmatrixoff() and draw_equalizer() functions optimized ? The Serial.readStringUntil() uses a default timeout of 1 second. This situation is in my opinion not suitable for a timeout. You need to calculate how much data is transferred and test if the Arduino can handle that.

@Jot: thank you for the tips, i've done some testing and i've found the draw_equalizer() is indeeed too slow. Here it is the full arduino source code. If it can't optimized more i guess i have to try another gfx library or switch to another controller as you suggested.

Check that the serial receive code works first. Estimate the maximum baudrate, e.g. how much time does the rest of the code take. What would happen if the serial buffer is not emptied in time and overruns?


text:
Arduino Nano/Uno and js sketch compiling/uploading from browser
I need to compile generated source code in js runtime then upload it to my device.
Compiling:
I have found arduino-cli
Uploading:
There is only avrgirl but it doesn't work in browser. What should I do?

Arduinos cannot be programmend in Nodejs. You need to write C/C++ or Assembler.

@chrisl, it's not about programming (code is c-generated one) it's about calling compiler from js

Ah, ok. But you can also upload sketches with arduino-cli. If you can use it, you can also upload sketches

You can't, and that's a good thing. If the browser could let a Web site access your hardware, that would be a huge security breach. You may be able to bypass this security restriction if you can write an extension (plugin) for your browser.

Okay then I will use extension for hex code uploading. Then how can I compile it using only in-browser js?

I mean: source code -> String -> Compiler -> Hex-string -> Extension -> Uploading

@caxapexac: Building a C++ compiler in JavaScript is not a trivial task. You may try to port avr-g++ using Emscripten.

Seems for me a weird way to do everything in the browser. Normally in such a situation you are actually building a web service, so the compilation could be done server side by calling avr-g++ or arduino-cli through the nodejs code. Then you only would need to encapsule arduino-cli in an extention for uploading on the local computer

I modify the code from js-stk500 to work from browser with web serial API. but I can't makr Arduino CLI to work in browser. Is that possible?


text:
Arduino ultrasonic sensor weird output
So I just got into arduino and bought Elegoo's car robot v3 kit and built it, but when I put the robot on "object avoidance" it constantly spins as though there is an object in front of it. I tried changing the code and had no luck so I thought maybe it was the sensor itself, when I hooked it up and ran:
void loop() {
   a=sr04.Distance();
   Serial.print(a);
   Serial.println("cm");
   delay(1000);
}

it displayed the correct distances so I figured it could not be the sensor. The curious thing happened when I added a few lines to the car's code to also make it print the distance it was seeing, and when the sensor is hooked up to the car for whatever reason all it sees is 18cm no matter the actual distance, which explains why it is constantly spinning. I have found the problem, but now my issue is that for the life of me I cannot figure out why it detects only 18cm constantly when hooked to the car.
#include <SR04.h>

/*
 * @Description: Rocker_Control
 * @Author: HOU Changhua
 * @Date: 2019-08-12 18:00:25
 * @LastEditTime: 2019-08-27 10:45:29
 * @LastEditors: Please set LastEditors
 */
#include <Servo.h>
#include <stdio.h>
#include "HardwareSerial.h"
#include "ArduinoJson-v6.11.1.h" //ArduinoJson

/*Driving Interface for Ultrasound Ranging*/
#define ECHO_PIN A4
#define TRIG_PIN A5

/*Motor Drive Interface*/
#define ENA 5
#define ENB 6
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11

/*Driving Interface for Infrared Pipeline Patrol*/
#define LineTeacking_Pin_Right 10
#define LineTeacking_Pin_Middle 4
#define LineTeacking_Pin_Left 2
#define LineTeacking_Read_Right !digitalRead(10)
#define LineTeacking_Read_Middle !digitalRead(4)
#define LineTeacking_Read_Left !digitalRead(2)

#define carSpeed 180 //PWM(That is: motor speed/vehicle speed)

Servo servo;
unsigned long IR_PreMillis;
unsigned long LT_PreMillis;

enum FUNCTIONMODE
{
  IDLE,
  LineTeacking,
  ObstaclesAvoidance,
  Bluetooth,

} func_mode = IDLE; /*Functional model*/

enum MOTIONMODE
{
  STOP,
  FORWARD,
  BACK,
  LEFT,
  RIGHT
} mov_mode = STOP; /*Motion model*/

void delays(unsigned long t)
{

  for (unsigned long i = 0; i < t; i++)
  {
    getBTData_Plus();
    delay(1);
  }
}

/*Acquisition Distance: Ultrasound*/
unsigned int getDistance(void)
{
  static unsigned int tempda = 0;
  unsigned int tempda_x = 0;
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  tempda_x = ((unsigned int)pulseIn(ECHO_PIN, HIGH) / 58);
  if (tempda_x < 150)
  {
    tempda = tempda_x;
  }
  else
  {
    tempda = 30;
  }
  return tempda;
}
/*Control motor: */
void forward(bool debug, int16_t in_carSpeed)
{

  analogWrite(ENA, in_carSpeed);
  analogWrite(ENB, in_carSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  if (debug)
    Serial.println("Go forward!");
}

/*Control motor: */
void back(bool debug, int16_t in_carSpeed)
{

  analogWrite(ENA, in_carSpeed);
  analogWrite(ENB, in_carSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  if (debug)
    Serial.println("Go back!");
}
/*Control motor:*/
void left(bool debug, int16_t in_carSpeed)
{
  analogWrite(ENA, 250);
  analogWrite(ENB, 250);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);

  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  if (debug)
    Serial.println("Go left!");
}
/*Control motor:*/
void right(bool debug, int16_t in_carSpeed)
{
  analogWrite(ENA, 250);
  analogWrite(ENB, 250);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  if (debug)
    Serial.println("Go right!");
}
/*Control motor:*/
void stop(bool debug = false)
{
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
  if (debug)
    Serial.println("Stop!");
}
/*
  Bluetooth serial port data acquisition and control command parsing
*/
void getBTData_Plus(void)
{
  String comdata = "";

  while ((Serial.available() > 0) && (false == comdata.endsWith("}")))
  {
    comdata += char(Serial.read());
    delay(3);
  }
  if ((comdata.length() > 0) && (comdata != "") && (true == comdata.endsWith("}")))
  {
    StaticJsonDocument<200> doc;                                //Create a JsonDocument object
    DeserializationError error = deserializeJson(doc, comdata); //Deserialize JSON data
    if (!error)                                                 //Check if deserialization is successful
    {
      int control_mode_N = doc["N"];
      char buf[3];
      uint8_t temp = doc["H"];
      sprintf(buf, "%d", temp);
      String CommandSerialNumber = buf; //Get the serial number of the new command

      switch (control_mode_N)
      {
      case 5: /*Clear mode  processing <command：N 5>*/
        func_mode = Bluetooth;
        mov_mode = STOP;
        Serial.print('{' + CommandSerialNumber + "_ok}");
        break;
      case 3:               /*Remote switching mode  processing <command：N 3>*/
        if (1 == doc["D1"]) // Line Teacking Mode
        {
          func_mode = LineTeacking;
          Serial.print('{' + CommandSerialNumber + "_ok}");
        }
        else if (2 == doc["D1"]) //Obstacles Avoidance Mode
        {
          func_mode = ObstaclesAvoidance;
          Serial.print('{' + CommandSerialNumber + "_ok}");
        }
        break;
      case 2: /*Remote switching mode  processing <command：N 2>*/

        if (1 == doc["D1"])
        {
          func_mode = Bluetooth;
          mov_mode = LEFT;
          Serial.print('{' + CommandSerialNumber + "_ok}");
        }
        else if (2 == doc["D1"])
        {
          func_mode = Bluetooth;
          mov_mode = RIGHT;
          Serial.print('{' + CommandSerialNumber + "_ok}");
        }
        else if (3 == doc["D1"])
        {
          func_mode = Bluetooth;
          mov_mode = FORWARD;
          Serial.print('{' + CommandSerialNumber + "_ok}");
        }
        else if (4 == doc["D1"])
        {
          func_mode = Bluetooth;
          mov_mode = BACK;
          Serial.print('{' + CommandSerialNumber + "_ok}");
        }
        else if (5 == doc["D1"])
        {
          func_mode = Bluetooth;
          mov_mode = STOP;
          Serial.print('{' + CommandSerialNumber + "_ok}");
        }
        break;
      default:
        break;
      }
    }
  }
}

/*Bluetooth remote control mode*/
void bluetooth_mode()
{
  if (func_mode == Bluetooth)
  {
    switch (mov_mode)
    {
    case FORWARD:
      forward(false, carSpeed);
      break;
    case BACK:
      back(false, carSpeed);
      break;
    case LEFT:
      left(false, carSpeed);
      break;
    case RIGHT:
      right(false, carSpeed);
      break;
    case STOP:
      stop();
      break;
    default:
      break;
    }
  }
}
/*
  Line Teacking Mode
*/
void line_teacking_mode(void)
{
  if (func_mode == LineTeacking)
  {
    if (LineTeacking_Read_Middle)
    {                           //Detecting in the middle infrared tube
      forward(false, carSpeed); //Control motor：the car moving forward
      LT_PreMillis = millis();
    }
    else if (LineTeacking_Read_Right)
    {                         //Detecting in the right infrared tube
      right(false, carSpeed); //Control motor：the car moving right
      while (LineTeacking_Read_Right)
      {
        getBTData_Plus(); //Bluetooth data acquisition
      }
      LT_PreMillis = millis();
    }
    else if (LineTeacking_Read_Left)
    {                        //Detecting in the left infrared tube
      left(false, carSpeed); //Control motor：the car moving left
      while (LineTeacking_Read_Left)
      {
        getBTData_Plus(); //Bluetooth data acquisition
      }
      LT_PreMillis = millis();
    }
    else
    {
      if (millis() - LT_PreMillis > 150)
      {
        stop(); //Stop motor control：Turn off motor drive mode
      }
    }
  }
}
/*f(x) int */
static boolean function_xxx(long xd, long sd, long ed) //f(x)
{
  if (sd <= xd && xd <= ed)
    return true;
  else
    return false;
}
/*Obstacle avoidance*/
void obstacles_avoidance_mode(void)
{
  static uint16_t ULTRASONIC_Get = 0;
  static unsigned long ULTRASONIC_time = 0;
  static boolean stateCar = false;
  static boolean CarED = false;
  static uint8_t switc_ctrl = 0x00;
  static boolean timestamp = true;
   Serial.print(A4);
   Serial.println("cm");
   delay(1000);

  if (func_mode == ObstaclesAvoidance)
  {
    servo.attach(3);
    if (millis() - ULTRASONIC_time > 100)
    {
      ULTRASONIC_Get = getDistance(); //Measuring obstacle distance
      ULTRASONIC_time = millis();
      if (function_xxx(ULTRASONIC_Get, 0, 30)) //If the distance is less than Xcm obstacles
      {
        stateCar = true;
        stop(); //stop
      }
      else
      {
        stateCar = false;
      }
    }
    if (false == CarED)
    {
      if (stateCar == true)
      {
        timestamp = true;
        CarED = true;
        switc_ctrl = 0x00;
        stop();          //stop
        servo.write(30); //sets the servo position according to the  value
        delays(500);
        if (function_xxx(getDistance(), 0, 25)) //How many cm in the front have obstacles?
        {
          switc_ctrl |= 0x01;
          //goto
        }
        else
        {
          switc_ctrl &= (~0x01);
        }
        servo.write(150); //sets the servo position according to the  value
        delays(500);
        if (function_xxx(getDistance(), 0, 25)) //How many cm in the front have obstacles?
        {
          switc_ctrl |= 0x02;
          //goto
        }
        else
        {
          switc_ctrl &= (~0x02);
        }
        servo.write(90); //tell servo to go to position in variable 30
        delays(500);
        if (function_xxx(getDistance(), 0, 25)) //How many cm in the front have obstacles?
        {
          switc_ctrl |= 0x04;
          //goto
        }
        else
        {
          switc_ctrl &= (~0x04);
        }
      }
      else
      {
        forward(false, 180); //Control motor：the car moving forwar
        CarED = false;
      }
    }

    if (true == CarED)
    {
      // Get cpu time
      static unsigned long MotorRL_time;
      if (timestamp == true || millis() - MotorRL_time > 420)
      {
        timestamp = false;
        MotorRL_time = millis();
      }
      if (function_xxx((millis() - MotorRL_time), 0, 400))
      {
        switch (switc_ctrl)
        {
        case 0 ... 1:
          left(false, 150); //Control motor：The car moves forward and left
          break;
        case 2:
          right(false, 150); //Control motor：The car moves forward and right
          break;
        case 3:
          forward(false, 150); //Control motor：the car moving forwar
          break;
        case 4 ... 5:
          left(false, 150); //Control motor：The car moves forward and left
          break;
        case 6:
          right(false, 100); //Control motor：The car moves forward and right
          break;
        case 7:
          back(false, 150); //Control motor：Car backwards
          break;
        }
      }
      else
      {
        CarED = false;
      }
    }
  }
  else
  {
    servo.detach();
    ULTRASONIC_Get = 0;
    ULTRASONIC_time = 0;
  }
}
void setup(void)
{
  Serial.begin(9600);         //initialization
  servo.attach(3, 500, 2400); //500: 0 degree  2400: 180 degree
  servo.write(90);            //sets the servo position according to the 90（middle）

  pinMode(ECHO_PIN, INPUT); //Ultrasonic module initialization
  pinMode(TRIG_PIN, OUTPUT);

  pinMode(IN1, OUTPUT); //Motor-driven port configuration
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);

  pinMode(LineTeacking_Pin_Right, INPUT); //Infrared tracking module port configuration
  pinMode(LineTeacking_Pin_Middle, INPUT);
  pinMode(LineTeacking_Pin_Left, INPUT);
}

void loop(void)
{
  getBTData_Plus();           //Bluetooth data acquisition
  bluetooth_mode();           //Bluetooth remote mode
  line_teacking_mode();       //Line Teacking Mode
  obstacles_avoidance_mode(); //Obstacles Avoidance Mode
}

New Debug:
/*Acquisition Distance: Ultrasound*/
unsigned int getDistance(void)
{
  static unsigned int tempda = 0;
  unsigned int tempda_x = 0;
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  tempda_x = ((unsigned int)pulseIn(ECHO_PIN, HIGH) / 58);
  if (tempda_x < 150)
  {
    tempda = tempda_x;
  }
  else
  {
    tempda = 30;
  }
  Serial.print(tempda);
  Serial.println("cm");
  delay(1000);
  return tempda;
}

You already figured out, that is is not a hardware problem, but a software problem. But you didn't show us your code. We cannot magically see it. Please edit your question to include the actual problematic code (a complete working example please).

I am trying to post the code, but when I copy paste it, the format gets ruined and I am having trouble getting it to stay in a block.

Past the code in.  Then highlight the code and click on the stackexchange.com icon for code.   (Oh, I see you have been able to embed code into your question, good.)  BTW, guessing, you are probably having a power supply / battery problem.  What are you using?  And if more than one type of power source, then when are you using them?

The power source is a 7.4V Lithium Battery 4000mAh.

I also finally managed to get the code formatted, thank you!

upvote for caring about the program listing readability without being asked

Welcome to the wonderful world of Arduino programming and robotics!
As you have discovered, sometimes the magic doesn't work with the first incantation, so some work is required to get the spell just right ;-).
When troubleshooting a problem with a sophisticated system like the Elegoo kit you have, it helps to drastically simplify things to start with to establish a working baseline, then add complexity incrementally until the problem behavior occurs. Then you can concentrate on the (hopefully) smaller piece of code that caused the problem, without having to wade through lines and lines of irrelevant programming.
It appears that you have started in the right direction with your simple program to display the distance once per second, so you have the right idea.  If you haven't done so already, I suggest you create a completely new Arduino sketch, with just your once/second measurement as the entire program (plus the #include  necessary to access the sensor).  Once you have it running in isolation, then add just the 'obstacles_avoidance_mode(void)' function along with some print statements to instrument the different decision trees of the function.  For instance, I might simplify the function down to something like this:
void obstacles_avoidance_mode(void)
{
  static uint16_t ULTRASONIC_Get = 0;
  static unsigned long ULTRASONIC_time = 0;
  ULTRASONIC_Get = getDistance(); //Measuring obstacle distance
  ULTRASONIC_time = millis();
  Serial.print("time = ");Serial.print(ULTRASONIC_time);
  Serial.print(", dist = ");Serial.println(ULTRASONIC_Get);
 }

Then add the required 'getDistance() function to the bottom of your new test program and call 'obstacles_avoidance_mode(void)' once per second.  Once you have that working to your satisfaction, then start adding small pieces of 'obstacles_avoidance_mode(void)' one at a time, along with whatever preconditions are required to force each small section to execute as you cause the sensor's reported distance to change by moving your hand toward and away from the sensor. Don't worry about the motors and/or servos all; you can hook them up later as needed.
By doing this you should very rapidly come to understand how the program is making decisions, without getting bogged down in all the other stuff going on in the full robot code.
Hope this helps,
Frank

I'm using ultrasonic sensor to get the water level in a watertank for my irrigation system. The following piece of code for measuring the distance works fine for me. I'd suggest to replace:
tempda_x = ((unsigned int)pulseIn(ECHO_PIN, HIGH) / 58);

(BTW what is 58?)
 with the following:
long duration;
duration = pulseIn(ECHO_PIN, HIGH);
tempda_x = duration*0.034029/2;

0.034029 is the speed of sound per second(m/s). And this times the duration it takes sound to get back, divided by 2 gives us the distance from the object.
Hope it helps.

Not too sure as to what 58 is as this is mainly code from the Elegoo robot car v3. However when I replace that line with yours it tells me "duration was not declared in this scope"

Oops, my mistake. I forgot to mention to declare duration at the top of your script as
long duration;
or just in getDistance function ...

Serial.print(A4) makes no sense, that just directly reads the GPIO pin (0 or 1). Maybe that statement is actually messing up the configuration of the GPIO and messing up the distance measurement.
You need to use the getDistance() function. For debugging, try printing the tempda return value just before the return statement. You still might need to convert that echo timing to cm distance though.

I removed the Serial.print string and added the debugging code, but as I am very new to this I believe I messed something up as it no longer shows me the distance in the serial monitor.

I placed the new debug up above as I can't get it to format well in comment form.