text:
Is it possible to do an OTA update using a GitHub link
I need to be able to download software updates through the internet without having my MKR1000 plugged in. Either that or have new code being pushed from my server (C++) to my MKR1000, and then rebooting with the new code.
Any help is useful.
Thanks.

you could use the InternalStorage object of the WiFi101OTA library to store and apply the downloaded binary

Well the goal is that i can have some MKRs spread out through the province and not have to touch them ever again, and be able to update them as necessary so the internal storage is a no-go.

it is called InternalStorage  because it stores the uploaded or downloaded binary to upper half of the flash memory. after successful upload you call apply() and it copies the binary to the run location and resets the board. new sketch is running

It may be possible if you can write your own bootloader, but it certainly won't be easy.
The normal way of doing OTA updates is to use a chip that has segmentable and remappable flash memory (such as the ESP32, ESP8266, PIC32MZ, etc) where your sketch is running from one segment, and that loads the new code from whatever source into the other segment. It then changes a single boot flag and resets the MCU, and the MCU then maps the second segment into the place of the first (swaps the two segments over) and runs the new code.
That can't be done with the SAMD21 since it has no remappable flash memory segments.
So the best you could hope for would be to reboot into a custom bootloader which then connects to the internet to download new code to flash into the main portion of the flash memory. And of course that would replace the existing bootloader and take a lot of work to create.

Addendum:
Apparently there is the "WiFi101OTA" library which allows over-the-air updates on SAMD21 boards. By all accounts this receives the new code and stores it away somewhere (a chunk of the internal flash, SD card, etc) and then copies that data to the main portion of the flash using a function running from RAM.
While this sounds good, I would not recommend using it in a live situation. For development it's fine, but not "in the field".
This is simply because there is no protection against "bricking" a unit.  Once the copy from storage to main flash starts you are at the point of never being able to go back. If that write should fail for whatever reason (there is a power outage, or the sketch crashes, or any of a myriad of other unpredictable reasons) the unit is dead.  You would have to manually reprogram the unit with a cable to bring it back to life.
By having the programming done by the bootloader (incidentally, some devices, such as AVR based boards, can only write to flash from the bootloader) the code that does the writing never gets overwritten, so a simple manual reset of the unit can restart the programming and recover the board.
If you were to adopt this library you would of course have to modify it to "pull" the update, not receive a "pushed" update. This should be trivial, but some level of network programming ability would be needed.

but the WiFi101OTA library does it. with a function in RAM, which copies the binary stored in upper part of the flash to the target location in flash. and I enhanced this library to other networking libraries and other MCU (nrf5, AVR) in the ArduinoOTA library

@Juraj I was not aware of such a library. Oh, and how does that work with AVR which can only write to flash from the bootloader segment?

@Juraj Also, that method is unsafe. If you start overwriting the code that is doing the programming and there is a crash or power outage the unit is bricked. With dual flash segments that can never happen since the switching of segments only happens once it's been verified the code is all written. That's why you'd want to do it from the bootloader not the main sketch, so it is possible to recover after a crash when running an ota update.

it doesn't brick the board. bootloader is not changed. if OTA fails, USB upload is possible. AVR ArduinoOTA needs enhanced Optiboot: https://github.com/jandrassy/ArduinoOTA#atmega-support

@Juraj "Bricked" means you have to manually re-upload the code through USB - something you don't want to be doing in the field. I would certainly never want to use such a thing in a live system. Anything that doesn't either use dual segment flash, or a bootloader that does the OTA work for you, is unsafe in a real environment. Development, fine. Live, hell no!

the bin is saved to the upper half of the flash and after sucessfull upload it is copied to the run location. there are not many reasons why a flash to flash copy should fail once it started. but yes it is "arduino" level, not professional level. I use it every day and if I have a problem, it is because I made a change which doesn't allow the sketch and OTA server run. but my M0 is only downstairs


text:
Increasing speed of Vl6180x Sensors
I have 5x vl6180x pololu ToF sensors. I have managed to hook up all of the sensors to the arduino via I2C by making each sensor startup at different times and when they do, changing their addresses, but while I can quite easily read them, they take a very long time, 50ms - 300ms. I'm using the Pololu VL6180x library and when I've investigated the library, I couldn't find any delays in the code. I have also tried to change the clock rate of I2C to 400kHz, but that didn't seem to affect the speed. The datasheet of the sensors says that a sensor might take ~63ms to respond, but is there any way to make it faster? If not, can I read the sensors with the AtTiny13A and send the data from each chip to arduino? Which protocol should i use to communicate with them, if i want to read their measured distance?
Ps. I'm making a robot which needs to move fast and react quickly to each sensor. (11 of sensors in total, none, except ToF are I2C)

You can use startRangeContinuous and readRangeContinuous to have the sensor continuously measuring the distance, negating the need to wait for the sensor to do a measurement.
Using readRangeSingle will start a single measurement, and this function will just sit there waiting for the measurement to be done, after which it will return the result.

Well, i have just tried it out, it seems that the sensors speed barely changes(remains ~60ms when it doesn't see anything and ~20ms when it does) and it keeps crashing every 5 seconds, stopping me from reading it more.

@PotatoMan Maybe it's crashing because 400kHz is too fast for your setup. Is it on a breadboard? Those usually have a relatively high capacitance. If that's the case you could try to decrease your pullup's resistance.

@SimSon I'm doing it all on a breadboard and tried it out with 10kHz to no avail, but nevertheless i can get a few raw readings and i can see, that, when reading those values, the timing still stays around 10ms - 60ms..

Without seeing the code, I can't really help.

source: Stack Exchange

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

sort: votes


text:
ESP32 - SIM800 - HTTPS lwIP
I am using ESP32 and SIM800L for my project. The SIM800L does support SSL, TLS 1.0, and TLS 1.1. But web servers nowadays usually support only TLS 1.2 and 1.3. I heard, that the ESP32 HTTPS client can use lwIP stack from other libraries. Is there some way to implement the lwIP? Is there some other way to get TLS 1.2 and 1.3 working?

it is not possible to make SIM800 work with LwIP.

@Juraj And is there any other way to get TLS 1.2 and 1.3 work on SIM800L?

Some, but not all, versions of the SIM800 support SSL. Having SSL support depends on the firmware version and the individual module. Users have had varying levels of success in using SSL on the SIM800 even with apparently identical firmware. If you need SSL and it does not appear to be working on your SIM800, try a different module or get a newer SIMCOM module than SIM800(they are really old that no longer in prouduction).

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


text:
How can I hack my intercom system to buzz people in remotely?
How would you go about activating this button remotely?
This board is from the intercom in my apartment. The button when pressed unlocks the building door. I've just ordered the MKR IoT bundle (https://store.arduino.cc/arduino-iot-mkr1000-bundle). My plan is to learn the basics and figure out how to activate this button remotely.

Check, how the button is connected on the board, if you can. Check, if there is any electrical load is connected to it (which would need a specific current to flow at minimum). Check, which voltage the system and especially the microcontroller use. Then maybe you can use a transistor (or relay for heavy load) to bridge the button depending on a voltage, that can be controlled by your MKR (note that it runs on 3.3V). Do your research and then edit your question to more precisely state the problem.

Agreed.  Please take the http://www.arduino.stackexchange.com/Tour to see how to format a question.  You are welcome here but we'll need more information in order to be able to help.

use a relay module; it's the safest simplest most compatible way.

3 possible solutions:

Connect the 2 contact for the button to a relay and control that relay from the arduino (example) But the kit you have doesn't include a relay.
Use a transistor to trigger the switch -- I would not recommend this option as your first project.  It would be easy to damage the intercom and/or your arduino.
Use the servo in the kit to physically press the button.  You will need to figure out the mechanical linkages but you don't need to attach wires to the intercom.

For a beginner project I would probably go with the third option.

Use an optocoupler. It isolates the Arduino, just like the relay does, but doesn’t require as much power as the relay (and doesn’t make any noise).

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


text:
Is it safe to power Arduino project using a power bank and wall charger?
I got an Arduino project that need a constant source of power. Rather than dealing with batteries, I want to use a power bank like this:

Better yet, I want to keep the power bank plugged in to the wall outlet using a wall charger like this:

The USB wire coming out of the power bank, I can modify it and connect it to the 5V on the Arduino (Pro Mini 5V version). Is it safe to do so? The application uses a stepper motor that draws around 200mA and only runs intermittently.
Thanks

you will possibly kill your power bank faster, unless it has a pass thru circuit (does not discharge while plugged in and fully charged).  i keep my rural Arduino PWS (weather station) powered like this all the time, because we have power outages on an almost daily basis.

what’s the load? is it enough to drop voltage and confuse your charge controller? if yes, it becomes a fire hazard. the USB battery needs to output 5V when plugged in, and mustn’t discharge the batteries to do this. use your multimeter to discover the truth!

Yes you can.  A promini will run very well on 5V from a wallwart.  Connect 5V to VCC (not RAW or VIN).  You can also find wallwarts with 2.1mm/5.5mm plugs, and a mating barrel jack adapter that ends in screw terminals so you don't have to try hacking up a USB cable.
Power bank, you will have to play games to convince it that something is connected and drawing sufficient current to keep it turned on.
Wallwart example  https://www.mpja.com/5-Volt-DC-Plug-Power-Supply-4A-Regulated/productinfo/18520+PS/
Barrel jack to screw terminal adapter example  https://www.mpja.com/55_21mm-Power-Jack-Screw-Terminals/productinfo/19454+PL/

Yes, that is my standard setup for Arduino and Raspberry Pi.


text:
Arduino DUE and 5V logic sensor?
For an application I use Arduino DUE and VNH2SP30 as the motor driver.I think this motor drive is only compatible with 5V logic but DUE provide 3.3V logic.Will my problem be solved if I use logic level shifter to convert 3.3V logic level to 5V?In the meantime, I control the speed and direction of the motor with the following code:
analogWrite(PWM_kare,head_analog);
digitalWrite(INB_kare, HIGH);
digitalWrite(INA_kare, LOW);

According to the datasheet (page 5) the "Input High Level Voltage" is 3.25V.  That means that any voltage over 3.25V will count as a HIGH.
That is kind of borderline for 3.3V logic which can drop below 3.3V for a HIGH depending on load and other circumstances.
So while it might work off 3.3V I would say for reliable operation you should use some form of level shifting in your circuit, yes.
A simple, cheap, MOSFET-based logic level shifter will do the job - there is no need for anything fancy.


text:
Strange things happening with Arduino PROGMEM
I am currently working on a display library. The font should be stored in PROGMEM. The code looks something like this:
unsigned int i = 0;
Serial.println(pgm_read_byte(&font[1]),HEX);
unsigned char width = pgm_read_byte(&font[0]);
unsigned char height = pgm_read_byte(&font[1]);
unsigned char spacing = pgm_read_byte(&font[2]);

The strange thing is that the code breaks (Serial spits out random characters, OLED displays only noise or nothing) when I remove the
Serial.println(pgm_read_byte(&font[1]),HEX);

If I replace it with something like
Serial.println("Hello World!");

the code breaks as well, but in a different way. I think pgm_read_byte() returns different things with different Strings in the Serial.println() function.
Is there something going on with the compiler? Are there some optimization options that I should change? Or am I doing it completely wrong?
Here is the whole function:
/**
 *
 * Displays text using a predefined sprite in PROGMEM
 * Only fonts with a uniform letter spacing are supported
 * The font must have the following format
 * Byte   Description
 *  0.    X width of one letter in pixel
 *  1.    Y height of one letter in bytes (8 pixel)
 *  2.    letter spacing in pixels
 *  3.    data
 *  .      .
 *  .      .
 *  .      .
 *  N.    data
 *
 * The data is arranged like this
 *    | 0 | 1 | 2 | 3 | 4 | ... |126|127
 *     b0  b1  b2
 *     b3  b4  b5
 *    LSB D0
 * In each byte the data is displayed like this
 *    .
 *    .
 *    .
 *    MSB D7
 *
 * A font starts with the symbol "!" (ASCII 33) and ends with the symbol "~" (ASCII 126).
 * Each symbol in between has to be present. The letters have to be arranged like this
 * Letter     A       B       C
 * Bytes    b0 b1   b2 b3   b4 b5
 *          b6 b7   b8 b9  b10 b11
 *
 * @param unsigned char disp[]          the display buffer where the text should be shown
 * @param const unsigned char font[]    the font in PROGMEM
 * @param const char *string            the string to display
 * @param unsigned char X               x location
 * @param unsigned char Y               y location
 * @param int mode                      blend mode
 */
void gfx::text(unsigned char disp[], unsigned char *font, const char *string, unsigned char X, unsigned char Y, int mode){
  unsigned int i = 0;
  Serial.println(pgm_read_byte(&font[1]),HEX);
  unsigned char width = pgm_read_byte(&font[0]);
  unsigned char height = pgm_read_byte(&font[1]);
  unsigned char spacing = pgm_read_byte(&font[2]);
  while(string[i])
  {
    if(string[i] > 32 && string[i] < 127){  //only display valid characters, otherwise leave a blank spot
      unsigned char s[width*height];
      unsigned char c = string[i] - 33;
      //transfer pixel with and height to the sprite
      s[0] = width;
      s[1] = height;
      //copy the other bytes
      for(int y = 0; y < height; y++){
        for(int x = 0; x < width; x++){
          unsigned int sprite_pointer = 2 + width*y + x;
          unsigned int font_pointer = 3 + c*width + x + y*width*93;
          s[sprite_pointer] = pgm_read_byte(&font[font_pointer]);
        }
      }
      sprite(disp,s,X+i*(width + spacing),Y,mode);
    }
    i++;
  }
}

I am also having issues with PROGMEM. I can't use forloops to iterate through and print a PROGMEM'd array, it just spits out garbage. I have to go character by character using constants.

The problem is probably not in the code you show, but in some weird interaction with other parts of your program. Please, post a Minimal, Complete, and Verifiable example isolating the problem.

Why compute unsigned int sprite_pointer = 2 + width*y + x;? The array s only has width*height entries, when the for loop goes at the maximum values of x and y, this index will be out-of-bounds. You need 2 bytes more in the s array. What's the size of the font you're passing it?

If this is code from a 3rd party library I would find another library.  If its your code, you need to look at simplifying the function so you can see why it doesn't work.  If anything goes wrong in the code you program will splat stuff everywhere, If its internet connected you could start a world war :)  What does 93 mean?

Maximilian Gerhardt was right. The array had only (witdh*height) but I wrote
(width*height+2) in it. So something else got overwritten and nothing worked. Thanks a lot!


text:
How do you convert PCM to PWM?
I'm a beginner and I've been developing my own library for a wave player. so far I have the SD card installed and OLED and rotary encoder all connected. I've successfully read the wave chunk and it's data(16bit and 44.1KHz). My question is that the data in wave file is PCM and I wish to play is using 16bit PWM and so how do I convert PCM to PWM?

http://playground.arduino.cc/Code/PCMAudio

An Arduino is not an audio player. It won't have enough processing power and/or memry for running an SD card, refreshing an OLED display and playing audio. Use specialized hardware and a decent DAC for audio playback.

Or go the cheap route and use an LC filter. This video has good info on both DACs (R2R-style) and PWM+Filter "DACs": https://www.youtube.com/watch?v=Y2OPnrgb0pY What's your speaker system? You might need another OpAmp or audio amplifier.

tttapa, I've seen a lot of tutorials online. Maybe if I remove the OLED display it might be able to run it but I'm just curious and I want to get to the end of it even if the output isn't want I desire.

Maximilian Gerhardt, LC filter makes sense after I've generated PWM signal. My whole problem is that I'm not able to do that. I just don't know what the interface between PCM WAVE file and PWM is.

There is no such thing as a PCM file. PCM is completely erroneously used to describe an uncompressed digital audio file. What it actually means is "A file which contains data that can be fed directly to a PCM device without any form of intermediate conversion".
What you have in a "PCM" WAV file is just raw sample data. After your header (usually 44 bytes) you just have 16-bit values representing your sample points, with the two channels interleaved one after the other.
Since PCM is a linear audio representation, the sample data it expects is a simple linear representation of the audio (unlike µLaw or A-law) and with no compression (such as MP3 or FLAC). And that is the exact same data that PWM expects since it too is a simple linear output.
However, none of that matters, because the Arduino simply isn't powerful enough to play your file. Maybe a smaller one (8kHz, mono, 8-bit) would be playable, but not yours. The numbers just don't add up.
There is a PCMAudio example available, but it only works from audio embedded within your program.
There is also a TMRpcm library available which plays from SD card, but is limited to 8-bit mono, though it can supposedly do up to 32kHz sample rate (though I wouldn't want to try doing anything else at all at that rate).
You would be better off using a system more geared towards audio - something with an I2S CODEC chip attached would be the best solution.

Thanks for replying early. Well I was thinking if we can use 16bit PWM for audio output at 44KHz timer interrupt. And to compensate for the low memory holding capacity of the Arduino we can use double buffering from an SD card.
OR
Adding an external 16bit DAC IC would reduce the complexity because then maybe I don't have to worry about PWM? (I'm not sure about this part.)

See my answer below. PCM can most certainly be converted to PWM and played on  most MCUs.

You should use an MCU with PWM generators to do that.
The problem with PWM is that the max resolution is quite low (10-bit) so you are effectively limited to 8-bit PCM.

Use a DSP editor like Audacity to export a 16KHz unsigned 8-bit WAV.
Import the WAV file as an array of unsigned char.
Set your PWM freq to the resonant freq of your speaker (eg. 31250Hz)
Set your PWM timer to fire at 16KHz and set the PWM duty cycle to the next array value.

I use 16KHz sample rate because:

Reduced memory footprint
Fewer timer interrupts
PWM's limited resolution does not seem to benefit from anything above 16KHz
I use piezo speakers directly wired to PWM pins in H-bridge.
A separate amp module might benefit from higher sample rates.

Comments have been moved to chat; please do not continue the discussion here. Before posting a comment below this one, please review the purposes of comments. Comments that do not request clarification or suggest improvements usually belong as an answer, on [meta], or in [chat]. Comments continuing discussion may be removed.


text:
Tinkercad but offline?
I have some issues with network and would like to work with arduino everywhere. I use Tinkercad which is great, but I would like to installit to my laptop and work without using WiFi. I couldn't find any "offline tinkercad" but maybe there are any similar programs where you can program AND write code inside.

I never use such things, but I seem to have an idea that Proteus may be what you want?

Nah I want arduino, I am  a beginer and Proteus is a bit  complicated

The only thing you can get that is Arduino is the IDE.

do you need the hardware sim of tinkercad, or just the ability to run code?

I want to connect everything to an arduino just like in tinkercad, without using an actual arduino. I do have the Arduino IDE, but there (for what I know) I can only write code, which I can't test without using Arduino

The best replacement (but keep in mind that Tinkercad is prob the best for code AND hardware sim) would be Yenka. They offer a "block style" language but you can go in depth with the hardware more than most programs.
Here is a ref image:

is the block style optional, 'cause i want to write code by myself?

i don't think so sadly


text:
How do I move more than 128 pixels when using Arduino Leonardo's Mouse.move?
How do I move more than 128 pixels when using Arduino Leonardo's Mouse.move?
Is it possible to modify the header file or use a different library?
I used the MouseTo library, but it wasn't the move I wanted.
We want to move as fast as possible to the relative coordinates, not as one pixel.
I've searched almost every community, but I haven't.
Give them a hand.

The USB HID protocol for mouse is the limitation on sending more then a byte sized value for the mouse movement in one event.
You can't create a faster USB mouse. Repeat the call of the move() function. Of course you can use a function to call move() repeatedly to move to target destination.
void mouseMove(long x, long y) {
  long max = max(abs(x), abs(y));
  int count = (int) (max / 127);
  signed char stepX = x / (count + 1);
  signed char stepY = y / (count + 1);
  for (int i = 0; i < count; i++) {
    Mouse.move(stepX, stepY);
  }
  signed char resX = x - (stepX * count);
  signed char resY = y - (stepY * count);
  if (resX != 0 || resY != 0) {
    Mouse.move(resX, resY);
  }
}

There were times when the exact value was not available when I called multiple times. Anyway, thank you for your answer.

For X and Y values between -64 and 64, consider multiplying the X and Y values you are passing to the method mouse.move() by 2.  In the above linked page, the example call to mouse.move() looks like this:

mouse.move(xVal, yVal, wheel)

Consider writing it like this for twice the change in either direction:

mouse.move((2 * xVal), (2 * yVal), wheel)

For values less then -128 or greater than 128, consider calling the method multiple times instead of once for each time it is desired to move the mouse.
A more difficult approach: You may also consider re-writing or adding to the Arduino mouse driver.  It appears the Arduino mouse driver is located here.  As this is C++ you will need to change the definition of the "mouse" method as well as how you handle int as opposed to char sized variables.  In this case you can take advantage of the C++ Method Overloading feature.  That is, you can have 2 methods of the same name with different parameter types.  C++ will treat them as two individual methods.  So the original mouse.move method can remain untouched.  While the new mouse.move method will be able to handle type singed int instead of type singed char values.

Wouldn't the multiplying approach let the parameters overflow? The explanation after that seems better to me, calling the method multiple times or changing the library.

what? the unsigned chars (-127 to 127) are defined in the HID event. how would you reimplement that?

I see. Your answer was helpful to me even if it was not possible.

@juraj, If the HID definition limit mouse movement the library can abstract this from the Arduino sketch by sending multiple HID commands should the value passed to the library be larger than allowed by the HID interface.  So a library call using ints instead of chars can still be created.

@chrisl, yes, I'll rephrase the answer.


text:
Is there a digital/ultrasonic Anemometer for Arduino?
I use Arduino DUE and I noticed that many forum users use the TX-23U Wind Sensor.
https://www.amazon.com/Crosse-Technology-TX-23U-Weather-Stations/dp/B0016MYA7U
Also, many people tried to create a DIY ultrasonic anemometer like this;
https://soldernerd.com/category/arduino-ultrasonic-anemometer/
Instead of using the DIY ultrasonic anemometer, I wanted to purchase one but I couldn't find one.
Is there an ultrasonic anemometer which I can purchase and connect it with my Arduino DUE?
3.3V power, non-mechanical rotation, I2C/SPI/UART support are the requirements. Thanks.

When I googled "ultrasonic anemometer" I found various suppliers, though I don't know, if these comply to your specifications or how expensive they are. Have you looked through the google results? I would think, that an ultrasonic anemometer is somewhat niche and this site is not meant for product recommendation, so you might not get a good answer here.

Frame challenge: pick a sensor that complies with your needs and specification - especially the performance characteristics you're interested in, e.g. range of wind speed to measure, required accuracy and resolution, response time and data acquisition rate, to name just a few. Don't look for something specific to Arduinos to not unnecessarily narrowing down your options. Then design or adapt an appropriate interface to make them both work together.
Common interfaces of "industrial grade" ultrasonic anemometers (e.g. 1 and 2) are RS232/RS422/485, so technically UART, though in need of level shifters or a RS-485/RS-422 transceiver, e.g. Maxim. Some also offer analogue output that might be feed into an Arduino's analogue in after matching voltage levels.
I would assume that I2C/SPI are rather uncommon as these are for short-distance, intra-board communication not for connecting a separate sensor module.
The same thought applies to the power supply, I recommend to drop the requirement of powering the sensor with 3V3 put rather select a power supply for a sensor available and affordable. The anemometers available at the linked vendors typically list a supply voltage of 5-30VDC or 6-24VDC.

You can see this one: SONIC-ANEMO-MICRO
https://lcjcapteurs.com/en/girouette-anemometres-capteur-vent/sa-micro-2/


text:
MKR1010 serial communication
Is communication using tx/rx from an arduino to mkr1010 the same as any other serial communication?
I ask because I can't find any tutorials or info on connecting an arduino to mkr1010, but there are plenty on connecting one arduino to another.

it has Serial1 on RX/TX pins

Though you need level shifting, since the Mega is a 5V device, while the MKR1010 works with 3.3V and cannot tolerate 5V on it's pins. The UART pins are only unidirectional, so it should be sufficient to put a voltage divider between Arduino TX and MKR1010 RX.


text:
Stop getting values from arduino after some time
I have a strange problem, I have Arduino UNO/MEGA and I need to get Gyro sensors's data and I want to see the data in the serial monitor. Seems like a simple task, I wrote a simple C program which collects data from Arduino through serial monitor I can see the data. Everything is working for few minutes and after that, it stops.
#include <Wire.h>
#include <MPU6050.h>
#include <Encoder.h>

MPU6050 mpu;
Encoder myEnc(11, 12);

long newP=0, newPosition=0, newPo=0, oldPo=0;//Encoder values

unsigned long currentTime, previousTime, elapsedTime;
double error, lastError, output, setPoint, cumError, rateError, kp=40, ki=0, kd=0;
// Timers
unsigned long timer = 0,timera=0;
float timeStep = 0.01;
//Yaw values
static double yaw = 0;

const int motor11=6;//LEFT MOTOR FW
const int motor12=7;//LEFT MOTOR BK
const int motor1pwm=3;
const int motor21=8;//RIGHT MOTOR FW
const int motor22=9;//RIGHT MOTOR BK
const int motor2pwm=5;

int thres1=120;//PWM Values
int thres2=120;

int flag1=0, flag2=0, flag3=0, flag4=1, flag5=0;

int x=0, y=0, save=0;

void setup()
{
    Serial.begin(115200);
    // Initialize MPU6050
    while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
    {
      Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
      delay(500);
    }
    mpu.calibrateGyro();
    mpu.setThreshold(1);

    pinMode(motor11, OUTPUT);
    pinMode(motor12, OUTPUT);
    pinMode(motor21, OUTPUT);
    pinMode(motor22, OUTPUT);
    pinMode(motor1pwm, OUTPUT);
    pinMode(motor2pwm, OUTPUT);
}

void loop()
{
    newP = myEnc.read()/4;
    newPo=newP-newPosition;
    Serial.print("Encoder ");
    Serial.println(newPo);

    Vector norm = mpu.readNormalizeGyro();
    yaw = yaw + norm.ZAxis * timeStep;

    if(abs(newPo)<=600) //Straight line motion
    {
        if(abs(newPo)%60==0)
        {
          if(flag3==0)//Increase x- coordinate
          {
            if(save<abs(newPo))
            {
              if(abs(newPo)>abs(oldPo))
              {
                x=x+1;
                Serial.print("X= ");
                Serial.println(x);
                Serial.print("Y= ");
                Serial.println(y);
                if(x==10)
                {
                  flag3=-1;
                }
                save=abs(newPo);
              }
              else if(abs(newPo)<=abs(oldPo))
              {
                save=abs(oldPo);
              }
           }
         }

          else if(flag4==0)//Decrease x-coordinate
          {
            if(save<abs(newPo))
            {
              if(abs(newPo)>abs(oldPo))
              {
                x=x-1;
                Serial.print("X= ");
                Serial.println(x);
                Serial.print("Y= ");
                Serial.println(y);
                if(x==0)
                {
                  flag4=1;
                }
                save=abs(newPo);
              }
              else if(abs(newPo)<=abs(oldPo))
              {
                save=abs(oldPo);
              }
            }
          }
        }

      if(flag1==0)//Set Point
      {
        setPoint=yaw;
        Serial.print("Set Point= ");
        Serial.println(setPoint);
        flag1=-1;
      }

      if(flag2==0)//slow start
      {
          digitalWrite(motor21, HIGH);
          digitalWrite(motor22, LOW);
          analogWrite(motor2pwm, 75);
          digitalWrite(motor11, HIGH);
          digitalWrite(motor12, LOW);
          analogWrite(motor1pwm, 75);
          delay(500);
          flag2=-1;
      }

      timer = millis();
      currentTime = millis();
      elapsedTime = currentTime - previousTime;
      error = setPoint - yaw;
      cumError = cumError+(error * elapsedTime);
      rateError = (error - lastError)/elapsedTime;
      output = kp*error+ki*cumError+kd*rateError;
      lastError = error;
      previousTime = currentTime;

      if(error>0.001)
      {
        Serial.print("1. YAW= ");
        Serial.println(yaw);
        digitalWrite(motor11, HIGH);
        digitalWrite(motor12, LOW);
        analogWrite(motor1pwm, thres2);
        digitalWrite(motor21, HIGH);
        digitalWrite(motor22, LOW);

        if(thres1+output<255)
        {
          analogWrite(motor2pwm, thres1+output);
        }

        else
        {
          analogWrite(motor2pwm, 255);
        }
      }

      else if(error<-0.001)
      {
        Serial.print("2. YAW= ");
        Serial.println(yaw);
        digitalWrite(motor11, HIGH);
        digitalWrite(motor12, LOW);

        if(thres2-output<255)
        {
          analogWrite(motor1pwm, thres2-output);
        }

        else
        {
          analogWrite(motor1pwm, 255);
        }
        digitalWrite(motor21, HIGH);
        digitalWrite(motor22, LOW);
        analogWrite(motor2pwm, thres1);
      }

      else if((error>-0.001)&&(error<0.001))
      {
        Serial.print("3. YAW= ");
        Serial.println(yaw);
        digitalWrite(motor11, HIGH);
        digitalWrite(motor12, LOW);
        analogWrite(motor1pwm, thres2);
        digitalWrite(motor21, HIGH);
        digitalWrite(motor22, LOW);
        analogWrite(motor2pwm, thres1);
      }

      oldPo=newPo;

      flag5=0;
      delay((timeStep*200) - (millis() - timer));
  }

    else if(abs(newPo)>600)
    {
      digitalWrite(motor21, HIGH);
      digitalWrite(motor22, LOW);
      analogWrite(motor2pwm, 90);
      digitalWrite(motor11, HIGH);
      digitalWrite(motor12, LOW);
      analogWrite(motor1pwm, 90);

      delay(300);

      if(flag5==0)
      {
        y=y+1;
        flag5=-1;
      }

      if(y%2==0)
      {

        while((abs(setPoint)-abs(yaw)<48)&&(yaw<0.2))
        {
          timera=millis();
          Vector norm = mpu.readNormalizeGyro();
          yaw = yaw + norm.ZAxis * timeStep;
          Serial.print("Turning Yaw= ");
          Serial.println(yaw);
          digitalWrite(motor11, LOW);
          digitalWrite(motor12, LOW);
          analogWrite(motor1pwm, 120);
          digitalWrite(motor21, HIGH);
          digitalWrite(motor22, LOW);
          analogWrite(motor2pwm, 120);
          delay((timeStep*2000) - (millis() - timera));
        }
        flag3=0;
      }

      else if((y+1)%2==0)
      {
          while(abs(yaw)-abs(setPoint)<50)
          {
            timera=millis();
            Vector norm = mpu.readNormalizeGyro();
            yaw = yaw + norm.ZAxis * timeStep;
            Serial.print("Turning Yaw= ");
            Serial.println(yaw);
            digitalWrite(motor11, HIGH);
            digitalWrite(motor12, LOW);
            analogWrite(motor1pwm, 120);
            digitalWrite(motor21, LOW);
            digitalWrite(motor22, LOW);
            analogWrite(motor2pwm, 120);
            delay((timeStep*2000) - (millis() - timera));
          }
          flag4=0;
          if(y==5)
          {
            while(true)
           {
              digitalWrite(motor11, LOW);
              digitalWrite(motor12, LOW);
              analogWrite(motor1pwm, 70);
              digitalWrite(motor21, LOW);
              digitalWrite(motor22, LOW);
              analogWrite(motor2pwm, 30);
            }
          }
      }

      digitalWrite(motor11, LOW);
      digitalWrite(motor12, LOW);
      analogWrite(motor1pwm, thres2);
      digitalWrite(motor21, LOW);
      digitalWrite(motor22, LOW);
      analogWrite(motor2pwm, thres1);

      flag1=0;
      flag2=0;

      newPosition = myEnc.read()/4;

      flag5=0;
      save=0;
      oldPo=0;

      delay(2000);
    }
}

This code is supposed to calculate a distance travelled in a line using encoder (PID algorithm implemented using Gyroscope data for straight motion) after reaching desired position, machine takes a U-Turn.
It stop for a second after taking the U-Turn and then starts straight motion again. The problem I'm facing is that the gyroscope readings stop randomly while machine taking the turn. Due to this, the machine keeps rotating about that point without stopping.
The serial monitor just stops displaying the reading. This does not happen every time, and it is very random.

Only some will look through all that code.  Suggest to start simple (rip out all the if() code) and keep adding back in code until it stops working.  First prove to us it is or is not a communications problem.  Then go from there.

Oh, should add.  It is a common problem that high current items such motors will cause the processors to reset / act unexpectedly.  Power your motors off a different power source WRT to the processor's power source.

@st2000 what should I add? Is there any way to solve this problem? Yes, tried with both way when we are connecting a different power source, common ground connected, also tried with the power source.

I think the problem has something to do with poor implementation. Even though I didn't go through all the code I found one that will cause the described behaviour: if y==5 the program will be stuck in the while(true) loop which contains no break condition. There might be other mistakes but the symptoms you descibe are quite vague and the code is so long... you should try to provide us with a minimal example

if y==5 the program will be stuck in the while(true) loop which contains no break condition. It is not even reaching up to this case. I have checked this case with a simple U-turn and stop, it is working fine multiple times. I am checking small case I will update and reduce code length


text:
Reliably reloading the calibration data of IMU BNO055
I am using the BNO055 IMU and the Adafruit Library.
I want to store the calibration data and load them after the microcontroller is powered off and repowered on.
The Adafruit Library provides an example for storing and restoring but, in actual facts, it does not work. It is always required to recalibrate the magnetometers, but even doing so, the library reperform the whole calibration including the accelerometers.
I would like to simply restore all the calibration data (including the magnetometers) so that no calibration needs to be performed when the IMU starts.
I have read a massive amount of posts on the argument, but I really could not figure out how to reliably load all the calibration data at boot and avoid recalibrating them.
Is there anyone who succeeded and can please share the code?

Possible duplicate of After restoring the BNO055 offsets to the sensor the calibration values are all 0

Actually no, it is not a duplicate at all. Indeed I am using a Teensy and Arduino. Also, that post does not show code.

read the answer in the duplicate, not the question. there is no way to avoid automatic calibration. the stored calibration is only used while the automatic calibration finishes. don't waste your time on it.

Thanks. Then what I am supposed to do? The last comment says "I would ignore the calibration. The sensor handles it. After power-up make same movements and the sensor calibrates itself. " So should I avoid any calibration in the end? And should I avoid storing the calibration in the EEPROM at all?

do you try to solve some problem or you only thought that you must handle the calibration?

I just want to have the calibration performed at boot automatically with the data previously stored. Any suggestion/code?

https://github.com/adafruit/Adafruit_BNO055/tree/master/examples/restore_offsets

I found the solution. It is enough to add a function that when reperfoming the calibration of the magnetometer, checks ONLY if the magnetometer is calibrated (while the calibration for the accelerometer and gyroscope is reloaded from the EEPROM).
void performMagCal(void) {
  uint8_t system, gyro, accel, mag;
  system = gyro = accel = mag = 0;

  while (mag != 3) {

    bno.getCalibration(&system, &gyro, &accel, &mag);
    displayCalStatus();
    Serial.println("");
  }

  Serial.println("\nMagnetometer calibrated!");
}


text:
NRF24l01 with Atmega 32u4 and internal clock
Will the nrf24l01 work with the Atmega 32u4 if I am using the 32u4's internal clock, or must I have an external clock source?

Knowing the interface between nrf24l01+ and Atmega32U4 is also answer to your question. And even with using asynchronous serial it should be possible (but might be less reliable sometimes)

Connecting to nrf24 via    CE, CSN, SCK, MOSI, MISO   -    I have the nrf24 working fine on my Pro Micro, now trying it on my custom pcb where I do not use an external oscillator.  My custom pcb works fine other wise, including the SPI as I have another device working on the SPI.  Just not working with the nrf24.

And SPI is synchronous interface, so there is a master sending CLK signal to clock data to selected slave

Correction,  My other device is connected via I2C,  not SPI.  But I am programming the 32u4 via SPI.

Without at least schematics, test scenarios and so on (what works or not works and where), it's hard to guess.

Should be just fine. I2C and SPI don't care about at what speed the MCU runs. Only things like UART sometimes require a more stable clock source, like a crystal, instead of the internal RC oscillator.

I found a mistake on my custom pcb,  I wanted CE as pin4 and CSN as pin5, but I mistakenly put them to pins 38 & 39 on the chip which are A4 and A5. Any issue having analog pins as CE and CSN?

You ask a yes/no question, to which the answer is yes, nRF24L01 as a serial peripheral device will work as well as if you had used an Arduino UNO or any other microcontroller, provided the SPI bus is correctly initialized.
Generally you want the following in the setup() part of your sketch/program:
  pinMode(CE_pin, OUTPUT);//chip enable set as output
  pinMode(CSN_pin, OUTPUT);//chip select pin as output
  pinMode(MOSI_pin, OUTPUT);//SPI data out
  pinMode(MISO_pin, INPUT); //SPI data in
  pinMode(SCK_pin, OUTPUT);//SPI clock out

  digitalWrite(CSN_pin, HIGH);//SPI idle
  digitalWrite(CE_pin, LOW);

  SPI.setBitOrder(MSBFIRST);//SPI Most Significant Bit First
  SPI.setDataMode(SPI_MODE0);// Mode 0 Rising edge of data, keep clock low
  SPI.setClockDivider(SPI_CLOCK_DIV2);//Run the data in at 16MHz/2 - 8MHz
  SPI.begin();//start up SPI library


text:
Programing AVR 32u4 via ISP with other ISP device connected
I have a custom PCB with an Atmega 32u4 chip.  I program the chip with AVRDUDE via ISP after it is has been mounted onto the PCB. All is well.
I now want to add wireless capability via the NRF24L01.  The NRF communicates with the 32u4 via ISP.  Can I still program the 32u4 on the PCB after the NRF has been mounted or will there be a problem since they are both connected to the ISP pins?

Yes, that is possible and I've done the exact same thing with an ATmega328 which controls a DAC via SPI. If it wasn't possible ISP wouldn't be an option whenever SPI is already in use.
You should make sure that the NRF's CS pin is high while flashing the firmware, otherwise it might corrupt a checksum verification or memory readout.
Note the difference between ISP (in-system programming) and SPI (serial peripheral interface). Even though ISP uses SPI and they have similar abreviations they are not the same.


text:
HC-05 Bluetooth module on breakout board with straight header pins
Has anyone found the HC-05 bluetooth module (on the breakout board) with straight header pins?  I seem to only be able to find them with the 90 degree header pins.  Removing those and soldering on straight ones for my project is getting tiresome...  I would even be happy to find them without header pins (but still on the breakout board).

In short: no. How many do you need that it's becoming tiresome? If the quantity is that high it's worth designing a custom PCB to take the module directly.

That is what I thought :-\  Thanks Majenko.  I will move forward with redesign to integrate just the module.

please post a link to the module or a picture of the module


text:
NRF24 CE and CSN connections without I/O pins easily accessible
I want 2 Arduinos communicating to each other, but only in one direction.  Arduino A = tx  and Arduino B = rx.
I have this working fine connecting CE and CSN on each NRF24 to pins 4 and 5 on each Arduino and using the nRF24L01 library.  No problem.
Since Arduino A will always ONLY be transmitting and Arduino B will always ONLY be receiving, can I do this with CE and CSN instead:
Arduino A --- put CSN to GND  and put CE to 3.3V
Arduino B --- put CSN to 3.3V and put CE to 3.3V
As to why?  This would simply help me interface the NFR24 to existing custom PCB's I've made which have no easy access to I/O pins.  My PCB's do have easy access to MISO, MOSI, and SCK.

No, you really do need the CE pin for both TX and RX modes.  See the following excerpts from the nRF24L01 datasheet.  They work practically the same for nRF24L01+:

It seems the CE pin is only used for TX, or to put it into standby. I think you can just connect it to VCC.
The CSN is required for SPI.
PS this RF24 library supports using the same pin for both CE and CSN. You'd have to define RF24_TINY for this to work.


text:
Sensor to detect whether string is in tension?
I need a sensor to detect whether there is tension on a string or not. I do not need an accurate measurement of the amount of tension- just whether the string is being pulled on or is taut.
Alternatively, if there is some homemade hack of this sensor, please let me know. I'd love to give it a shot!

tie the string to a spring loaded lever that closes a switch when the string is pulled

Tie the string to a momentary pull switch. It's like a button but you pull it, not push it.


text:
6 channel PWM with 2 - 5 kHz frequency
Is it possible to set all 6 PWM frequencies to a value between 2 and 5 kHz?
I've read that the base frequency for pins pins 5 and 6 is 62500 Hz.
And the divisors for the pins 5 and 6 are only this ones: 1, 8, 64, 256, and 1024.
The closest I can get is 7.812,5 Hz with the 8 divisor. Are there any other possibilities to achieve this?

To be honest, I don't know. I haven't choosed yet. My first attempt was to do it with the Raspberry, but the suggestion was to use Arduino. So I found this example: https://playground.arduino.cc/Code/PwmFrequency/

So I know it's goin to be an Arduino, but not exactly which model, because I didn't knew which are capable of my requirements in my question. If this sooo unclear to you, then go on and vote.

ok, since you are talking about arduino for sure, I am removing the vote to close

Judging from your mentioning 62.5 kHz as the base frequency for
pins 5 and 6, I assume you are talking about an Arduino Uno or
something similar.
If you set the timer 0 to phase correct PWM mode (which is how the
Arduino core configures the other timers), then its base frequency is
about 31.373 kHz (F_CPU/510). With the prescaler set
to 8, you get a PWM frequency of about 3.922 kHz on pins
5 and 6.
Note that you can set all three timers in this mode and have 6 PWM
channels at this frequency. But note also that by reconfiguring
Timer 0 you loose all the standard Arduino timing functions.

Thank you for your answer. Are there any other models which are better suited for this? But nevertheless, this is quite helpfull. Thank You!

@WaKai: A Mega has way more timers. On the other hand, if you don't need the Arduino timing functions, the Uno could do the job fine, and the Mega would be overkill.

Ah, I see. Clock speed: 16 MHz divided by 510 in phase correct mode for the ~32 kHz base frequency. Neat :-)
As far I can think ahead, I won't need any more timers. So the UNO should be perfect.


text:
Arduino Uno COM issue + Braccio qu
hey guys so i get this error when plugging in my arduino and not sure why:

Blockquote
Arduino: 1.8.9 (Windows 10), Board: "Arduino/Genuino Uno"
Sketch uses 930 bytes (2%) of program storage space. Maximum is 32256
  bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving
  2039 bytes for local variables. Maximum is 2048 bytes.
  avrdude: ser_open(): can't open device "\.\COM5": The system cannot find the file specified.
Problem uploading to board.  See
  http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
This report would have more information with "Show verbose output
  during compilation" option enabled in File -> Preferences.

How can i solve it? It used to work and not sure what's happened... also does anyone know if the Braccio robotic arm can be connected to arduino via just the arduino/usb cable alone? Because when i connect the braccio shield v4 to both th arduino(and to laptop) and to the wall, it actually causes my laptop to switch off ??

it appears that you are asking three different questions .... please ask only one question per post

the error is indicating serial port COM5 on your computer is unavailable. (windows treats a serial port like a 'file' on the programming level, hence the confusing message). This could be a hardware issue or a driver issue. You'll have to troubleshoot that first.


text:
Chip sync error while updating ATfirmware in esp8266
I find trouble updating my firmware with esp8266 with following error message.
[espDownloader.py][line:351][ERROR]: Chip sync error: Failed to connect to ESP8266: Timed out waiting for packet header
[2019-06-04 07:53:16,009][ESP8266Loader_spi[1]][espDownloader.py][line:439][ERROR]: ESP8266 Chip sync error esp_sync_blocking.
I am unable to resolve even after a number of attempts.
Please help me resolve my issue. Thank you in advance.

is the module in flashing mode, by pulling io 0 LOW at boot?

Yes m putting it in flash mode

does the original firmware answer over that port, cable and adapter?

my original firmware provides Garbage data and displays ready command, but  it doesn't answers any AT command.

read the 'garbage; at 74880 baud. it is the boot log. (some part will be always garbage or Chinese) send AT command at 115200 baud with both line ends set

thank you for your help, there was some problem with my chip. I bought an another one and it's working fine.


text:
Is it possible to program/flash ESP8266MOD(07) With Arduino UNO
i am new to ESp and yesterday i received my ESP8266MOD, i don't have FTDi connector with me right now(it's on the way).
Is it possible to flash ESP with Arduino UNO?
Regards,
Ben

yes you can. all you need is 5 wires. flip rx and tx and put gnd to rst on the uno.

Yes you can.
Take a look at this detailed guide.
The most important thing to keep in mind is that you have to connect from the ATmega16U2's perspective, so you have to swap RX and TX:

You'll probably want some buttons to facilitate the flashing process:

I think it is possible. You can use the Arduino Uno 's Rx and Tx lines, but maybe you will need to have a voltage divider resistor arrangement to step down the 5V UART lines from the Uno to the 3.3V needed by the ESP, otherwise you risk damaging the ESP.
The basic approach to flash a ESP is described by several web sources and instructables, such this one Getting started with the ESP8266 ESP-12 (there is also one section how to flash with an Arduino Uno).


text:
MQTT with OLED realy :- display not coming properly
I am very new to Arduino/ESP and I am writing a code to activate 2 relays using MQTT. Also like to display status on OLED
here is my code
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "SSD1306Wire.h"
#define wifi_ssid "ssid"
#define wifi_password "wifipassword"
#define mqtt_server "192.168.1.1"
#define mqtt_user "username"
#define mqtt_password "password"

SSD1306Wire  display(0x3c, D2, D1);
const int relay1 = 5;
const int relay2 = 4;
String header;
String display_line2;
String output5State = "off";
String output4State = "off";
const int output5 = 5;
const int output4 = 4;

WiFiClient wificlient;
WiFiClient espClient;
PubSubClient client(espClient);
ESP8266WebServer server(80);

//------------------- MAIN WEB PAGE ------------------------
const char MAIN_page[] PROGMEM = R"=====(
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>HOME IOT</title>

Security Door

<button class="button">Open</button>

<button class="button">Close</button>

)=====";
//------------------- MAIN WEB PAGE ------------------------

void setup() {
  Serial.begin(9600);
  //dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  //-----------------------------------------
  WiFiManager wifiManager;
  //wifiManager.resetSettings();
  wifiManager.autoConnect("IOT-LivinRoom");
  //-----------------------------------------
  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);
  server.begin();
  Serial.println("Initializing OLED Display");
  display.init();

  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  Serial.println("HTTP server started");
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);
  WiFi.begin(wifi_ssid, wifi_password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String messageTemp;
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }
  Serial.println();

 if(strcmp(topic, "livingroom/securitydoor") == 0){
     Serial.print("Changing esp01 relay1 to ");
     if(messageTemp == "on"){
       digitalWrite(relay1, LOW);
       Serial.print("On");
       doorOpening();

     }
     else if(messageTemp == "off"){
       digitalWrite(relay1, HIGH);
       Serial.print("Off");
       doorClosing();
     }
 }
 Serial.println();

 if(topic=="livingroom/ac"){
     Serial.print("Changing esp01 relay2 to ");
     if(messageTemp == "on"){
       digitalWrite(relay2, LOW);
       Serial.print("On");
       doorOpening();

     }
     else if(messageTemp == "off"){
       digitalWrite(relay2, HIGH);
       Serial.print("Off");
       doorClosing();
     }
 }
 Serial.println();
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
      client.subscribe("livingroom/securitydoor");
      client.subscribe("livingroom/ac");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

//--------------------------- void loop-----------------------
void loop() {

  server.handleClient();
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

}

//----------------------------- Web Calls Function --------------------------------------
void handle_OnConnect() {
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s);
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

//----------------------- LED display--------------------------------------

void doorOpening() {
  display.clear();
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 0, "Door");
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 28, "Opening");
  display.display();
}

void doorClosing() {
  display.clear();
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 0, "Door");
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 28, "Closing");
  display.display();
}

actually doorOpening() function is coming and doorClosing() function is not coming on OLED
again i am not very good in programming and arduino/esp8266

I would suggest leaving the MQTT broker and perhaps the OLED out of the software until you get the primary feature of opening and closing the garage door working as expected.  Also, there is no reason to assume certain libraries are compatible with one another.  Even if they work on one Arduino platform they may not work with one another on a different platform.

but here if i call the function in voild loop, oled is displaying what i expected also MQTT is always working for me.
i thought of doing the mqtt and oled before actual electrical circuit

Could be  a number if issues you might have with your code or the MQTT source.  For instance, are you actually sending "OFF" instead of "off" or even "Off"?  That is why I said do the simple things first.  Make sure they work.  Then add to what you know works.  When something breaks and you can not figure it out.  That would be the time to ask a question.

BTW, consider using Tasmota and a supported Sonoff ESP based product instead of writing your own code.  With Tasmota you can assume the MQTT feature works, the web server works, the WIFI works and the control over the supported Sonoff relays work.

i found the issue, actually relay pin was defined on D1 & D2 by mistake i connected oled to that pins


text:
Fastest sim module available?
I have used sim900 in my project but it isn't fast, I don't know if it is because it is on 2G or what, I wanna know if I can get something good that can send SMS messages immediately and doesn't take time to send multiple messages, if I switch to something that supports 3g can that solve my problem?

what is the actual problem that you are trying to solve?

@jsotola I have been trying to make a device that is being used to alert a seleted few people by SMS of a danger in that area, like when someone call on that number, it will automatically reject my call and then send my number through sms to other people that this guy is saying that there is some danger and for more information call this guy, but for that I need to send SMS messages as soon as possible, I have tried it with sim900 and it has reached it limit like it takes a few seconds before it can send the next message.

And there are a lot of things in GSM like class, speed etc, and I don't know if using 3G or 4G can make any difference to SMS sending speed too, so that is what I am asking here, if using them can make any difference or not.

I have been trying to make a device that is being used to alert a seleted few people by SMS of a danger in that area ... that part of your comment is clear and easy to understand and for some reason the rest of the comment is gibberish .... anyway,  maybe there is a way to send an SMS to multiple numbers with one command

SMS is a 2G technology, it does not utilised packet switch system in 3G/4G, so if you want to reduce latency, try to uses data network like socket connection.


text:
How can I upload .hex files to a Pro Micro using Linux?
I have a hand-wired keyboard that uses a Pro Micro board, with an ATmega32u4 chip. I can't seem to flash firmware on it. The commands I've been trying are variations of:
avrdude -p m32U4 -P /dev/ttyACM0 -c avr109 -U flash:w:atreus62.hex

The errors I've been getting begin:
Writing | #######avrdude: error: programmer did not respond to command: set addr
####avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: write block
 ***failed;
 ***failed;
 ***failed;
 ***failed;

And end:
#avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
#avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
# | 100% 0.16s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x0d != 0x0c
avrdude: verification error; content mismatch
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: error: programmer did not respond to command: exit bootloader

I'm on Arch Linux. Any ideas?

Enable verbose mode, program it once with the IDE, and copy the command line it uses.

What is the IDE?

And what do you mean by "program it"? Could you just tell me what the avrdude command is? I don't have any IDE installed.

Also verbose modes -v, -vv, -vvv, and -vvvv don't really seem to affect anything.

You are asking a question on the Arduino site, presumably you are familiar with the Arduino tools?  If not, give that a try first to validate your hardware and tools setup (before you try to do things the hard way.  Use the avrdude and configuration file for it that ships with a modern Arduino IDE version, and let the IDE drive it the first time, with verbose mode selected in the dropdown menu, so you see the suitable command.

I have no idea what the Arduino IDE is all about, but I installed it, and can't really make heads or tails of it. How can I open a hex file with it? If I could get the IDE to program the board, that'd be fine, too, but I have no idea what's going on in this program.

Also the IDE doesn't seem to have my board listed (pro micro).

@Jon, how did you create the hex file? ... it is odd that you would not know what an IDE is.

Using QMK. I know what an IDE is, just not what the Arduino IDE is supposed to do with .hex files, or how it's supposed to work.

There's two stages to uploading a hex file to a USB-based Arduino - and you're only doing the second stage.
The first stage is to reset the board into the bootloader so it can accept the instructions from the second stage.  The IDE normally does that manually for you when you hit the UPLOAD button.
The way these boards are reset is to first open the CDC/ACM port and set the baud rate to 1200, then close the port again. That triggers the code to reset the board into the bootloader.
You can probably do it using the stty tool in Linux:
$ stty -F /dev/ttyACM0 speed 1200
$ stty -F /dev/ttyACM0 speed 115200
$ avrdude -p m32U4 -P /dev/ttyACM0 -c avr109 -U flash:w:atreus62.hex

The second stty may not actually be needed, but it's good to reset the baud rate to a normal value ready for uploading. I don't have a board to hand right now to test it though.

Those commands don't seem to help, sadly. They both return 9600, if that's at all helpful. I'm still getting "programmer did not respond" errors.

The return value is the value it was before changing it. The second should return 1200 not 9600.  You can try using stty -F /dev/ttyACM0 ospeed 1200 ispeed 1200 instead.

That doesn't seem to help either, I'm afraid.

Have you had it working in the IDE at all?

I'm at a loss for how to upload .hex files to a chip using the IDE. (And furthermore the IDE is almost totally useless to me, since the UI isn't HiDPI-friendly.)

You don't upload hex files with the IDE. You write code, compile it, and upload that. Try the Blink example.

@Jon The point of the IDE and the reason we're all harping on it is that success in using the IDE's automation to upload trivial example code you aren't interested in shows you the commands you can then use to upload your custom hex file.  It lets you benefit from the work someone else put into figuring out how to do this, rather than having to figure it out again from scratch.  There's more wrong than right with the Arduino IDE when it comes to actual software development, but what it is good at is getting trivial code into a chip without spending a day reading documentation.

Also it confirms that your board is actually working and able to accept code. Some cheap chinese clones come without a bootloader.

If I can't upload hex files with the IDE, though, how can I use it? The codebase that generates my hex files is fairly complex, and scattered in a bunch of files across QMK. There's a real network of includes, env vars, and makefile instructions that I, as a non-C programmer, can't make sense of. Trying to put this all together in a way that the IDE will understand seems incredibly complicated. So I think everyone's advice to use the IDE is well-intentioned, but it won't help me just get this already-compiled hex file onto my board, which should be a simple task.

We're not telling you to use the IDE to complete your task. We are telling you to use the IDE to test that the board and everything is functional. Once that is confirmed we can then move on to more low-level things.

@Majenko you just saved my day, thank you! Couldn't get QMK to flash to my pro micro using any of the normal tooling, but setting ospeed and ispeed explicitly caused it to magically work. For the record I'm on OSX.

I had the same issue, and it was caused by udev, I found the answer here
It's some obscure bug
Tweaking udev rules solved the problem for me, now all is good, here is the procedure: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules

Had the same issue, and this fixed it for me! (mostly - I still had to use the stty commands from Majenko's answer, and run the upload a couple of times in order to get it working... but it worked!) It's a bit difficult to find this answer...


text:
Can I track 70 pressure sensors from Arduino Mega?
I am a beginner at Arduino which I just received in the mail. My understanding is my Arduino Mega has 54 digital inputs and 16 analog inputs making for 70 inputs all together. I would like to track pressure sensors which are configured to detect simply open or closed. Given I can use my analog inputs as digital inputs can I have 70 pressure sensors? My project differs from others in that I dont need to track a gradation. In regards to the mega wiring what can I do to achieve this? Will I need a separate breadboard for each pressure sensor?

It depends on what your pressure sensors are.

I am building my pressure sensors from velostat and copper tape. How about for arguments sake we say I am using something out of the box that is either simply open or closed. I can adapt the sensor to meet my needs. Hypothetically can I connect all the sensors to digital inputs?

Yes. The sensors are just buttons.

Thanks for the commentary. In my literature i see a complex wiring scheme for a button. Can you tell me the wiring scheme?

IO pin to button. Button to GND. Turn on internal pullup. Nothing can be simpler.

In my literature i see a complex wiring scheme for a button. ... please share the literature if you can

how are the sensors arranged? .... what is the distance between the sensors? ... are they in any kind of groups? .... you could use a matrix keypad arrangement of 8x10, for example. ... then you would only require 7 connections to the arduino

also be aware, that you would need some I/O pins to "present" whatever you get from those sensors. And that probably 2 of that 70 I/O pins would be connected to your computer, while programming/debugging your code (you can output the results there as well, but you may want to send the results out in other way, say I2C (so more 2 I/O pins) to manipulate something to beep or blink or so, when some sensors are pressed.). Should I need to read exactly 70 inputs (or even more) for just 0/1, I would use some shift-registers for all inputs and poll them with just 3 pins, having rest free for outputs


text:
Fade In/Fade Out with multiple LED strips
I want to make a strip led application(Fade In/Fade Out).Each strip has 48 pixels.One of the strips should be red and the other should be blue.Using the for loop, I managed to fade in-fade out a small number of strips (eg 10).But when I fade in / fade out all of the 48 leds, the code behaves as if there is a "delay".I guess that's because there's a lot of data in the for loop.Is there a way to do fade in / fade out without using a for loop?
#include "FastLED.h"
#define NUM_LEDS_PER_STRIP 48
CRGB redLeds[NUM_LEDS_PER_STRIP];
CRGB blueLeds[NUM_LEDS_PER_STRIP];
void setup() {
FastLED.addLeds<NEOPIXEL, 6>(redLeds, NUM_LEDS_PER_STRIP);
FastLED.addLeds<NEOPIXEL, 7>(blueLeds, NUM_LEDS_PER_STRIP);
FastLED.setBrightness(0);
}

void loop() {
//fade in
for(int i=0;i<256;i=i+5) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i);
redLeds[j] = CRGB(255,0,0);
blueLeds[j] = CRGB(0,0,255);
FastLED.show();
}}
//fade out
for(int i=255;i>=0;i=i-5) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i);
redLeds[j] = CRGB(255,0,0);
blueLeds[j] = CRGB(0,0,255);
FastLED.show();
}}
}

Each change of brightness requires sending out 48 LEDs x 3 bytes/strip, = 144 bytes = 1152 bits of data. Each bit needs 2.5uS of data, so 2.88mS minimum at 400 KHz data rate. I don't know what rate FastLED.h uses, might be as fast as 800 KHz. How many strips? 2? So double that.
Each string needs all of its data sent out if any one LED changes, so you might change 1 LED, and leave 143 alone, all the data still gets sent out. That's just the way the addressable strips work.

Thank you for the advice, but I don't know what you mean by "leave 143 alone."How do I make the 143 LED leave alone with the code?

@bopole 143: the number of bytes for one ledstrep that you do NOT want to change (48 leds * 3 bytes/strip = 144 bytes, 1 you want to change, the others  (143) not).

Say you had just 1 LED. Now you want to change 1 LED, and leave the other 2 as is. You have to send the 1 new value, and resend the 2 unchanged values. That's the way a chip like WS2812B  and others used in addressable strips work.  Expand to 48 LEDs. One byte changes, you send that new value and resend the unchanged values for everything else.

CrossRoads already gave a likely reason for the delay (so upvoted).
One way to solve it is using one microcontroller (slave) per LED string and split the load, and using one microcontroller as master:

Use a fast communication protocol between your current MCU (master) and the slaves (preferably small/cheap ones like Arduino Mini/Micro's), e.g. SPI which is easy to use for communication.
To make sure they all start at the same time, you can first send all data (SPI), and at the end after all data is sent to all slaves, set on the master a GPIO high where all slaves listen to, knowing they have to start sending.
SPI is very fast, but if you want to save communication time, you can make some smart commands (e.g. like sending a command to reset a group of bytes, or change a group of bytes by a certain value etc). Depending on what commands you want, it might be needed to store the data of all led strips on your Arduino, which can cost quite some money (see CrossRoads answer).


text:
Code working well on Arduino Uno is not working with Mega 2560
Following is the code block from my script. It uses timer1. Why it is not compatible with Arduino Mega?
TCCR1A = theTCCR1A; // 0b10000010;
  /*10 clear on match, set at BOTTOM for compA.
   00 compB disconected initially, toggled later to clear on match, set at BOTTOM.
   00
   10 WGM1 1:0 for waveform 15.
   */
  TCCR1B = 0b00011001;
  /*000
   11 WGM1 3:2 for waveform 15.
   001 no prescale on the counter.
   */
  TIMSK1 = 0b00000001;
  /*0000000
   1 TOV1 Flag interrupt enable.
   */
  sei();             // Enable global interrupts.
  // Set outputs pins.
  DDRB   = 0b00000110; // Set PB1 and PB2 as outputs.
  pinMode(13, OUTPUT); // Set trigger pin to output

It's not working because code you write is code that will work only on ATmega328. Every ATmega328 chip will run this code without any problem.
If you want that Mega does same task as Uno, then you have to rewrite whole code and use Arduino functions(such as pinMode, digitalRead etc..) or read ATmega2560 datasheet and use ATmega2560 registers. Also Search for ATmega2560 pin layout, you'll need it if you want use registers.


text:
How to Specify Array Length during Object Construction within Arduino IDE?
I'm working on a group project to involving the creation of an in-house library using the Arduino IDE. As the Arduino IDE uses C++, the library must be a class. One of the classfields is an array of numbers. We would like it if we could specify the array length during object construction, as there are pros and cons to low and high array lengths. Is it possible to specify or change the array length during object construction?
Unfortunately, the Arduino IDE doesn't allow the usage of C++ vectors, so that's out of the question.

Arduino library doesn't need to be a class

It's not out of the question. There are various ports of the STL (Standard Template Library) for the Arduino. Try searching for them. The Arduino IDE does not itself preclude using them.

As suggested in st2000’s
answer, you could use
dynamic allocation but, if you do that, do not forget to free the
allocated memory in the destructor. Otherwise you have a nasty memory
leak and your program will not live long:
class MyClass {
public:
    MyClass(size_t length) : arrayLength(length) {
        theArrayOfNumbers = new int[arrayLength];
    }
    ~MyClass() {
        delete[] theArrayOfNumbers;
    }
private:
    const size_t arrayLength;
    int *theArrayOfNumbers;
};

One issue with this approach is that dynamic allocation is no very
friendly to the limited amount of memory you have in a microcontroller.
A safer option would be to use a template class instead. This way the
array is statically allocated:
template <size_t arrayLength>
class MyTemplateClass {
    int theArrayOfNumbers[arrayLength];
};

One caveat with this approach is that the users of the library may not
be comfortable with the syntax for instantiating a template. You will
have to provide clear examples in the documentation. Another issue is
that the array size will have to be a compile-time constant.

As suggested in the previous answer - better to link to the answer. There is no such thing as permanent "previous" in Stack Exchange. The order of answers depends on the voting. Each answer has a share link which can be used to get a suitable link to it.

a note: for every use of the template with a different size, compiler generates a different class. every class takes space in program memory

@NickGammon: Good point. Added the link.

Memory allocated using new[] has to be deleted using delete[], not delete.

tttapa is right. That line should read: delete [] theArrayOfNumbers;

Oops! My bad. Turns out, with avr-gcc, operator delete and operator delete[] are implemented identically, as jmp free. But then, of course, this should not be relied upon. I fixed the answer.

Another way is for the caller to provide the memory as a pointer to enough bytes for 'N' objects (cast, if necessary, as a pointer to the required type), and the number, 'N' of such objects. This gives the caller the choice of whether to allocate statically or dynamically.
It looks like you want an array of ints. So you'd allocate an array (statically, in my example, but you could choose whichever best fits your application):
int memArray[N];
// ...
myClass(N, memArray&);

I avoid allocating memory from the heap, but someone else might have a different preference or a situation that requires it; this technique lets the library work for either.

Some example solutions can be found in this stackexchange question/answer.  The accepted answer used this code:
private int size;

private String words[];

public WordStore(int n){
     words =new String[n];
}

and releasing the allocated memory? and prevent fast memory fragmentation?

Really good points @Juraj, I'd add them but Edgar has already provided good examples.  Thanks.


text:
Arduino Wifi Works one way but not the other? (ESP32) (Possible Variable Type Problem)
I am working on a code that accepts input from serial monitor and connects to Wifi, and have been getting issues.
my SSID for my wifi is "SamF" but for some reason arduino only likes it when I initialize at the top, not when I accept it from serial monitor even though they are the same..
Example The below code works:
#include <WiFi.h>

char ssid[] = "SamF"; //OR const char* = "SamF"
char pass[] = "secretPassword";
void setup()
{
WiFi.begin(ssid, pass);
}
void loop () {}

The Code Below Does not work..
#include <WiFi.h>
char pass[] = "secretPassword";
void setup()
{
ssidSerial = my code that receives Serial input and converts to char

for(int k=0;k<=3;k++){
ssidPlaceHolder[k]=ssidSerial[k];
}
const char* ssid = ssidPlaceHolder;
WiFi.begin(ssid, pass);
}
void loop () {}

Everything compiles fine, I debugged by using Serial.print and they are both displaying "SamF" and sizeof(ssid) for both is 4... so I am not sure why one works and the other doesn't? any ideas?
Thanks in advance for any help, and if anyone needs the code after I am done I will be more than glad to share it on git!

add a terminating 0 to ssidPlaceholder end. 4 char string needs 5 char array to have the 5th position set to 0

why do you copy the string from ssidSerial to ssidPlaceHolder and what for is the assignment to ssid pointer?

Thanks for response Juraj, I will try add the terminating 0 to the variable once I get home and will let you know what happens, I copied it over because ssidSerial adds garbage data at the end, because I am using Bluetooth Serial, ssidSerial is "SamF   garbage symbol" and I needed "SamF" that is why I am coping it over.

just to clarify more,  receiving after receiving Bluetooth serial data the variable ssidSerial becomes "SamF   garbage symbol/data" of length 10 which I thought would mess it up.  the wifi library accepts data in the form of a pointer which is why it's there, I know its the same thing as just ssidPlaceHolder but I thought it would help

perhaps you send the new line character(s) \n or \r\n, not garbage

interesting... I will print out the hex value to see what exactly the additional data is

->So the problem was that I had not terminated the char, I didn't know you needed to manually terminate them for some reason. Thanks for answering, please answer the question below so that I can select your answer and you can get reputation!
->Also, If you are wondering or curious, the "garbage data" at the end of the array was some symbols and negative acknowledgments it was ",@NAK?  NAK". Which might be coming from the Bluetooth of the ESP32? maybe it is how Bluetooth ends it's message, I am not too familiar with networking. Thanks again!

Basic string in C is an array of characters terminated by a 0. All functions taking char* or const char* use this 0 to determine the end of the string, because there is no other information about the length of that string.
In your question you copy characters from one characters buffer to other, but you do not set the terminating 0, so the function begin takes the data after the pass pointer until some random memory location with 0.


text:
Can client IP address be obtained from Arduino Ethernet2 library for W5500 during client.connected() call?
I've found posts explaining how to get client IP by modifying the W5100 Ethernet library and the Adafruit CC3000 library but not the Ethernet2 lib for W5500 chip, which is different enough that the W5100 mod won't work. I suspect the TCP Socket struct will contain it, but haven't been able to find its declaration anywhere to confirm this so I can modify the library to make it accessible.

in Ethernet library 2.00 (it is not Ethernet2), EthernetClient has remoteIP()

Use the new update of the 'old' Ethernet library. It is version 2.00 and you can install or update it in the Library Manager in IDE. Note, it is not Ethernet2 library. The new Ethernet library supports W5500 and has client.remoteIP().
example
  if (client.connect(server, 80)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());

New features in version 2.0.0
  Auto-detection of W5100, W5200, and W5500 Ethernet hardware.

The version cited here is for the W5100 chip and won't work with the W5500, as mentioned on the Arduino reference page for the Ethernet library - "Ethernet library (Ethernet.h) manages the W5100 chip, while Ethernet2 library (Ethernet2.h) manages the W5500 chip; all the functions remain the same."

https://github.com/arduino-libraries/Ethernet/releases

Thanks, the link was helpful. As I thought, I already had it installed in my Arduino IDE. When I looked at the source file names I saw W5100.cpp and thought nothing had changed. Looking at the code, though, I see additions to handle W5200 and W5500.

This solution works: http://forum.arduino.cc/index.php/topic,82416.0.html if "W5100.readSnDIPR(_sock, remoteIP);" is replaced with "w5500.readSnDIPR(_sock, remoteIP);" [note the lower case 'w']. I didn't think it would because I can't find readSnDIPR() in the Ethernet2 library source, but after reviewing the Wiznet 5500 data sheet (https://www.mouser.com/pdfdocs/w5500_ds_v100e.PDF) I realized it was probably a read of the "Socket n Destination IP Address" register and decided to try it and see if it linked. It did, and successfully returns the remote IP after connecting.

and why do you use an outdated library? Ethernet2 is now obsolete

From Arduino reference page for Ethernet library: "Ethernet library (Ethernet.h) manages the W5100 chip, while Ethernet2 library (Ethernet2.h) manages the W5500 chip; all the functions remain the same." The current version of Ethernet2 is V2, btw, and it does not have a remoteIP method in its client class.

the new version is less then a month old. the docs are not updated

I have the latest version available via the Arduino IDE. Perhaps you should post a link here to the later version for the benefit of others.


text:
How to improve response time of this sound operated LED?
I have written the following code for lighting an LED on a  clap ( using sound sensor)   that I have connected via a resistance of  330 OHM on pin number 4.
However, when I clap once,  close to the sound sensor,  it does not lights  the LED. But it only lights the LED if  I provide prolong exposure to sound  ( more than 6 seconds) on the sound sensor.
How can I improve this , so that even if I clap once for a seconds duration, the LED glows?
int soundSensor=10;
int LED=4;

void setup()
{
 Serial.begin(9600);
 pinMode(soundSensor,INPUT);
 pinMode(LED,OUTPUT);
}

void loop()
{
  int SensorData=digitalRead(soundSensor);
  if(SensorData==1)
  {

     digitalWrite(LED,HIGH);
  delay(3000);

     Serial.println("LOUD, LOUD");
     delay(1000);
  }
    else
  {

     digitalWrite(LED,LOW);
     Serial.println("SLOW, SLOW");
     delay(1000);
  }
 }

One thing is that your program does a lot of waiting, the loop only runs once every second when there's no sound. Also the delay could be in the sensor itself, make clear what sensor you're using. Ideally you would also include a schematic to show how it is connected.

I think the problem is in the times you check the sensor. If you clap exactly when you check it will glow even if clapped for 1 ms, but if it checks in between two claps it doesn't detect it.
So check more often (reduce the delays) and check for so many sound detections within one second.
Or, as JRE below proposes, use an interrupt, this is even better but needs a bit more programming skills. Still interrupts are used a lot in microcontroller programming so it is worthwhile to check into this.

Or use an interrupt.

@JRE Thanks for the good remark, I updated my answer.

Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. Good tasks for using an interrupt may include reading a rotary encoder, or monitoring user input (like clapping).
Using the attachInterrupt() function is the way to go here!
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

Depending on sensor , simple modification with series diode to detect impulse and hold decaying slow with say 0.01uF to  and 10 MOhm to 0V will detect 1st time and stretch pulse ~ 0.01u*10M =0.1s


text:
GPS: Not receiving any valid output from ATGM336H
I have an Arduino Pro Mini along with a GPS Unit - ATGM336H. Below is the sketch I'm currently using:
#include <SoftwareSerial.h>
#include "Ublox.h"
SoftwareSerial GPS(4,5);
Ublox serial_gps;

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

void loop(){
  while(GPS.available()){
  char c = GPS.read();
  if(serial_gps.encode(c)){
  Serial.println(serial_gps.longitude);
    }
  }
}

I'm able to receive NMEA stream from the GPS Unit and parse (tried TinyGPS++, TinyGPS and Ublox) the stream but the data is not valid nor does it ever change. I've read that this GPS unit can take up to 32 seconds to get a fixed position and deliver valid co-ords but I cannot receive any.

Is there anything obviously wrong with my sketch or hardware setup?
Any and all help would be greatly appreciated!

remove the if(serial_gps.encode(c)){ Serial.println(serial_gps.longitude); } .... instead, use Serial.println(c); to see if there is any actual data ...... I think that you are sending individual characters to gps.encode(), so you get nothing back

while(GPS.available() > 0) {....
Also is the GPS unit outside?

I have tested the project both indoors and outdoors. I do receive NMEA streams but they seems to be lacking critical info.
I will include the >0 and get back to you with a result

There is no difference between while(GPS.available()) and while(GPS.available() > 0). 0 is false anything else is true and GPS.available() doesn't return negative values.

available() returns the number of bytes in the RX buffer, so if you juts use available() zero will be returned and the sub will run and return zeros which is what his output looks like. If you use available() > 0 then only when 1 or more bytes exist then the sub will run.

If available() returns zero then the while loop will not run, since zero is false.


text:
Posting TinyGPS++ co-ordinates as paramaters with GPRS
I'm able to view my co-ords on the Serial Monitor using Serial.println(gps.location.lat(), 6);
I believe the data type returned by gps.location.lat() is double. I need to pass this value to a webservice with AT commands over GPRS.
double latitude = gps.location.lat()
Later in my code I execute AT commands to begin HTTP POST. I would like to know how to pass these double values in my paramaters.
gsm.println("AT+HTTPPARA=\"URL\",\"http://webservice/service1\"");
 gsm.println("AT+HTTPDATA=192,10000");
 gsm.println("latitude=" + latitude); < This is not allowed.
How can I pass this parameter to my web service.

One solution may be to split the commands:
gsm.print("latitude=");
gsm.println(latitude);

I'm not sure how you should pass multiple parameters; if it is the usual syntax you can write something like
gsm.print("latitude=");
gsm.print(latitude);
gsm.print("&longitude=");
gsm.println("longitude);

If I have the time I'll research into this a bit.
To check what is the problem, you may try to send "static" messages, like
gsm.println("latitude=12.345");

To check if this format is the correct one
EDIT: after a very quick research
It looks like the AT commands are a bit more complicated. In order to send the parameters, at least on a SIM800L, you should:

send the HTTPDATA command (the first parameter is the length of the payload)
wait for the board to send you the command DOWNLOAD
Send the body of the request, which is formatted as a JSON object. This means you have to send something like { "latitude" : 12.345, "longitude": 98.765 }

After all, it is much faster to use a library already developed for this, for instance ArduinoSIM800L (check a library available for your GPRS modem, or modify this one)

Seperating the values in individual print commands was the trick. Thanks!


text:
VMA101 Mega 2560 upload error
I have a Velleman VMA101 Arduino Mega 2560.
https://www.velleman.eu/products/view/?id=435498
When I connect it to my computer, I can see it on Port COM18 with a yellow triangle, which means something is wrong. On IDE I had COM3 available, so I went to device manager and chaged the port to COM3.

The drivers are installed correctly when I installed the Arduino IDE 1.8.7.
I tried to get the board's info and I got this:
BN: Unknown board
VID: 04E8
PID: 6860
SN: Upload any sketch to obtain it

After that, I tried to upload an empty project to see whether it will work or not. It didn't work and I got this error message:
avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Desktop\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
An error occurred while uploading the sketch
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

What's wrong with my board?
How can I solve this problem?

The board was working perfectly for months

Uninstall the device and let Windows find it again.

I uninstalled everything (devices, drivers), then installed everything again. The computer recognized the device and installed correctly the driver but I got "code 52" which looks related to unknown signature of the driver. How could this be solved?

Embrace the dark side and upgrade to Windows 10? No driver needs to be installed then.

found solution here https://forum.arduino.cc/index.php?topic=317769.0 thanks anyway


text:
On the LEDs WS2812C
I've got a few questions about these LEDs (WS2812C). According to what I understand in the data sheet, they are adressable RGB LEDs with 4 pins: VCC, GND, DIN,DOUT. I'm working on a project that is an LED cube, and these LEDs are a very good candidate for my project, but I'm trying to figure out how I'm supposed to wire them (like how the circuit diagram should be).
So I have three questions:
1) is 1111 the maximum number of LEDs I can have in series? because the datasheet says that the maximum transfer rate is 800Kbps, and if I have to refresh the LEDs at a rate of 30 fps, and if my math is correct, 800Kbps/30fps/24bits = 1111 pixels. So please let me know if my math is correct on that, because that would imply that I would need two rows of LEDs if I were to make a 20x10x10 LED cube.
2) In the cicuit diagram of the datasheet there was only a capacitor and no resistor. According to what I know, you should always have a resistor in series with your LED, so that you don't blow it out. It is still the case with these?
3) Can I have one big capacitor instead of many small ones in parallel? I'd think that it would be equivalent but I'm not an expert so I don't know.
If any of you can help me figure out the answer to these questions I would highly appreciate it. Thanks.

are you sure that the LEDs are suitable for a 3D layout?

the serial protocol has a reset signal of 50μs for each refresh, so the maximum LEDs would be 1109 for 30fps

if you know what you are doing, apparently you can drive 20,000+ WS2812C @ 130fps

Ok, so to clear up a little how I'm going to make this cube happen, I am designing my own pcb and it's going to be a 5x5x5 cube to start, but I might make a bigger one in the future. Now I neeed to figure out the capacitor and resistor configuration for the pcb.
So do I need to have one capacitor (of value 15pF) per LED, or can I have one bigger capacitor (of value 15pF*n) for n LEDs?


text:
5th Led wont turn on (ws2812)
I'm trying to re-use a piece of example code I found here:
https://howtomechatronics.com/tutorials/arduino/how-to-control-ws2812b-individually-addressable-leds-using-arduino/
And I only have 5 LEDs in my strip, so I changed the define NUM_LEDs to 5, but when compiling with that value, I get a compilation error. with the define at 6 it works tho, but the 5th LED wouldn't turn on. Here is my code:
#include <FastLED.h>
#define LED_PIN     7
#define NUM_LEDS    6
CRGB leds[NUM_LEDS];
void setup() {
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);

}
void loop() {

  leds[0] = CRGB(0, 10, 0);
  leds[1] = CRGB(10, 0, 0);
  leds[2] = CRGB(0, 10, 10);
  leds[3] = CRGB(10, 10, 0);
  leds[4] = CRGB(10, 10, 10);
  FastLED.show();
  delay(500);
  leds[0] = CRGB(0, 0, 0);
  leds[1] = CRGB(0, 0, 0);
  leds[2] = CRGB(0, 0, 0);
  leds[3] = CRGB(0, 0, 0);
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();
  delay(500);

}

So in the code, I've set the first LED to green, seccond one to red, third one to blue, 4th one to yellow, and the 5th one to white. As you can see in the picture they all light up correctly but the 5th one which stays blank, and I don't know why. I have tested this LED individually and it works perfectly well so it's not a hardware problem. I would encourage anyone who wants to test this code on 5 LEDs and let me know if it works for them, I'd be surprised it it did, but if you have a better solution for me, I would appreciate it.
Thanks.

What is the compilation error you get when setting the number of LEDs to 5? Does the 5th LED turn on if you set it to another color, let’s say red? You said it works individually and, looking at the picture, it seems you have wired the LEDs yourself: have you checked the data line is soldered correctly and you don’t have a flickering connection?

Holly crap, I literaly did this earlier today and had a compilation error, but I just tried it now, and the error went away. no idea why. By the way I got these PCBs made and you're right, I did solder it myself

but the 5th LED still doesn't light up. It might be a problem with the circuit but I really think it's the code. If someone can test this code on a strip of 5 LEDs it would be nice if they could confirm if it's a hardware problem or the code.

Your code is non optimized but correct: all LEDs should light up but very dim for half a second and turn off for another half. Please note you are setting a value of 10 out of 255, meaning you are about at 5% power. Try replacing 10 with 255 and see the increased brightness, but take into consideration the increased power consumption as well: the power supply for the strip must be able to safely deliver that much current.

what happens if you code it for 10 LEDs, does the last one work then?


text:
How to connect 10 coin vibration motors to UNO?
I am new to arduino and anything related to electricals and electronics. I need info on how to connect 10 vibration motors to arduino uno without damaging the board. Do I need an external circuit to regulate and control power supply or can I directly plug in all 10 motors to the board directly?

Lookup how to connect a motor to an Arduino (resistor, transistor and flyback-diode). These vibration motors sound small enough that you might be able to connect them directly to the Arduino, but you'd have to provide us with something like a part-nr, so we can check the current rating of the motors.

Specifications: Outer diameter: 10 MM; Thickness: 3 MM
Rated voltage: 1V To 6V,; Current: 66 MA
Output Speed: 12000 RPM (https://www.amazon.in/dp/B07YPS3D3L/ref=cm_sw_r_cp_apa_i_duYDFb81K30VN)

Current is too high for an Arduino. Any small transistor (NPN BJT or N-channel FET with low enough Vgs) will do to drive one. Multiply that by 10 and bob's your uncle. Maybe two ULN2003 will be more economic.

Any small transistor, plus a flyback diode, plus (for a BJT transistor) a properly sized current limiting resistor.

I would suggest a pair of ULN2003 chips.  These are 6 darlington transistors in a single chip.   Two chips will give you the ability to connect 12 motors.
Each one needs an IO pin to control it - if you want speed control then you will have to look into adding extra PWM channels. For just ON/OFF control any IO pin will do (even analog ones).
10 motors running at the same time will be up near the limit of the Arduino's 5V pin current supply, so you really should consider a separate external 5V power supply (maybe a USB phone charger) of 1A or more to power everything (connect the power supply to the motors and the 5V pin of the Arduino).

Thanks for your input. But I will have at most only two of them running and I don't need any control except on and off over the motors. This is possible without ULN2003 drivers right?

It is possible to replace the ULN2003 chips with 10 transistors and 10 diodes. You can run it all from the Arduino's 5V pin though instead of an external power supply.

Watch out for the voltage drop from the ULN2003 chips, I think it about 1.4V at load.

@Gil What about it? You read the rated voltage or the motors?

The motor is not a constant output device, it still works by watts of power. The motor will only draw enough current to move its load at a given speed. Lets assum the impedance of the motor is a constant; If we change the voltage we change the wattage and hence the torque and probably speed. "The Arduino a power supply it is not!" On a good day it has a 200ma max capability. This is dependent on the power the regulator can dissipate, dictated by load and the voltage going into the Vin pin.
If we look at the 66mA it draws times 10 motors that is 660 mA is way beyond the Arduino rating of 200ma. Total chip Vcc current (all output pins total and chip overhead): 10 output pin driving 10 motors @ 66 ma is way beyond max for whole chip.