text:
Wemos D1 / Witty Cloud D8 doesn't behave as expected
When using D8 in the code doesn't work, nothing happens, but replacing D8 with 15 works like a charm. And to test this I created the code below. I know that D8 has worked earlier, but I don't remember which version I was using at that time, but it was a yer or more ago.
Environment:

Arduino IDE ver. 1.8.13
ESP8266 board ver. 2.7.4
Witty Cloud or my add on version to WeMos D1 (https://oshpark.com/shared_projects/r3NRvNjx)
WeMos D1 R1 chosen in Board manager

// "Witty Cloud" test program

// A0 - LDR resistor
// D2 - Button
// D6 - Green LED
// D7 - Blue LED
// D8 - Red LED

// Constants won't change. They're used here to set pin numbers:
const int LDR = A0;
const int BUTTON = D4;
const int GREEN = D6;
const int BLUE = D7;
const int RED = D8;

void setup()
{
  Serial.begin(115200);
  pinMode(LDR, INPUT);
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  pinMode(BUTTON, INPUT);
}

void loop()
{

  delay(1000);

  Serial.println("");

  Serial.print("LDR: ");
  Serial.println(analogRead(LDR));

  digitalWrite(RED, HIGH);
  digitalWrite(BLUE, LOW);
  Serial.println("--- Red ---");

  delay(1000);
  digitalWrite(RED, LOW);
  digitalWrite(GREEN, HIGH);
  Serial.println("--- Green ---");

  delay(1000);
  digitalWrite(GREEN, LOW);
  digitalWrite(BLUE, HIGH);
  Serial.println("--- Blue ---");
}

Have you looked at the core of your board? In wiring.c (i think) these makros should be defined. Are they defined with the pin number or the bit number in the port?

I actually found the error, check, https://github.com/esp8266/Arduino/blob/master/variants/d1/pins_arduino.h and found the row static const uint8_t D8   = 0; bummer

D1 R1 has different pin mapping then R2 and mini

Now I see my mistake, I chosed a "WeMos R1" and not "LOLIN(WEMOS) D1 Mini".... why has WeMos changed to LOLIN ?


text:
Brushless motor vibration/jitter/noise - arduino uno
I am currently using these motors and driving them off these drivers and an arduino uno, and alternatively trying to make them turn using the setup in step 6 (both with l298n and without) in this instructable. I have 4 motors and all are exhibiting the same behaviour.
Using the drivers, I just sent a constant PWM via PWM pin, and the motor would only spin at high values around 255, but even then only when I touch the motor does it start spinning. This spinning is then not even smooth, it pauses a bit every second or so and results in a sort of jittering. After a bit more, plugging the motors in it now just makes an increasingly louder whining noise, kind of like it's getting ready to take off but doesnt really spin. Code used here is just basic as below:
void setup () {

pinMode(9, OUTPUT);

}

void loop (){

analogWrite(9, 255);

}

Using the instructable setups, I've wired exactly the same way (wiring for l298N version is in step 10, wiring for discrete steps is just directly pwms to the motor), but the motors will not spin like theirs do (same poles and slots, 12n14p). Mine just jitters back and forth in tiny steps and looks like it's just twitching. Code used is exactly as at the end of 'step 6'.
Imgur album of issues

sounds like the power supply is running out of juice

put the analogWrite into setup() ... remove it from loop()

source: Stack Exchange

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

sort: votes


text:
MKR ZERO is not detected in IDE / MKR ZERO not showing up in windows 8.1/
I m connect it with my IDE software and its work perfectly yesterday, but today morning I'm connected it to software to upload another sketch but its didn't detect the port and the charge led is not on yesterday but today is on. I tried every resolution which is given on website but its didn't work. please help me through this I'm new to this board.

Does this answer your question? Why is the IDE not able to find the board despite it being clearly seen and selected?

A few possibilities come to mind:

Your USB cable is bad.  Try a known good one.
Your USB port has failed.  Try a different port or try plugging something else into this one to verify that it's still OK.
Your MKR ZERO has become damaged somehow.

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


text:
Error in uploading sketch to digispark attiny85 board
I'm trying to use Digispark attiny85 board and running into issues uploading the sketch.
The drivers are correctly installed. I have followed this page as a reference.
Below the sketch and the error message.

Thanks for any help

"LAB C Student 8" is part of your installation and work path. It contains spaces. I can not see the flasher call (launcher) complete but it seems as the path is not quoted in "..." so the complete path is separated in many arguments and thus the flasher can not find the hex file to upload. It's just a guess. But the tool calls in the output above do not fail and the paths are escaped therein.

please remove the picture of text and replace it with the actual text ... some of us are unable to view images ... it is also easier to test your code

You cant have spaces in your name. I made a second account named 'test' to run the code


text:
Arduino Esp8266 Signal(TIMER0_COMPA_vect) can’t compile
Trying to compile a program containing the statement SIGNAL(TIMER0_COMPA_vect) written for arduino. But I want to use it on an esp8266 board. The code will compile  for Arduino uno. But I get an error “expected constructor, destructor, or type conversion before ‘(‘ token when I try to compile for a Wemos D1 board. Can anyone help me convert the statement to pass the compile test. Thank you

That instruction is for setting up an interrupt handler for the timer. It is very much specific to the AVR.
There's a lot more to do that just adjust that one statememt - you have to completely rewrite the whole of the timer code that you're using to operate with the ESP8266 SDK calls.
Without knowing what your code intends to achieve it's impossible to help you further, but this library may be of help to you.


text:
What motor to move a small telescope?
i just bought a hobby telescope, it works well for being nothing much than a toy, the very problem is that the gesrs that should keep it stable are all plastic and very hard to tighten while keeping it steady.
So I thought to let the gears wide open and move it with arduino: you point the object manually then with 4 buttons move it by small steps.
I've tried to use a couple of servos i had at home, mg90s 2kg 180°; while 180° is enough for the purpose, first i don't think 2kg is enough for the X axis motor, second one is not very precise (using the default library).
I know I can achieve better results calibrating the pulse manually, but maybe is better if I use better motors.
What motors (and why) would you reccomand?
Servo or stepper?
Being for a hobby the budget is low, so very max 50$?

It's really not an easy task to build a stable mount control on an unstable platform. There are good reasons why reasonable quality telescope mounts are in the $500+ price range. Will you be using it for astonomical objects (i.e. tracking)?

I wouldn't use a servo for this. You don't have very fine control over the angle with a servo. Also with a typical telescope the focus is more on rather slow and precise movements, instead of fast ones.
Instead I would use a stepper motor. Depending on your exact requirements, these can be rather cheap to rather expensive.
Here also the mechanics come into play. The motor should not be attached directly to the axis, but instead through some gears (the axis of the telescope having the larger gear). That will allow for smaller, more precise movements and also lower the needed torque for the motor. Of course this depends on your actual telescope hardware, meaning if you can put a gear right to the axis. If not, you could limit the motor driven movement a bit and install a level, which then could be pushed or pulled by a nut on a threaded rod, which gets driven by the servo motor. This would be rather easy to implement, though you may need to correct for the different rotation behavior, when you get to the outer sides of the movement (for the actuator being linear, while the resulting movement is circular), by some mathematics in your code.
Since you want to keep your costs very low, you might wanna use the 28BYJ-48 stepper motor (including the fitting driver). In terms of stepper motors they are rather bad, but they are really really cheap and - depending on the gear ratio/level length/thread pitch - it might not matter that much for you. You could always update to a better stepper motor in the future.

I agree with using a stepper motor. Some commercial telescope mounts use a normal gear motor with feedback from an opical encoder.

Thank for your reply. The main idea is to build something with a rotating plate (this way can be paired with some lights and become a quick tool to take pictures of small items, for example), and since here no problem i could use the cheapest motor with a gear and a belt, easy to do and to keep stable. For the up/down movement, considering that has to lift the weight of the telescope, I'll try your suggestion. I need to make some prototypes with the structure becouse would be nice to have a full 160° rotation.

For the vertical motion a stepper motor would also be better than a servo. It ca give you more torque. Also: When you are using a gear or threaded rod with nut on it, the actual force is also multiplied. The mentioned stepper motors have a bit of slack, but I used them for a self build laser engraver and had OK results. Make sure, that you provide enough power to the motors, or you will have less torque


text:
Error downloading package_esp32
I've been trying to install esp32 on Arduino IDE for days now but I keep getting 'error downloading package' message. I checked the over and over again, it's correct. I even tried installing it manually using GitGUI but it's not working. Please help me.

what's correct?

The link. I was wondering maybe I was making a mistake but I checked, there's no mistake

Describe exactly what steps you followed and any error messages you get. Otherwise we'll just have to guess. You may write "it's correct" but the fact that you can't get it to work tells me otherwise. Did you follow these instructions ?

The content of the boards manager json file the ESP32 Arduino package downloads and is well formed JSON.  There appear to be 14 distinct .zip and .tar.gz files for the core and tools files for the various platforms supported by the 1.0.4 release.  All of them download for me.  You should update your question in all the ways mentioned in comments above.

*Started the IDE, opened files>preferences, entered the link, open tools>boards>boards manager, searched for esp32 but it showed blank. I tried three types which I all found on the net
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json
https://dl.espressif.com/dl/package_esp32_index.json
The error message I keep getting reads;
'Error downloading [the link I use]'

The last, https://dl.espressif.com/dl/package_esp32_index.json is what I believe to be correct and what I'd used when doing the work behind my prior comment.

What do you think could be the problem?

Also experiencing this issue, exactly as described by the OP. Anyone have a solution?


text:
Error uploading to esp 32 board
I had a problem when installing the esp32 core. I couldn't do it through the board manager procedure because I can't find esp32 for installation in the board manager even though I put the link correctly in the preferences section so I had to download a zip file and unzip it in hardware/espressif/esp32 folder. Now whenever I try to upload the code(a simple LED blinking code) it says error compiling for board with the following error message
exec: "C:\Users\ABDUL\Documents\Arduino\hardware\espressif\esp32/tools/xtensa-esp32-elf/bin/xtensa-esp32-elf-g++: file does not exist
Please help me. I don't know what to do anymore

So does the file, C:\Users\ABDUL\Documents\Arduino\hardware\espressif\esp32/tools/xtensa-esp32-elf/bin/xtensa-esp32-elf-g++, exist?

You know that, besides entering the link in the preferences section, you have to download and install the new board manager from the "Tools->Board XXX->Board Manager" menu, don't you?

what link is this? ... I put the link correctly in the preferences section

This link "https://dl.espressif.com/dl/package_esp32_index.json". I put it in preferences but I couldn't find the esp32 for installation in tools>boards>board manager. I searched as instructed but I couldn't find it

Sometimes it seems to help to close and reopen the IDE after editing the boards manager URLs list.

The correct link is https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json

I just tried it. It's showing the same result as the previous one. It's not showing esp32 in the board manager

Have you tried reinstalling the IDE or installing an older version?


text:
DC motor fan speed control with Temperature Sensor
I used this circuit schematic for the project however, when DC Motor starts to work, temperature value is increasing abnormally high. How can I solve this problem? It shows abnormal high values like 70, 85 ,101 etc.

#define TEMPERATURE A0
#define fan 3
void setup(){
Serial.begin(9600);
pinMode(fan, OUTPUT);
}

void loop(){
float temp = analogRead(TEMPERATURE);    //Read the analog pin
temp = temp * 0.48828125;   // convert output (mv) to readable celcius

Serial.print(temp);
//print the temperature status
Serial.print('\n');
delay(1000);

 if (temp<=24){
  analogWrite(fan, 51);

  delay(1000);

}
else if (temp<=26 && temp>24){
  analogWrite(fan,122);

  delay(1000);

}
 else if (temp<=30 && temp>26){
  analogWrite(fan,223);

  delay(1000);

}
else if (temp>30){
  analogWrite(fan,255);

  delay(2000);

}
}

Hello Raul, please edit your original question instead of asking a new one. Duplicate: DC Motor fan control with Temperature sensor

I think the problem lies in the fact, that you did not calibrate the sensor. You just take the analog reading and multiply it with 0.48828125. Where did you get this value from? And what kind of sensor do you use. The schematic shows a sensor with 3 pins. Is it perhaps a digital sensor like the 18B20? You can not use the analog port to read a digitial sensor.

I am assuming that whatever temperature you are measuring is not rising when the motor is on.
I see that you are sharing the power/ground between your temperature sensor IC and the motor.  Motors are extremely noisy from an electrical viewpoint and it's almost certainly causing your temperature sensor to malfunction.
It would be best to separate the temp sensor power/ground connections from the motor power/ground connections completely.  Power the motor from an external supply instead of sourcing it from the Arduino.
Another thing that might help is to add some bypass capacitors as close as possible to the motor and to the temperature IC across the Vcc and GND lines.  This will help to smooth out the power in spite of the noise that the motor itself generates.  Generally you want at least one of two types, an electrolytic capacitor and a ceramic capacitor.  These are both inexpensive if you don't already have some on hand.  I'll suggest a 10 uF electrolytic and a 0.1 uF ceramic capacitor near both the motor and the temp sensor.

Besides all the good advice from jwh20, you should start with a general strategy to find out where the problem lies.  You should hang a DVM directly between the sensor output and ground and see if the voltage also shows the rising problem.  If not, the trouble is in your code.
A drifting value is often due a wiring issue, like a bad sensor ground.  It wouldn't hurt to go over all the wiring very carefully.


text:
Attiny85 Clone Cannot set P1 to input
Everything i read about the chinese Digispark attiny85 clones says you can use p0-5 as digitlal I\O (p5 as after fuse reset)
Simple test code for a button will not let me use P1 as an input tied to a simple button.
The code below works on p0,p2,p5 but will only interrupt the LED that is set to on, on P1.
#include "DigiKeyboard.h"

//pins 3 & 4 used for usb connection
bool buttonState1 = 0;

void setup() {
  pinMode(1, INPUT);
  digitalWrite(1, HIGH); //turn on pull-up resistor
}

void loop() {

    if (digitalRead(1)!= buttonState1){
      buttonState1 = digitalRead(1);
      if (buttonState1 == LOW)DigiKeyboard.print("test1");
    }

}

I had a quick look into the Schematics of a digisparc board. P1 is hardwired over an LED and a resistor to GND. If you turn on the PULL UP resistor for P1 the LED should light up and the voltage at P1 would be very low (it depends on the voltage divider that is built from the PULL UP resistor and the LED resistor); so the P1 reading should be LOW. If you connected the Button to GND and press it, the voltage at P1 drops to 0. But, that does not affect the LOW state. The program does not react. The LED turns off, because it is not powered anymore.
You could try to connect the button to +5V and do not setup a PULL UP resistor for P1. If you press the button the LED should light up and +5V should be at P1. It should change its state from high to low. (I did not tried that; but I see no reason, why it would not work).


text:
Powering arduino sensors - what resistor should I use?
Recently I have asked a question, why my sensors do not work on external power supply (link). I have found out, that I was limiting the current too much with the resistors. I have tried using two sensors:

DHT22, rated at 1.5mA max (picture of my module)
BH1750, rated at 190uA max (picture of my module)

My logic is, if they are rated at that current, I should put a resistor in the Vin, to restrict the current to given value. But it turned out that I was wrong, because they started working only after I removed my resistors.
My questions is - should I put a resistor in there? If yes, then how do I know what resistance should I have, if the data sheet values are misleading?

You should have NO resistor.
The datasheet states the current values the device will pull from the supply. Supplies DO NOT PUSH CURRENT.
Remove all resistors.
As long as the voltage is correct and the supply can provide at least as much current as all devices combined want to use then it will work.

And I was wondering, why every electrical component had clearly specified the operating voltage, but the current was somewhere below in the details section. That would explain things. Thank you!

99% of components and devices require a specific voltage to operate, and the current varies depending on what it is doing at the time. The main exception is LEDs which have to have a specific current instead of a specific voltage.

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


text:
How to receive data from Xbee in AT mode on Arduino Nano
I need to print data on the Arduino serial monitor received from the Xbee in AT mode. I have searched on most forums and have not found anything on how to do this.
I have my Xbee tx connected to Arduino nano Rx and rx connected to tx.

You connected the Xbee to the single hardware serial interface that the Nano has. Is is also used by the USB to Serial chip, which connects to the Serial Monitor. So what you are sending to the Xbee is also sent to the Serial Monitor. What the Xbee sends is only sent to the Arduino (since the Xbee TX pin is connected to RX of Arduino and also TX of the Arduino's USB to Serial chip).
But you can separate then by using a SoftwareSerial interface on any other pins of your liking. Then you can connect the Xbee to it. Then forward the output of the SoftwareSerial interface to the Serial interface. To see how this works have a look the first example of the SoftwareSerial library. It's basically checking both interfaces, reads available data from one interface and writes it to the other (note the write() in contrast to print() since when forwarding you don't want to interpret the data again to another format like print() does).
Also there are plenty examples and tutorials about SoftwareSerial on the web. An important restriction is that only one SoftwareSerial interface can listen to data at any time. The Hardware Serial interface doesn't have such a problem.

Thank you for your reply. I will try this. You said that only one Software Serial can listen to data at once. Does this mean that I would not be able to connect a GPS module to a software serial interface on different pins as well as the Xbee module? How would I solve this problem?

When you are interfacing a module, which only will send data, when you ask for it, you can implement time sharing. So listen to one interface, asking the corresponding module for info and reading it. Then listen on the other interface, asking that module for info and reading it. Rinse and repeat. Though this only works if you cannot miss data from one module while you are reading the other. If you would miss data, you can change to a microcontroller with more Hardware Serial interfaces, like the Arduino Mega.

Ok thank you this makes sense.

How do I add the SoftwareSerial Library? It does not seem to come up in the Library Manager?

Because its already part of the Arduino Core. You don't need to install it. You can use it directly with the Arduino IDE.


text:
Can't upload arduino code on the board due to some programmer issues
As I connected my arduino-uno board and made sure of the "Board" selected, and the "Port" selected as well. There is a problem while uploading, I tried updating the arduino IDE, reinstalling all the arduino drivers, I tried to borrow a new arduino board from a friend and I am 100% sure it is working.
The message I get from the IDE:
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1d

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Thanks in advance!

First of all thank you for replying,
I double checked the chip and it is atmega328 and I am selecting the board.
But I want to try to change the baud rate to 9600 (Overriding Baud Rate) but I do not know how, do you have any clue?

I faced the same problem while uploading.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
To solve that I changed my port to another USB port and I selected the particular port, Its uploaded successfully. But it's in MacBook not in Windows.
Try this once, by changing the port.

Try changing baud rate to 9600.
Another thing to check is the chip your Uno has. My Uno has the atmega328. Make sure you select that board.

All Unos will have the Atmega328P.

The ide does not allow you to upload sketches? If it does not allow you to upload to your oard or your friends board i would assume the issue is witb the software. Maybe try reinstalling the ide. I had the same error problem with a avrdude and the buad rate was wrong. That might not be the case with yours.

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


text:
Bluetooth and Short Audio Source
I am looking to use an Arduino to monitor an incoming audio source (mobile radio/HAM/Walkie Talkie) for a transmission and send this stream through the car audio system speakers. Speaking back on the radio isn't important, but might explore using the car system for that as well.
My car provides the built in ability to listen to FM radio with my phone paired through bluetooth. When a call comes in on my phone, the car system detects and mutes the FM radio to play a ringtone from my phone over the car speakers. It also displays caller info, but I don't care about that for the radio audio. My car also has wired only Apple CarPlay. I would like to be able to plug my iPhone in through the cable for music streaming, and then connect my mobile radio through bluetooth to have the short messages mute the music and play the radio audio similar to the phone ring.
I am seasoned with Arduino but pretty new to bluetooth. Research so far looks like the ring and other actions happen through AT type of commands within the Headset Profile. Page 23 of the PDF below shows a RING command, but no ability to set the specific 'ringtone' if you will. Page 34 of the PDF suggests there is a way to set these ringtones or even an audio notification. Are these capable of relaying a live stream such as a mobile radio source?
Reference PDF: https://www.silabs.com/documents/public/application-notes/AN992.pdf
Is this something possible with a bluetooth module on Arduino?
The alternative scenario I can fall back on would be a Bluetooth middle man that can accept multiple audio signals (hopefully with bluetooth as an option), and then mute the primary source to play the secondary. I prefer above so I can use the CarPlay functions.


text:
Remote camera with Arduino MKR GSM
I'm interested in making a remote camera that could take and process still photos and send over cellular data using the Arduino MKR GSM. Is this feasible with the specs of the arduino? If it is does anyone have any suggestions of camera modules?

If you don't specify more details the answers to this are going to come down to responder's personal preferences.  E.g. how often are you taking pictures, how much data are you allowed to use, what resolution do you need etc.

Most Arduino boards don't even have enough memory to store a single still image. You might be able to get it to work, but it would be a lot of work. Get some other board, like for example the raspberry pi. Or get a cheap/old smartphone. A smartphone is probably cheaper than a board, and camera module and a GSM module combined.

Esp cam would be another option


text:
Broken USB connection
When I connected an external power supply to my Arduino Uno R3 (it was connected to PC via USB cable too), I heard Windows disconnected device sound and the device isn't visible since then (nothing happens when I plugin the USB). Cable is ok, because it works with the second Arduino. TX/RX LEDs don't blink anymore.
Following this guide, I checked two things:

I was able to flash ATMEGA328 with LED blinking program using external ICSP programmer and it worked
I was able to flash ATMEGA16U2 with the official firmware and it completed without any error

Is there anything else I can check? I'm not really desperate to fix it - I just want to know which component is broken.

Is it possible that the voltage on your external power supply exceeded the limits of the Uno's input?  The range is 6-20V DC with (+) at the center.  If you exceeded 20V or if the polarity was reversed the Uno may be damaged.

Does the power LED come on?

Power supply is 12V. Yes, the power LED is on (both with USB or power supply). The board itself works just fine. The only problem is with missing USB signal.

trace usb lines on arduino board.  could be dead usb-tty chip.

Is it possible you connected the 12V to the 5 volt pin. This would probably blow the port on windows and destroy the arduino but it appears you got lucky with the arduino. Try something else not related to the Arduino stuff after powering down and restarting the windows computer. If that does not work the odds are high the Windows port is blown. If it now is working try again you may be all set.

USB port in PC is ok. I checked it with my 2nd Arduino.

Good Job, I am glad the PC is OK, I am a Linux person so about the only thing I know about windows is I look through them. At this point without the board and proper tools I cannot be of any more help, good luck.


text:
utf8 to hex macro
I would like to replace utf8 characters to byte values for easier character display handling.
The actual replacement table comes from the lcd datasheet therefore it is not utf8 to ascii conversion. Hence I would like to define some macros, where I put the utf8 character, and it returns some matching hex code.
Here is the bare minimum code:
#define IV('┌') 0xC9
#define IV('°') 0xB2

char line0[4] = {0xC9, '4', 0xB2, 0}; // works
char line1[4] = {IV('┌'), '4', IV('°'), 0}; // do not work

void setup() {}
void loop() {}

It does not compile and I must be missing something obvious or rather basic.
Any help is much appreciated.

#define IV('┌') 0xC9

That really isn't how macros work. What goes in the brackets is a named parameter that is then used in the body of the macro. You can't have multiple macros named the same like that.
The simplest thing to do is just make a set of macros named after what the character is.  For example:
#define CHR_DEGREE 0xc9
#define CHR_BOX_TL 0xB2

char line1[4] = {CHR_BOX_TL, '4', CHR_DEGREE, 0};

I do not want to have english names of the chars as defines, the whole point of my post is be able to do semi-ascii art. Some kind of lookup table is desirable.

UTF-8 is not a simple 1:1 mapping. It uses character sequences of variable length. A simple lookup table is not possible.

I came up with a solution, please see below. I hope you or someone else has a better way to do it.

@user12933 There's a flaw in your design: a char can't contain a UTF-8 multi-byte character,

Does it count that it compiles and works as expected irl on a real lcd screen? (just tested it, no artifacts every char/symbol show up)

@user12933 If the first byte of each of those characters is unique then fine. It will discard any subsequent bytes in the character. You'd be better using wchar_t and UTF-16 instead (L'┌')

Let us continue this discussion in chat.

After some googling I came up with this solution.
I really hope someone finds a more elegant way to express it.
These embedded ternary operators are really error prone.
#define IV(i) ( \
(i)=='┌' ? 0xc9 : \
(i)=='⎩' ? 0x15 : \
(i)=='⎭' ? 0x17 : \
(i)=='⎰' ? 0x18 : \
(i)=='°' ? 0xb2 : \
(i)=='™' ? 0xd0 : \
(i)=='Ξ' ? 0xd8 : \
(i) )

char line2[21] = {0x15, '_', 0xd8, '_', 0x17, 0xd0, '1', 0xc9, '5', 0x18, '5', '0', '0', 0xb2, ' ', ' ', ' ', ' ', ' ', 0}; //original
char line4[21] = {IV('⎩'), '_', IV('Ξ'), '_', IV('⎭'), IV('™'), '1', IV('┌'), '5', IV('⎰'), '5', '0', '0', IV('°'), ' ', ' ', ' ', ' ', ' ', 0}; //wanted

void setup() {}
void loop() {}

Macros can give weird errors is you do not parenthesize them properly. Here, you have lots of useless parentheses, yet the ones that would be needed to make the macro safe are missing. With only the required parentheses it would look like: #define IV(i) ((i)=='┌' ? 0xc9 : (i)=='⎩' ? 0x15 : (i)=='⎭' ? 0x17 : (i)=='⎰' ? 0x18 : (i)=='°' ? 0xb2 : (i)=='™' ? 0xd0 : (i)=='Ξ' ? 0xd8 : (i))

@EdgarBonet ty, corrected.


text:
MKR Wifi 1010 Project Design
I am newer to microcontrollers and have my first project I would like to try. I have started to sketch out a basic design and would like feedback on things that I may be missed or over looked. I understand I am new and things are probably not correct or I might miss use terminology, please feel free to correct me in any aspect.
Project Scope- I would like to integrate the MKR Wifi 1010 into Alexa using IoT to have an Alexa command sent to the MKR Wifi 1010 that then pulls in a relay that actuates a 12v solenoid.
Hardware
Power supply 1- FQCMOGU AL-1250, Input 100-240v 1.6a, Output 12v 5a
Power supply 2- Drok 15w DC/DC, Output 5v 3a
Microcontroller- Arduino MKR Wifi 1010
Relay- Songle SRD-05VDC-SL-C
Solenoid Valve- Beduan 12v
Here is a sketch of my original plan. Let me know any safeties/ protections I may have missed, calculations that do not make sense or if there is an easier/ better way. I have not order the hardware yet and want some people better at this than me to check it over before I do.

a common project with Arduino IoT Cloud and MKR 1010. https://create.arduino.cc/projecthub/303628/arduino-iot-cloud-amazon-alexa-integration-4e6078

@Juraj Thank you for the response. I did read that article and it is the reason I chose the MKR 1010 for this project.
What I was looking for out of this question was a second opinion on my design to make sure I am not setting my self up for any early failures or better methods of achieving this project.
I will re-read the article to make sure I did not miss anything.


text:
SoftWire Library Programming Questions for I2C with Digital Pins
I am trying to use 3 TOF10120 Laser Sensors with one Arduino that all have the same, fixed I2C Address. I don't believe it is possible to change the I2C address of the TOF10120, but if I am wrong, please let me know (also, I need 3 different addresses). This being said, I am trying to use the SoftWire Library (https://github.com/stevemarple/SoftWire - very interesting library, but not great documentation) to help me to use my three sensors with Digital Pins. Does anyone have any experience with the SoftWire Library and how to get readings from a laser sensor?
I can provide the code I have, but it probably wouldn't be very helpful anyway. I am particularly curious as to how to use the DigitalWrite() and DigitalRead() functions for I2C with SoftWire.
Thanks for all the help in advance!

you are asking questions about a sensor, but you have not provided any documentation for the sensor

The datasheet is in another language - it isn't helpful at all. The default address is 0x52 for I2C. I bought the sensor from here: https://www.amazon.com/Taidacent-100-1800mm-Distance-Infrared-Detector/dp/B07KW1XN5X

foreign language datasheet is more useful than no datasheet

Link to Datasheet PDF in Google Drive: https://drive.google.com/file/d/1KAIB9xDaO4HcIDBsFz9ia2koAKH_af-_/view?usp=sharing

that datasheet has enough english to find what you need ... there appears to be a command to set the I2C ID ... use google translate to confirm

Would you mind telling me on what page and in what location/line on that page that command is? Also, how do you even send the sensor the command?- any resources for doing so would be greatly appreciated.

I found where it is, but am unsure of exactly how to proceed. Is the command s7-xxx#? How would I even send this command to the sensor? I wouldn't think it would be via the Arduino IDE.

connect one sensor to arduino and use a sketch to send the command

You may use the SoftWire library for that. You may share the SCL lines and have one SDA line for every sensor. Look at the "ListDevices" example of the SoftWire library; you will have to create three SoftWire objects with different SDA pins. Alternative, you may use an I²C multiplexer like TCA954x (there are breakout boards available), which is more convenient as you can use the default (hardware) Wire library and save space and cycles.

You can change the tof10120 to any i2c address between 1 and 254. you need to write the serial string 's7-xxx#' where xxx is the decimal address required (in string form). I wrote a simple python program for the raspberry pi to change my sensor addresses via the Rx Tx.

If would be good to add a reference to where that information can be found in official documentation if possible.  From what I gather the change is perminant, or rather non-volatile.  If that's correct, it might be good to say.


text:
Bluetooth Upload is Hanging
I am trying to program my Arduino via bluetooth and have been following this tutorial very closely in order to do so: https://www.instructables.com/Program-an-Arduino-Wireless-Over-Bluetooth/
I have been able to put my HC-05 into AT command mode, entered the commands, and received the "OK" responses. When I go to try to upload the code, however, the sketch usually hangs and nothing happens. The TX on my HC-05 goes to the Arduino RX, RX to TX, VCC to 5V, GND to GND, and EN to RESET.
I am able to see the device no problem on my windows computer and seem to be using the correct port. Any ideas on how to fix the issue?
Any help is greatly appreciated!

what is EN pin?

I think it is the same as the Pin 32 or something. My HC-05 only has STATE, VCC, GND, TXD, RXD, and EN.

as you can see in the tutorial the wire for reset is solder directly to the Bluetooth module. it is not a random pin.

How should I connect the HC-05 to the Bluetooth module then?

do you have the reset wire soldered to the BT module?

I was just reading this tutorial: https://www.fpaynter.com/2019/06/arduino-remote-programming-using-a-hc-05-bluetooth-module/ which indicated that I instead should connect the STATE pin to the Arduino's RESET pin. It still is not working though.

I was just reading more of that tutorial again - my HC-05 shows no lights or anything when plugged in. Is that a problem?


text:
Where are source files for Due?
Where are the source files containing the definitions and the HAL functions located for the Due?
I am trying to do CMSIS programming.

There is an interesting discussion about Hardware Abstraction Layers (HAL) on Reddit’s r/Arduino. They assert that the Arduino environment as a whole is a HAL. https://www.reddit.com/r/arduino/comments/2y61su/when_would_you_start_caring_about_the_hal/?utm_source=share&utm_medium=ios_app&utm_name=iossmf

There is also an interesting discussion on the Arduino forum about getting started with the common microcontroller interface standard (CMSIS) https://forum.arduino.cc/t/anyone-using-cmsis-how-to-get-started/226150

Also there are a number of CMSIS libraries available for Arduino.

The Arduino Core for supporting Arduino Due is called ArduinoCore-Sam, which can be found at https://github.com/arduino/ArduinoCore-sam, inside the system directory, you will find the CMSIS device driver.


text:
Arduino DUE wheel encoder
I have an Arduino due, I am trying to keep track of ticks on two wheel encoders, polling in an infinite loop results in terrible performance. Have any suggestions?
It looks like the due might have an internal counter but I don't know how to use it, is there a library?

please add your code to the post ... the performance issue may be caused by bad code

You can use an interrupt handler to measure frequency. Works quite well.
volatile int32_t _ticks = 0;
public void FrequencyIsr()
{
    _ticks++;
}

// Add this to setup()
// Mode can be FALLING, RISING or CHANGE
attachInterrupt(digitalPinToInterrupt(pin), FrequencyIsr, mode);

// Add this to loop()
int32_t currentTime = millis();
// Clear the interrupt flag, so that we can read out the counter
noInterrupts();
int32_t ticks = _ticks;
interrupts();
// and then calculate the amount of ticks since the last update (if you need the speed)
int32_t timeDelta = currentTime - _lastTime;
int32_t tickDelta = ticks - _lastTicks;
double ticksPerMs = (double)tickDelta/timeDelta;
_lastTime = currentTime;
_lastTicks = ticks;


text:
Mirroring PWM input on a pin + Motor Encoder
I am interested in hooking up a nano to an RC receiver. I want the nano to mirror the PWM input and output on another pin when a specific command is given via serial. I also want to send the received command via serial to a computer(Pi or Jetson) at the same update rate.
I can run pin change interrupt on the input pins to basically enable/disable the pins but I'm wondering if there is a better way.
I also will be updating a motor encoder at pin change interrupt, I'm guessing around 4k interrupts/second.
Do you think the Nano provides enough juice or I should use a Pico?

You haven't mentioned the PWM frequency nor did you mention the baudrate of the serial. But if we do the math here, classic Nano runs on 16MHz i.e. per cycle is 62.5 nanoseconds. That's plenty if juice if you do everything right.


text:
How does the compiler/assembler work wrt bootloader?
I realized that on the atmega boards the bootloader is programmed into the chip.
I'm curious, when compiling a sketch how does the compiler/assembler differ from compiling a standard C program for a chip without a bootloader?
Is there still a main? Does the linker put the startup code in a different area? Obviously with the bootloader you're no longer compiling a program which places code at the reset address.

https://stackoverflow.com/questions/919781/how-can-i-get-an-assembly-language-listing-of-my-arduino-sketches-on-windows#930855

On the Uno and similar AVR-based boards, the compiler and assembler are
not aware of the bootloader. The compiled program starts at address
zero. There you have the interrupt vector table, starting with the reset
vector. That vector is a jump to the C runtime startup code, which does
some low-level initialization, then calls main() from the Arduino core
library, which calls setup() and loop() from your sketch.
The bootloader lives at the end of the flash. The AVR chip has a few
bytes of non-volatile configuration memory called “fuses”. These bytes
are configured by the Arduino board maker to dedicate the last
512 bytes of flash to the bootloader, and to start executing the
code at the start of the bootloader on power up and on reset events. It
is then the bootloader's responsibility to jump to address zero in order
to start the user's program.

So I can write standard programs with avr studio and not change anything and have them loaded?

@FourierFlux: I have never used AVR Studio, but I do occasionally write regular AVR programs using avr-libc, compile them with avr-gcc, and upload them to an Uno using avrdude.

Ok but the point is you just compile a standard C program.

warning for future readers. the answer really only applies to AVR architecture. it doesn't carry over to other architectures


text:
Setup Due counter
How do I setup a Due to count rising edges on a pin automatically without having to waste time on an ISR?
I have some wheel encoders, the simplist implementation is direction less where you only count rising edges.
I went the Due to count rising edges automatically and an ISR on a timer will periodically pole the current count

what does this mean? ... waste time on an ISR

what does this mean? ... timer will periodically pole

encoder questions have been asked, and answered many times ... this site is not a tutorial forum, so please do research first, then ask questions about any problems that you encounter

From what I understand the Due has a counter with internal circuity instead of an ISR using to count.

Have you a reference for that claim?

Normally I would set up a timer/counter to use an external clock. Looks like the atsamd does it differently and uses a "count on event" setting. Read the datasheet and see if you understand it (I don't from a cursory glance).

Actually I was looking at the SAMD21 not the SAM3X of the Due. That seems to have TCLK0-TCLK2 as clock inputs to timers. Chapter 36 of the datasheet details them.

You need to pick a timer that isn't being used for anything else and configure it as a simple counter with the clock source set to the external clock pin for that timer.

At block level, input clock signals of each channel can either be connected to the external inputs TCLK0, TCLK1 or
TCLK2, or be connected to the internal I/O signals TIOA0, TIOA1 or TIOA2 for chaining by programming the TC
Block Mode Register (TC_BMR). See Figure 36-2.
Each channel can independently select an internal or external clock source for its counter:

External clock signals(1): XC0, XC1 or XC2
Internal clock signals: MCK/2, MCK/8, MCK/32, MCK/128, SLCK
This selection is made by the TCCLKS bits in the TC Channel Mode Register (TC_CMR).

I am not personally familiar with the peripherals of the Due, but chapter 36 of the SAM3X datasheet details the workings and registers that you need to set.
Your encoder signal then connects to that clock input pin and the counter then counts every incoming pulse until you reset the count from your other periodic timer ISR.


text:
Where is the positive and negative holes on the arduino mini breadboard?
I have the mini arduino breadboard. The pins go from A to J and 1 to 17. On the larger breadboard, there are symbols + and -. My breadboard doesn't have those two sections to put wires in. Does anyone know what to do?

Does anyone know what to do?

Do whatever you want to do.
There's nothing special about the +/- rails of a breadboard - they're just chunks of metal that go along instead of across, and are longer, with more holes, and someone has helpfully coloured them red/blue and added some symbols.
If you want a common place for + and - then just choose a common place for + and -.


text:
ESP8266 SocketIOclient constant disconnect with Python WebServerSocket
I am writing a program that echos back the message sent to the web socket server on a host machine. When running the ESP module, the connection is established but immediately disconnects as seen in the first image. I originally thought this maybe a result to the host machines firewall, however, using my laptops connection, I was able to produce the desired echo. Is the constant disconnect a result in different protocols or something I am missing?
WebSocketServer on host machine (modeled off example)
import asyncio

from autobahn.asyncio.websocket import WebSocketServerProtocol, \
    WebSocketServerFactory

class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

        # echo back message verbatim
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

if __name__ == '__main__':
    factory = WebSocketServerFactory("ws://127.0.0.1:9000")
    factory.protocol = MyServerProtocol

    loop = asyncio.get_event_loop()
    coro = loop.create_server(factory, '0.0.0.0', 9000)
    server = loop.run_until_complete(coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
        loop.close()

ESP8266 modeled in arduinoWebSockets
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ArduinoJson.h>

#include <WebSocketsClient.h>
#include <SocketIOclient.h>

#include <Hash.h>

ESP8266WiFiMulti wiFiMulti;
SocketIOclient socketIO;

void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
    switch(type) {
        case sIOtype_DISCONNECT:
            Serial.printf("[IOc] Disconnected!\n");
            break;
        case sIOtype_CONNECT:
            Serial.printf("[IOc] Connected to url: %s\n", payload);
            socketIO.send(sIOtype_CONNECT, "/");
            break;
        case sIOtype_EVENT:
            Serial.printf("[IOc] get event: %s\n", payload);
            break;
        case sIOtype_ACK:
            Serial.printf("[IOc] get ack: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_ERROR:
            Serial.printf("[IOc] get error: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_BINARY_EVENT:
            Serial.printf("[IOc] get binary: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_BINARY_ACK:
            Serial.printf("[IOc] get binary ack: %u\n", length);
            hexdump(payload, length);
            break;
    }
}

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

    //Serial.setDebugOutput(true);
    Serial.setDebugOutput(true);
    Serial.printf("[SETUP] starting up");

    Serial.println();
    Serial.println();
    Serial.println();

      for(uint8_t t = 4; t > 0; t--) {
          Serial.printf("[SETUP] BOOT WAIT %d...\n", t);
          Serial.flush();
          delay(1000);
      }

    // disable AP
    if(WiFi.getMode() & WIFI_AP) {
        WiFi.softAPdisconnect(true);
    }

    wiFiMulti.addAP("ssid", "password");

    //WiFi.disconnect();
    while(wiFiMulti.run() != WL_CONNECTED) {
        delay(5000);
        Serial.println("Retrying...");
    }

    String ip = WiFi.localIP().toString();
    Serial.printf("[SETUP] WiFi Connected %s\n", ip.c_str());

    // server address, port and URL
    socketIO.begin("local host address", 9000);
    // event handler
    socketIO.onEvent(socketIOEvent);
}

unsigned long messageTimestamp = 0;
//int attempts = 0;
void loop() {
    socketIO.loop();
}

First, does the default ESP8266 example work with your Python server? It's best to start with that as a reference. Next, did you change any of the library's default config, uncomment or comment out anything?
At the moment, neither device is showing that the Websocket connection was ever opened, they just show "disconnected" or "closed", so something likely happened during the setup stage that made one party drop the connection. Try adding #define DEBUG_ESP_PORT Serial to WebSockets.h (after the Arduino.h inclusion), so we can see more detailed logging from the library.

Hi @SoreDakeNoKoto , thanks for the reply. After some sleep and a deeper dive, I found a post that suggested the library was the problem. Ended up using this instead. Best

After testing the server on the host machine using an additional computer, I was able to produce the desired output. I would suspect it is an issue within the library or mis-use/understanding. I found a post that suggested the library was the problem and ended up using this library instead.
Using the example implementation , I was able to achieve the desired results.


text:
Reliably measuring the energy consumption of arduino running sketch
I would like to know if there is a programmatic way of measuring the energy consumption of a sketch or at least if this is possible via external devices.
My aim is to compare the energy consumption of two devices, connected to usb, running slightly modified versions of the same sketch e.g., one using crypto and one without using crypto.

Are you only interested in that, or do you really want to reduce power ? For example with a battery operated Arduino ? For a ATmega328P as a bare-bone Arduino, the actual code does not make the difference, but the sleep mode (there are a number of different sleep modes) does and of course how long the Arduino is busy between sleeping is important, and also the clock speed. Without sleep mode, it does not matter what code the Arduino is running.

use something like this one with time counters, or the simpler and cheaper spot-reading USB meters

@user35247 Not a duplicate.  Your link is about using an Arduino to measure the consumption of other things, this is about measuring the consumption of an Arduino.  Though as already pointed out, there's not much variation to measure until the software starts playing with hardware features beyond merely running code.

programmatic way of measuring t

Not sure what you meant by that but typically you can use a high side current sense amplifier to get a measurement of the current. Then adv a known voltage to get vcc. That known voltage could be the internal reference, if available
In some cases a resistor on vcc can be used to measure current, together with two dividers.


text:
How to read a timer's value once stopped?
I've downloaded the Timer1 library but unfortunately it seems that the read() method has been removed from it. I tried also SimpleTimer library from the arduino website but the program didn't compile because of undefined reference to `SimpleTimer::SimpleTimer()' error. Anybody knows how to solve this error or just another timer library which has a read function?
To be more specific I need to start a timer as I press a button and to stop it as it is released.

Have you considered looking for an input capture library instead?

To start a timer, give it a clock by setting the CSn2..0 bits. One set of those bits stops the clock thus the timer. Read the data sheet to be sure.

Here, below is a code which is you looking for. When you pressed a button then a timer is started and when you released it then a timer is stopped. And you can also see that time also means how long button is pressed.
const uint8_t button_pin = 2;

void setup()
{
    pinMode(button_pin, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop()
{
    static int last_button_state = HIGH;
    static unsigned int push_count;
    static unsigned long last_press_time;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if (last_button_state == HIGH && button_state == LOW) {
        push_count++;
        last_press_time = now;
    }

    // Report when the button is released.
    if (last_button_state == LOW && button_state == HIGH) {
        unsigned long push_duration = now - last_press_time;
        if (push_duration < 10) {  // discard bounce
            push_count--;
        }
        else {
            Serial.print(F("pushes: "));
            Serial.print(push_count);
            Serial.print(F(", duration: "));
            Serial.print(push_duration);
            Serial.println(F(" ms"));
        }
    }

    last_button_state = button_state;
}


text:
Tap into display signal
(Newbie Arduino developer).
I am interested to read the signal being sent to a small flat screen display in an industrial appliance, while not disturbing the display. The goal is to capture screenshots and upload them over a network connection.
Is that possible. What do I need to find out about the signal/display?
Any pointers to get started, would be greatly appreciated.

Depends on how much resources (time and money) you have. An AVR based Arduino will have a hardtime capturing display signals and holding and uploading the image. The simples solution is a web-cam.

If you want to interface electronically: Different display technologies (LED and LCD being the most likely of many) combined with many different electronic protocols makes this question too vague to even start to answer. If you want to build an optical interface: To understand patterns captured by a camera, often people use computer vision.  OpenCV is a commonly used software package for computer vision.  However, OpenCV requires a very robust computer to run on.  So only the high end Arduino boards with real operating systems are viable options for this purpose.

On the other hand, if it's a little text-only LCD, being driven not too fast, you might stand a chance as the protocol is fairly simple. More information required certainly.

Will try to see what information can be gathered, when I have it taken apart the next time.


text:
How to convert numbers from Serial port input to HEX String?
I am trying to read digits (number from 0 to 255) from Serial port, convert them to HEX String and send them using SoftwareSerial as HEX.
For example:
when I send '60' trough the serial port, the SoftwareSerial will send '3C'
currently I am using the following code:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 4); // RX, TX

String inputString     = "";
boolean stringComplete = false;

int HexInt = 0;
String HexString = "00";

void setup() {
  Serial.begin(115200);
  mySerial.begin(38400);
  inputString.reserve(200);
  delay(500);
  Serial.println("");
  mySerial.println("");
}

void loop() {
  serialEvent();
  if(stringComplete) {
    HexInt = inputString.toInt();
    HexString = String(HexInt,HEX);
    if (HexInt<16) HexString = "0" + HexString ;
    HexString.toUpperCase();

    mySerial.println(HexString);

    Serial.println(inputString); //debug
    stringComplete = false;
    inputString = "";
  }

}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar == '\n') continue;
    if (inChar == '\r') {
      stringComplete = true;
      if (inputString == "") inputString = "NULL";
      inputString.toUpperCase();
      continue;
    }
    inputString += inChar;
  }
}

My question is:
Is there a more elegant / effective way to perform the same outcome?

You have the number. It's made up of two nibbles, each representing 4 bits (1 hex character).
If you want to do a manual conversion take the first nibble (AND with 240) add it's value to "0" then do the same for the lower nibble (AND with 15).
OR
What I would do is use:
char HexString[3];
sprintf(HexString,"%02X",HexInt);

since you're not dealing with floats, you're good to go.
OR
edit: I recalled a printf function that we put together once before, I don't know if it would work with SoftwareSerial, so you might have to play around with it a bit, but as a 3rd option, you could try the following. I don't have access to an Arduino or compiler at the moment, otherwise I'd have a play with this right now.
Before your setup:
// Function that printf and related will use to print
int serial_putchar(char c, FILE* f) {
    if (c == '\n') serial_putchar('\r', f);
    return Serial.write(c) == 1? 0 : 1;
}

FILE serial_stdout;

In your setup, add:
// Set up stdout
fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE);
stdout = &serial_stdout;

in your loop, change your assignment to:
HexString = printf("%02X",HexInt);

from: https://arduino.stackexchange.com/a/480/304

It should be char HexString[3];, you need space for the null terminator at the end of the string. And depending on the source of the data input it may make sense to either use snprintf or verify that the value is never outside the expected range. It pays to always be paranoid about buffer overflows.

I usually have to think about these, but running a quick test in gcc confirms for a value of 0x05, HexString[0]='0', HexString[1]='5',HexString[2]=0.

Exactly, an array that is 3 long not the 2 long that you are allocating.

yes. you're right... edited :)

thank you very much for the quick respond.. I tried using the Second solution but I have a different issue now. I am actually trying to sent the HexString + another String like this mySerial.println("GR+" + HexString); and I get an error regarding char and string cannot be added together.

did you solve that? If not you should ask a new question and post a link here so I can catch it. It depends, what does HexString now contain? guessing by the error it's a char since "GR+" is a string. In the mean time and since it's just the .println() you're having a problem with here, just use multiple .print() and a .println() to achieve the same thing

@Madivad this is exactly how I solved it - I use print("GR+") followed by a println(HexString). thank you!


text:
ESP8266 - UDP send interruptions
I'm trying to transfer data from ESP8266(NodeMCU ESP12E) to my laptop. I'm coding ESP using Arduino IDE. I am able to receive correct packets (each containing 400 bytes) on a visual basic console program. However, to see whether the transmission is continuous or not, I have toggled an output pin whenever UDP.endpacket() returns 1. I observed waveforms on DSO. I found that UDP.endpacket() does NOT return 1 many times and the there is no transmission from ESP for a significant amount of time (milliseconds). Refer attached waveforms.
Why does UDP.endpacket() return 0 for such long time? Why is UDP transmission getting interrupted? How can I solve this? Please feel free to ask for more details if necessary.
Code :
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "Connectify-me33";
const char* password = "donfour276";

WiFiUDP Udp;
unsigned int localUdpPort = 65000;

unsigned int dest_port = 11000;

unsigned char clientBuf[400];
int clientBuf_len=0;

#define test_pin 5

int return_udp_fcn = 0;

void setup()
{

  WiFi.begin(ssid, password);
  delay(5000);

  Udp.begin(localUdpPort);

  pinMode(test_pin, OUTPUT);
  digitalWrite(test_pin, HIGH);

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);

}

void loop()
{
        digitalWrite(test_pin, HIGH);

        //filling up buffer
        for(clientBuf_len = 0; clientBuf_len<=399; clientBuf_len++)
        {
            clientBuf[clientBuf_len] = 0x7E;
        }

        //UDP transmit
        Udp.beginPacket("172.22.0.1", dest_port);
        Udp.write((const uint8_t *)clientBuf, 400);
        return_udp_fcn = 0;
        return_udp_fcn = Udp.endPacket();
        if(return_udp_fcn){
          digitalWrite(test_pin, LOW);
        }
        delayMicroseconds(100);

}

I think you need a delay(1); after your call to write().
There is/was a bug where the underlying buffer files up and can't get time to clear.  It looks like it will require a change to the ESP8266 firmware from the manufacturers before it will get fixed properly.
See what you think:
https://github.com/esp8266/Arduino/issues/1696
https://github.com/esp8266/Arduino/issues/2285

Thank you for your quick response. I tried again with a delay after write. I got the same results. I also tried with multiple delays after each line in the code. The problem still persists.


text:
How to program an Arduino Uno to collect data using a timer interrupt and analyze that data in matlab?
I working on a project where I want to collect sensor data (from a sensor) and I want to analyze the first 20 data sample (e.g., find the range, trendline e.t.c.). I know how to compile a timer interrupt in Arduino IDE (using an ISR timer), but how would I be able to do this something similar (ISR timer) in MATLAB. The reason being, I want to collect my sensor data at exactly 20 Hz and using a delay function can prove to be inaccurate. Also, when I run a sample program that collects data in MATLAB, my sample frequencies change from 15Hz to even 24Hz (as shown below) . Does anyone have any suggestion on how I can do this? If the question is not clear enough I can elaborate more in the comments.
This is my MATLAB code:
clear all;
a = arduino('com4', 'uno');
i = 0;
v1 = zeros(1e4,1);
v2 = zeros(1e4,1);
x = zeros(1e4,1);
t = timer('TimerFcn', 'stat=false; disp(''Timer!'')',...
                 'StartDelay',5,'Period', 1);
start(t)

stat=true;
tic
while(stat==true)
   %while i<60
    i = i + 1;
    v1(i) = readVoltage(a, 'A0');
    v2(i) = readVoltage(a, 'A1');
    x(i) = i;
    disp(x(i));
    pause(.00001);

  % end
end
toc

% %Plot voltage versus time
v1 = v1(1:i);
v2 = v2(1:i);
x = x(1:i);

p = v1;
n = v2;
%Plot voltage versus time
figure(1);
plot(x,p,'-',x,n,'-')
xlabel('Elapsed time (sec)')
ylabel('v')
title('Ten Seconds of voltage Data')
%set(gca,'xlim',[t(1) t(i)])
legend('v1', 'v2');

%
delete(t) % Always delete timer objects after using them.

Output is
>> Timer
     1

     2

     3

     4

     5

     6

     7

     8

     9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

Timer!
    76

Elapsed time is 5.032553 seconds.
>>

I apologize for the long output. But as you can see, I specified a pause time of .00001, which should give me well over a 20Hz sampling frequency. But I only get 76 samples/5 seconds = 15.2Hz. Also, sometime when I run this the program may collect 79sample/5secons, or even  121sample/5seconds. It just is not consistent. I was hoping to solve this with a timer interrupt that will be hard coded in MATLAB to collect data at exactly 20Hz. Please let me know what y'all think. Thank you.

This is Arduino SE, so we can tell you how to use a timer interrupt in Arduino. But we are no Matlab experts, so your question is off topic here. Currently the sample frequency is directly dependent on the execution time of all the involved function calls, including readVoltage() you didn't account for that I guess. I don't know, what exactly that function does and what firmware you have on the Arduino. Depending on that you might need to write your own firmware, that can be better fitted to your goal. The readVoltage() function might be too slow.

I agree with chrisl: this looks more like a Matlab question than an Arduino question. 2. I don't think Matlab is the right choice for real-time sampling. You could instead let the Arduino handle the timings and send the data through the serial port, then process the data on Matlab.

The latency for matlab with arduino is a known issue. A good start would be to change the default communication speed of 9600 baud

Your title says you want to collect the data with an Uno and analyze it with MATLAB, but your description suggests you are also trying to collect some data with MATLAB. Which one is correct? If it's as the title says, MATLAB doesn't need to sample at all; it only needs to read the collected data from the Uno, after the fact.

You have an Arduino in your project, which runs ISR loops at very precise intervals. There's no point in adding timing on the receiver side. Just timestamp the data and collect it as it comes in.

I've configured the timer differently making use of its UserData property. The timer will update the data every fixed period for a specified number of samples.
close all;
clear all;

% Some useful constants.
NUM_SAMPLES = 20;
PERIOD = 0.05;

global a;
a = arduino('com4', 'uno');

% Initialise data. It will be updated by the timer.
data.i = 0;
data.v1 = zeros(NUM_SAMPLES, 1);
data.v2 = zeros(NUM_SAMPLES, 1);
data.x = (1:NUM_SAMPLES) * PERIOD;

% Initialise timer for a fixed period for a specific number of samples.
t = timer;
t.ExecutionMode = 'fixedRate';
t.Period = PERIOD;
t.TasksToExecute = NUM_SAMPLES;
t.TimerFcn = @TimerCallback;
t.UserData = data;

% Run the timer and wait for it to complete.
start(t);
wait(t);
stop(t);
data = t.UserData;  % Retrieve the updated data.
delete(t);

% Plot voltage versus time.
figure(1);
plot(data.x, data.v1, '-', data.x, data.v2, '-');
xlabel('Elapsed time (s)');
ylabel('Voltage (V)');
title('Voltage Data');
st = sprintf("%0.3f seconds", NUM_SAMPLES * PERIOD);
subtitle(st);
legend('v1', 'v2');

function TimerCallback(obj, event)
    global a;
    obj.UserData.i = obj.UserData.i + 1;
    obj.UserData.v1(obj.UserData.i) = readVoltage(a, 'A0');
    obj.UserData.v2(obj.UserData.i) = readVoltage(a, 'A1');
end

Each communication with Arduino takes 20ms, you have two in the loop so in the ideal conditions you could get 25 readings/second. See here the source
This also depends on the size of the data you request.
I think this is what you are looking for but I cant give you any advice since I don't have Matlab and Octave is not having this feature.


text:
How to exit out of a timer interrupt (ISR(TIMER1_COMPA_vect))
I have a code here where I collect an array of data and do some data analysis with the data. The only thing I'm struggle with is how to exit the ISR after I am done running my code. I am using a pre-scalar of 256 and running the ISR once (1Hz)
const signed int numReadings = 21;
volatile int gauge0[numReadings];
volatile int gauge1[numReadings];
volatile int add[numReadings];
volatile int deltaGAUGE;
volatile int slopeADD;
volatile int mean;

const int A0_pin = PC0;
const int A1_pin = PC1;

const uint16_t t1_load = 0;
const uint16_t t1_comp = 62500;

void setup() {

  //Set A0 and A1 pins as inputs
  DDRC &= ~(1 << A0_pin);
  DDRC &= ~(1 << A1_pin);

  //Reset Timer1 Control Reg A
  TCCR1A = 0;

  //Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  //Set to prescaler of 1024
  TCCR1B |= (1 << CS12);
  TCCR1B &= ~(1 << CS11);
  TCCR1B &= ~(1 << CS10);

  //Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  //Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  //Enable global interrupt
  sei();

       Serial.begin(9600);
       Serial.println(" ");
       Serial.println("START");
        Serial.println(" ");

}

ISR(TIMER1_COMPA_vect){

       Serial.println(" ");
        for (unsigned int i=0; i<numReadings; i++)
            {
                        gauge0[i] = (analogRead(A0_pin))*(100.00/1024.0);
                        gauge1[i] = (analogRead(A1_pin))*(100.00/1024.0);
                        add[i] = ((gauge0[i]+gauge1[i]));

                        deltaGAUGE = abs(add[20] - add[0]);
                        slopeADD = abs((add[20]-add[0])/(20-0));
                        mean = (add[1]+add[2]+add[3]+add[4]+add[5]+add[6]+add[7]+add[8]+add[9]+add[10]+

                     add[11]+add[12]+add[13]+add[14]+add[15]+add[16]+add[17]+add[18]+add[19]+add[20])/20;

                        if(i == 20)
                {
                      Serial.print("This of the delta AVG reading: ");
                      Serial.println(deltaGAUGE);
                      Serial.println(" ");
                      Serial.print("This of the slope reading: ");
                      Serial.println(slopeADD);
                      Serial.println(" ");
                      Serial.print("This of the mean reading: ");
                      Serial.println(mean);
                      Serial.println(" ");
                      Serial.println("END");
              }

                        delay(50); //wait .05 sec

          }

}

void loop()
{

}

When I run the circuit, the interrupt keep executing every seconds for an infinite amount of time, while I just want it to run once and exit.
I have tried the exit(0) command but I get an output that looks like this
START

This of the delta AVG reading: 0

This of t

As you can see, The program does not execute completely. Anyone have any idea how I can fix this, or anyhow I can better my code? thank you.

take all the code in ISR and move it into an if block inside loop() ... set a flag inside the ISR ... set the if block to execute when the flag is set

ISRs are time critical and should finish as fast  as possible. Yours is taking much too long. Look very critically at what MUST be done when an interrupt occurs and move all other code out of the ISR, especially all of the time consuming Serial.print() and the delay(). Let the main program handle the calculations and the output. The ISR only needs to do the measurements.

Forget about interrupts and read Blink Without Delay.

@StarCat it's even worse. delay and to some extent Serial.print require interrupts to work, but all interrupts are disabled while running your ISR code. So the code will just hang.

Why are you using a hardware timer for a long interval like 1 second? Why don't you just use millis() (or micros(), if you need more precision) to time the measurements? That would be way easier

As some of the comments have suggested, I would either get rid of the ISR or reduce the size significantly. When using ISRs, it is recommended that you keep the code as small as possible. Use it to set variables, for example
//these two variables are global
ISR(TIMER1_COMPA_vect){
    someValue = true;
    numberOfValues++;
}

you should also never use any Serial functions inside an ISR as these use interrupts themselves which can cause all kinds of problems
After using the ISR to update global variables, you can then use if() or while() statements within the loop() function to execute your serial print functions and such
P.S. on a side note, I would recommend changing your code where you calculated mean from
    mean = (add[1]+add[2]+add[3]+add[4]+add[5]+add[6]+add[7]+add[8]+add[9]+add[10]+
add[11]+add[12]+add[13]+add[14]+add[15]+add[16]+add[17]+add[18]+add[19]+add[20])/20;

to
for(uint8_t i = 1;i<=20;i++){
    mean += add[i];
}
mean /= 20;

Use cli(); to completely disable interrupt. Then use sei(); to re-enable the interrupt if you need it later.


text:
Hardware Serial connection for Arduino Mega 2560 NEO GY-GPSMV2 GPS module
My project is Vehicle Tracking System, One of my module is GPS module (Neo GY-GPSMV2). I can successfully see the GPS coordinates via Software Serial. But what I want is that my Arduino should not be connected to my laptop. So I should use Hardware Serial (correct me if I'm wrong). But I read some blogs that I should use resistors to avoid damage to m GPS module if I will use Hardware Serial. I searched for the wiring of it then I see this.  (Please remind that I'm using Mega so please just focus on the wiring). So I bought a 10k and 4.7k resistors. My question is how can I appl this on an actual wiring? should I split the wire? or what?

Most importantly, I want to point out that a Mega has 4 HardwareSerial ports: Serial, Serial1, Serial2 and Serial3.  There is no reason to use an inefficient software serial port library.  Software serial libraries use the processor to handle each bit transition, so they use much more CPU time.
SoftwareSerial is particularly inefficient, because it disables interrupts for the entire time that a character is being sent or received, and it can't do both at the same time.  This will interfere with your sketch or other libraries.  This answer lists the various serial port choices.
To answer your question:

... how can I apply this on an actual wiring? should I split the wire? or what?

Yes, 3 things get connected together at two places.  Most people use breadboards for prototyping.  Stick two wire ends (a "split" wire) and one end of a resistor into a common row of the breadboard, connecting them electrically.
But for a permanent solution, you should solder two separate wires and one end of the resistor together.  A small piece of perfboard can help secure the wires and discrete components.  It's a little kludgey, but you can strip the insulation from the middle of one piece of wire (don't split the wire) and solder one end of the resistor to it.
BTW, I always recommend real level-shifter modules that use FETs.  They're fast, so you can also use them for SPI interfaces, like an SD card, and they're bi-directional (5V to or from 3.3V).  And they're cheap.  You would just solder individual wires from the Arduino and the GPS device to various through holes in the module PCB.
The picture in your post shows a direct connection between the GPS transmit pin and the Arduino receive pin.  While this will not damage either pin, the GPS transmit voltage is not quite within the range specified for the Arduino receive pin.
Note the use of the word "specified".  If you read the specifications for the two devices, you will see that a logic 1 out of the GPS pin (called VOH) is slightly under the minimum acceptable voltage for the logic 1 input to an Arduino pin (called VIH).
You can also use discrete components to "step-up" the GPS TX voltage up a little.  You can google for many different solutions.  Hackaday has a nice summary.  MicroChip AppNote DS41285A has many suggestions.  Again, I would strongly suggest using a level-shifting module.
Many people report using a direct connection without problems.  It is possible that:

the actual devices have a higher VOH and/or lower VIH, or
the data is received with various amounts of errors, and the GPS parsing library (or sketch) ignores the errors.  Take a look at my NeoGPS library.  It is the fastest, smallest, most accurate and most reliable GPS library.  It can help you detect (and reject) bad data.

Great answer slash-dev. 5 Bi-Directional Logic Level Shifters for $1.18USD. https://www.aliexpress.com/item/5pcs-lot-5V-3V-IIC-UART-SPI-Four-Channel-Level-Converter-Module-for-Arduino-Free-Shipping/1821378018.html?spm=2114.search0104.3.37.RsrApE&ws_ab_test=searchweb0_0,searchweb201602_3_10152_10151_10065_10130_10068_10344_10547_10342_10343_10340_10548_10341_10084_10083_10139_10307_10059_10314_10534_100031_10604_10103_10142,searchweb201603_25,ppcSwitch_5&algo_expid=f05a8d79-9069-444a-b5e8-cf1361ee8656-5&algo_pvid=f05a8d79-9069-444a-b5e8-cf1361ee8656&transAbTest=ae803_4&priceBeautifyAB=0


text:
ERROR on SIM900AT comand HTTPDATA (POST method)
Good day community, I have a project which is VEHICLE GPS Tracker and I'm using Arduino Mega, NEO GPS6MV2 and SIM900. I'm using SIM900 to send the GPS coordinates on a web server. I'm using the POST method and SIM900 is capable of this by using AT commands. I will also save the coordinates on a MySQL database.
My problem here is I can't send the data on the MySQL database. As you can see on the latter part of the commands, it response "ERROR".  That's why the coordinates failed to enter on the database. This is what I have on the database: What do you think is the problem here?

Is there a 10 second delay between DOWNLOAD and ERROR?

If you say you are going to send 90 characters you must send 90 characters. No more, no less. I count 70 there.
You have to send them immediately the modem responds DOWNLOAD otherwise it times out (10 seconds) and you get ERROR. It looks to me like you're not sending anything (except maybe a blank line) for those 10 seconds and only trying to send once it has errored.


text:
WiFi101 Client HTTP POST fails after 3rd request
I would really appreciate any help, my home project has been put on hold for weeks as I haven't been able to figure this out. In a nutshell, I'm connecting to my wifi network, measuring temperature from a sensor, and sending that temperature data to a server via a HTTP Request. All of that stuff works.
I have it in a loop, and on the 3rd HTTP request I get 'Connection Failed' when it's trying to client.connect(server, 80) - I don't understand why it fails. I've tried adding client.stop() and client.flush() after each HTTP request, but nothing fixes it. Below is my sketch file with some of the temperature code removed to make it easier to read
#include <SPI.h>
#include <WiFi101.h>
#include <string.h>
#include <stdlib.h>
#include <OneWire.h>
#include <DallasTemperature.h>

//WiFi Client Setup
char ssid[] = "HIDDEN";    //  your network SSID (name)
char pass[] = "HIDDEN";       // your network password
int status = WL_IDLE_STATUS;    // the WiFi radio's status
char server[] = "HIDDEN";
WiFiClient client;

// Setup for temperature sensor
#define ONE_WIRE_BUS A5
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress insideThermometer;

void setup() {
  Serial.begin(9600);
  WiFi.setPins(8,2,A3,-1);
  while (!Serial) {
    Serial.println("Waiting for serial");
  }

  //Connect to wifi shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    while (true);
  }
  wifiConnect();
  sensors.begin();
}

void loop() {
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
  /*
  Code to get temperature here
  */
  httpRequest(temp);
  delay(10000); // 5min
}

void httpRequest(String temp) {
  String request = "POST /api/webhooks/temp?temperature=" + temp + " HTTP/1.1";

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connected to server");
    client.println(request);
    client.println("Authorization: Token HIDDEN");
    client.println("Host: HIDDEN");
    client.println("Connection: close");
    client.println();
  }
  else {
    Serial.println("Connection failed");
  }
}

void wifiConnect() {
  //Attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    delay(1000);
  }

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

I am so disappointed by the lack of support in arduino community, lack of good documentation, and poorly written hardware/libraries. Even the example sketches fail.

I tried changing the strings to char's, that didn't work.
Verified that it was closing connections with the server, check.
Was reading around and saw someone who tried a soft reset of the wifi client here. I added the following to the end of my httpRequest() method
client.stop();
WiFi.end();
delay(10);
WiFi.begin(ssid, pass);

And now it's working just fine. I'm going to have it run all night and see if there are any issues, but it's definitely an improvement as I can make more than 3 requests :|
This seems like a terrible work around. Clearly something isn't getting reset after each HTTP request on the wifi client, and this (right now) is the only way to solve it. I'd really love any other feedback on a better ways to solve it. Seems like some issues with the WiFi101 Library.

Are you still using this method?

I had the same issue. I can send consecutive requests, but if client.connect fails (e.g. timeout or whatever), then all subsequent requests fail. The only way of recovering is doing what you have done WiFi.end() + WiFi.begin(), in my case only after failure.
It happens with both WiFi101 and WiFiNINA (my project runs on both boards)


text:
How to send message from one embedded system to another embedded system like in cars, from one car to another?
I want to send message from one embedded system to another embedded system, like from one car to another without using phone number. just turn on the wifi.. connect and send message. There are ways to to send text to phone but not this kind of texting? Iam short of time. I only need to know what will be required to do this ? PLease help

If you want to communicate over WiFi, you need WiFi modules. And then you can use HTTP, TCP or UDP.

You can use ESP8266 modules( like Wemos d1) for wifi connections. The good thing about those are that they are also programmable and you can use arduino IDE to program. You can get two of those and make first one a server/host and second on a client for connection. There is more options of course: Bluetooth, RF link etc. Google "short distance connection arduino"

ESP8266 WiFi Module is a WiFi serial transceiver module, based on ESP8266 SoC. This chip implements a full TCP/IP protocol stack and the very interesting feature is that it has also a great computational power onboard. You can easily program it using Arduino IDE. You can buy this development boards in town market and its very low cost also.
Bluetooth/BLE4.0 Bluetooth is a type of wireless communication used to transmit voice and data at high speeds using radio waves. It is a standard protocol for short-range radio communications between many different types of embedded devices. Devices need to be within approximately 10 meters of each other, and the typical data transfer rate is around 2 megabits per second (Mbps).

These two are the most preferable for shorter distance communication.


text:
Does old/low charge battery affects internal clock?
Totally newbie in eletronics here, but could not find the answer for this one.
When a battery is nearly-exhausted, it's voltage and or amperage dims, right?
My question is if this kind of scenario (running low battery) would affect the arduino internal clock using only it.
I'm using arduino to a device that will operate remotely (with a 9V battery), and also logs intervals using the time function.
If battery is near-exhausted, then will this skew the numbers I get?

Microprocessor clock crystal frequencies can vary a few parts per million when microprocessor supply voltages vary significantly.  For example, a Czechoslovakian blog article (which was mentioned in avrfreaks.net and is shown in automatic-translated form at translate.google.com) shows a nearly-negligible drop of about 14 PPM as supply voltage for an Atmel ATtiny2313 rises from 2.4 V to 3.5 V or drops from 5 V to 3.5 V.  In the results, crystal frequency was about 4000000 Hz near 2.4 V and 5 V, and drops to 3999945 Hz near 3.5 V.
I refer to that 14 PPM frequency change as nearly negligible because typical inexpensive crystals have ±50 PPM or worse accuracy and stability specifications, and ±50 PPM or worse allowance over temperature changes of a few degrees, and somewhat larger allowances as the crystal's load capacitance varies by a few pF.  Thus, crystal frequency changes due to supply voltage changes are negligible compared to changes due to other causes.

Let's assume by "internal clock" you mean the internal oscillator, as the arduino's processor does not have a built-in real-time clock (something that is meant to keep track of real time like seconds/minutes/hours.)
The arduino is not like a motor where it runs slower if a lower voltage is applied. If the voltage goes too low, the arduino will just reset. Once it resets, the program running in it just starts over again, unless the battery voltage is so low it can't even start up.
If you're feeding it with a 9V battery, you're going through the 5V linear regulator on-board, which is not very energy efficient. Keep that in mind if your goal is to create a project that is meant to run a long time on the 9V battery. See the notes at http://www.gammon.com.au/power for tips on reducing the power used by an arduino and/or ATMega-based project.


text:
Mosquitto TLS over WifiMulti on ESP8266
With these few lines I am able to attach my certificate, tell it to WifiClientSecure the certificate, start the wifi as well as the mosquito pubsubclient:
WiFiClientSecure espClient;
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}

PubSubClient mqtt_client(espClient);
mqtt_client.setServer(mqtt_server, 8883);
mqtt_client.setCallback(mqtt_callback);
espClient.setCertificate(ca_crt, ca_crt_len);

if (!mqtt_client.connected()) {
  mqtt_reconnect();
}

mqtt_client.loop();

With these lines I am able to connect to wifi, depending on which the closest station is:
ESP8266WiFiMulti wifiMulti;

wifiMulti.addAP("primary-network-name", "pass-to-primary-network");
wifiMulti.addAP("secondary-network-name", "pass-to-secondary-network");
wifiMulti.addAP("tertiary-network-name", "pass-to-tertiary-network");

wifiMulti.run();

How can I combine both? I.e, I am interested in sending data to secure MQTT over a set of possible wifi networks?

The WiFiMulti has nothing to to with the MQTT and TLS side of things at all.  It only has anything to do with the WiFi.  As such it just replaces the code that directly interfaces with the WiFi.
That is, this code:
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}

is replaced by this in the global scope:
ESP8266WiFiMulti wifiMulti;

This in setup():
wifiMulti.addAP("primary-network-name", "pass-to-primary-network");
wifiMulti.addAP("secondary-network-name", "pass-to-secondary-network");
wifiMulti.addAP("tertiary-network-name", "pass-to-tertiary-network");

and this in loop():
wifiMulti.run();

All the MQTT side of things remains exactly the same.

Thanks for the answer. How can I tell the wifiMulti (or anything else in case it is not wifiMulti) my certificate? What I mean is the espClient.setCertificate(ca_crt, ca_crt_len); line in the question above :-) Or does that part stay as it is?

You don't tell the WiFi. You tell the client. That's completely separate to the WiFi.

Follow up on the answer from @Majenko.
#include <WiFiClientSecure.h>
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
WiFiClientSecure espClient;

#include <PubSubClient.h>
PubSubClient mqtt_client(espClient);

Serial.println("setup_wifi_multi_addAP()");
wifiMulti.addAP("ap1", "pass1");
wifiMulti.addAP("ap2", "pass2");
wifiMulti.addAP("ap3",  "pass3");

while (wifiMulti.run() != WL_CONNECTED)
{
  Serial.print(".");
  delay(500);
}

Serial.printf(" connected to %s\n", WiFi.SSID().c_str());

mqtt_client.setServer(mqtt_server, 8883);
mqtt_client.setCallback(mqtt_callback);
espClient.setCertificate(ca_crt, ca_crt_len);

if (!mqtt_client.connected()) {
  mqtt_reconnect();
}
mqtt_client.loop();

void mqtt_reconnect() {
  Serial.println("mqtt_reconnect()");
  // Loop until we're reconnected
  while (!mqtt_client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (mqtt_client.connect("ESP8266mqtt_client-1")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(mqtt_client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

If you are using only secure connection without require_certificate in mosquitto configurattion just change
espClient.setCertificate(ca_crt, ca_crt_len);
to
espClient.setCACert(ca_crt, ca_crt_len);
setCertiticate is used mainly to mutual authentication.


text:
How to control speed of 28BYJ-48 stepper motor without using library?
Iam using 28byj-48 stepper motor and I want to know how to control its speed without using any library. I got to know that we need to add delays in between steps but I don't know how much delay I need to add and how delay effects the rpm. It is very much helpful if anyone suggest me how to do this.

start by examining the blinkWithoutDelay example sketch that is included with the Arduino IDE ... it will teach you how to execute events at intervals without blocking the rest of the code

A stepper motor always needs a driver. As the ULN2003 (or similar) driver is normally shipped together with the 28byj-48 motor, I will assume, that you have this driver.
The ULN2003 has 6 pins:

Vcc and ground need to be connected to your power source. Note, that it is risky to connect Vcc to the 5V pin of the Arduino. While that might work, when there is no load on the motor, a loaded stepper motor can draw rather high currents. Letting these current run through the Arduino might fry the voltage regulator or the power switching diode. High currents should always flow past the Arduino, not through it.

The other 4 pins (which are marked as IN1 to IN4 on my ULN2003 driver board) are for controlling the phases. You need to connect these 4 pins to 4 individual digital outputs on your Arduino. As these are the phases of the stepper motor, you need to activate them in the correct order. You have this pattern
  1000
  0100
  0010
  0001

for full steps, and this pattern
  1000
  1100
  0100
  0110
  0010
  0011
  0001
  1001

for half steps. Each digit of each number represents the status of the corresponding phase; 1 means activated/HIGH, 0 means deactivated/LOW. To move the stepper motor forward, you move in the list of phases down. To move backwards, you move up in the list.

When using a stepper motor, the speed is determined by the number of steps per time interval. Let's assume, we want to use delay(), which is really easy, though not recommended (see explanation below), we can do steps and delay() inbetween:
void loop(){
    step();
    delay(10);
}

This code would do a step and then delay for 10ms. Thus we have about 1 step every 10ms. With 64*64=4096 steps per revolution (the motor itself seems to have 64 steps; additionally there is a gear with ratio 64 mounted on it; this might be different for you) we get a full revolution every 4.096s. When you use half the delay(), the speed will be double: with 5ms delay we get a full rotation every 2.048s. So you can use the delay() to set the speed of the motor.
Now we need the step() function, that I used above. There are multiple ways of writing this in code. I would propose to put the pins and phases into arrays and iterate through them with a static variable, which holds the current position in our phase pattern. Something like this:
//in global scope defining the pins for the phases
int stepper_pins[4] = {2, 3, 4, 5};

void step(bool forward){
    const uint8_t phase_pattern[][4] = {
        {1,0,0,0},
        {0,1,0,0},
        ...
    };
    static uint8_t current_step = 0;
    if(forward){
        current_step = (current_step + 1) % 4;
    } else {
        current_step = (current_step - 1) % 4;
    }
    for(uint8_t i=0;i<4;i++){
        digitalWrite(stepper_pins[i], phase_pattern[current_step][i]);
    }
}

We hold the phase pattern in a 2-dimensional array. The variable current_step is declared static, so it will keeps its value between the executions of the function. Then - depending on the parameter forward - we increment or decrement the current step and take that value modulo 4 (the number of phase patterns). That ensures, that current_step stays in the index range of our phase pattern array and will wrap around from the end of the pattern to the start and vice versa. After that, we loop through the 4 stepper pins and set them according to the current element in the phase_pattern array. You can easily adept that code for half steps.
Note, that this code is totally untested. Also this can be reached with way less code (at least for full steps), but I think this code is better understandable.
Now: Why not using delay()? This function will block the execution of other code. In that time the Arduino is just fiddling thumbs. In general that is considered bad practice. It is good, when you only need that one functionality and no responsiveness. But lets assume, you want to add a button, so that the motor reacts to your button presses. Long delay() calls will impact the responsiveness of your code. So instead you could use a non-blocking coding style. In the Arduino world this is easily done with the millis() function, which returns the number of milliseconds since startup and thus acts like a clock. Refer to the BlinkWithoutDelay example, that comes with the Arduino IDE, and to the many tutorials on the web, that you can find with search terms like "Arduino millis tutorial" or something like that.

EDIT:

how your code controlling the motor speed?

The delay() call is determining the motor speed. If you want to change the speed, you need to change the value of the delay. You didn't mention any input device, so I just leave the speed constant. But of course you can define a variable for the delay and change that delay based on some input device. How exactly that is done depends on your requirements, mainly what type of input you want to use.

if we didn't specify any delays in between steps, will it spin at its max rpm?

When you don't use any delay, then most likely your code will run too fast for the motor. The driver will set the motor phases very very fast. So fast, that the motor cannot follow that (because it has a specific inertia). (Much like the wheels of your car can loose the grip on the street and spin without moving the car, the stator of the motor can loose the magnetic grip on the rotor, which leads to further rotating phases, but a rotor, that is standing still) So you reach the maximum speed before that and it depends on the motor, the driver, how much load is on the motors and how much current your power source can give you (I once tried to provide 3 of these motors with a 1A power supply, but they moved very weak, until I upgraded to a bigger power supply, that can provide about 5A, I think). You need to test yourself, how fast you can drive your motors. So try to lower the delays step by step, until the motor cannot move in your setup anymore. Then you have the minimum delay, and the maximum speed.
Note: The delay() function won't be accurate for very low delays in the single digit milliseconds. In that case you might wanna use delayMicroseconds(), which is more accurate in that range and also can get in you in the microsecond range.

Your explanation is wonderful,but how your code controlling the motor speed

And one more question,if we didn't specify any delays in between steps, will it spin at its max rpm?

@Akashbabutammali I added explanations for both questions in my answer.