text:
ESP32 - Social distance detector - code
I recently got an ESP32-CAM for a project of mine. I was planning to attach an ultrasonic sensor to it, and when the ESP32 CAM detects a face, it would send a signal to the ultrasonic sensor to start measuring, and then the LCD would display the distance.
The original plan was to let the CAM code run on the ESP32-CAM module, and the ultrasonic sensor code on the Arduino Uno, but I cannot find a way to do let both programs communicate with each other, or putting them in one program. Any ideas?
The ESP32 Cam is connected to the Arduino Uno using rx and tx.
I am trying to combine these two programs:
This is the ESP32-CAM code:
#include <ArduinoWebsockets.h>
#include "esp_http_server.h"
#include <WiFi.h>
#include "camera_index.h"
#include "esp_camera.h"
#include "fb_gfx.h"
#include "fd_forward.h"

const char* ssid = "Manitoba";
const char* password = "pjq20070616";

// Arduino like analogWrite
// value has to be between 0 and valueMax
void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 180)
{
  // calculate duty, 8191 from 2 ^ 13 - 1
  uint32_t duty = (8191 / valueMax) * min(value, valueMax);
  ledcWrite(channel, duty);
}
int pan_center = 90; // center the pan servo
int tilt_center = 90; // center the tilt servo

#define CAMERA_MODEL_AI_THINKER
#include "camera_pins.h"

using namespace websockets;
WebsocketsServer socket_server;

static inline mtmn_config_t app_mtmn_config()
{
  mtmn_config_t mtmn_config = {0};
  mtmn_config.type = FAST;
  mtmn_config.min_face = 80;
  mtmn_config.pyramid = 0.707;
  mtmn_config.pyramid_times = 4;
  mtmn_config.p_threshold.score = 0.6;
  mtmn_config.p_threshold.nms = 0.7;
  mtmn_config.p_threshold.candidate_number = 20;
  mtmn_config.r_threshold.score = 0.7;
  mtmn_config.r_threshold.nms = 0.7;
  mtmn_config.r_threshold.candidate_number = 10;
  mtmn_config.o_threshold.score = 0.7;
  mtmn_config.o_threshold.nms = 0.7;
  mtmn_config.o_threshold.candidate_number = 1;
  return mtmn_config;
}
mtmn_config_t mtmn_config = app_mtmn_config();

httpd_handle_t camera_httpd = NULL;

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

  // Ai-Thinker: pins 2 and 12
  ledcSetup(2, 50, 16); //channel, freq, resolution
  ledcAttachPin(2, 2); // pin, channel

  ledcSetup(4, 50, 16);
  ledcAttachPin(12, 4);

  ledcAnalogWrite(2, 90); // channel, 0-180
  delay(1000);
  ledcAnalogWrite(4, 90);

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  //init with high specs to pre-allocate larger buffers
  if (psramFound()) {
    config.frame_size = FRAMESIZE_UXGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }
#if defined(CAMERA_MODEL_ESP_EYE)
  pinMode(13, INPUT_PULLUP);
  pinMode(14, INPUT_PULLUP);
#endif
  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  sensor_t * s = esp_camera_sensor_get();
  s->set_framesize(s, FRAMESIZE_QVGA);

  WiFi.begin(ssid, password);

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

  app_httpserver_init();
  socket_server.listen(82);

  Serial.print("Camera Ready! Use 'http://");
  Serial.print(WiFi.localIP());
  Serial.println("' to connect");
}

static esp_err_t index_handler(httpd_req_t *req)
{
  httpd_resp_set_type(req, "text/html");
  httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
  return httpd_resp_send(req, (const char *)index_ov2640_html_gz, index_ov2640_html_gz_len);
}

httpd_uri_t index_uri = {
  .uri       = "/",
  .method    = HTTP_GET,
  .handler   = index_handler,
  .user_ctx  = NULL
};

void app_httpserver_init ()
{
  httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  if (httpd_start(&camera_httpd, &config) == ESP_OK)
    Serial.println("httpd_start");
  {
    httpd_register_uri_handler(camera_httpd, &index_uri);
  }
}

static void draw_face_boxes(dl_matrix3du_t *image_matrix, box_array_t *boxes)
{
  int x, y, w, h, i, half_width, half_height;
  fb_data_t fb;
  fb.width = image_matrix->w;
  fb.height = image_matrix->h;
  fb.data = image_matrix->item;
  fb.bytes_per_pixel = 3;
  fb.format = FB_BGR888;
  for (i = 0; i < boxes->len; i++) {

    // Convoluted way of finding face centre...
    x = ((int)boxes->box[i].box_p[0]);
    w = (int)boxes->box[i].box_p[2] - x + 1;
    half_width = w / 2;
    int face_center_pan = x + half_width; // image frame face centre x co-ordinate

    y = (int)boxes->box[i].box_p[1];
    h = (int)boxes->box[i].box_p[3] - y + 1;
    half_height = h / 2;
    int face_center_tilt = y + half_height;  // image frame face centre y co-ordinate

    //    assume QVGA 320x240
    //    int sensor_width = 320;
    //    int sensor_height = 240;
    //    int lens_fov = 45
    //    float diagonal = sqrt(sq(sensor_width) + sq(sensor_height)); // pixels along the diagonal
    //    float pixels_per_degree = diagonal / lens_fov;
    //    400/45 = 8.89

    float move_to_x = pan_center + ((-160 + face_center_pan) / 8.89) ;
    float move_to_y = tilt_center + ((-120 + face_center_tilt) / 8.89) ;

    pan_center = (pan_center + move_to_x) / 2;
    Serial.println(pan_center);
     int reversed_pan_center = map(pan_center, 0, 180, 180, 0);
    ledcAnalogWrite(2, reversed_pan_center); // channel, 0-180

    tilt_center = (tilt_center + move_to_y) / 2;
    ledcAnalogWrite(4, tilt_center); // channel, 0-180

  }
}

void loop()
{
  auto client = socket_server.accept();
  camera_fb_t * fb = NULL;
  dl_matrix3du_t *image_matrix = NULL;

  while (true) {
    client.poll();
    fb = esp_camera_fb_get();
    image_matrix = dl_matrix3du_alloc(1, fb->width, fb->height, 3);

    fmt2rgb888(fb->buf, fb->len, fb->format, image_matrix->item);

    box_array_t *net_boxes = NULL;
    net_boxes = face_detect(image_matrix, &mtmn_config);

    if (net_boxes) {
      draw_face_boxes(image_matrix, net_boxes);
      free(net_boxes->score);
      free(net_boxes->box);
      free(net_boxes->landmark);
      free(net_boxes);
    }

    client.sendBinary((const char *)fb->buf, fb->len);

    esp_camera_fb_return(fb);
    fb = NULL;
    dl_matrix3du_free(image_matrix);
  }
}

And here is the ultrasonic code:
#include <HCSR04.h>
#include <LiquidCrystal.h>
#define trigPin 7
#define echoPin 6
#define buzzer 9
#define backlight 10

LiquidCrystal lcd(12, 11, 5, 4, 3, 8);
UltraSonicDistanceSensor distanceSensor(trigPin, echoPin);

int tempReading;
double tempK;
float tempC;
int rounded;
int temp_round;
volatile boolean modes = 0;
double distance;

void setup() {
  lcd.begin(16, 2);
  attachInterrupt(0, changeMode, FALLING);
  pinMode(2, INPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(backlight, OUTPUT);
  digitalWrite(backlight, HIGH);
  backlightOn();
}

void loop() {
  tempReading = analogRead(A0);
  tempK = log(10000.0 * ((1024.0 / tempReading - 1)));
  tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK );
  tempC = tempK - 273.15;
  distance = distanceSensor.measureDistanceCm(tempC);
  temp_round = round(tempC);
  if (modes == 1) {
    backlightOn();
    if (distance >= 300 || distance <= 0) {
      rounded = 0;
      lcd.clear();
      lcd.print("Out of range");
      lcd.setCursor(0, 1);
      lcd.print("Temperature:" + String(temp_round) + " C");
    }
    else {
      rounded = round(distance);
      lcd.clear();
      lcd.print("Distance: ");
      lcd.print(rounded);
      lcd.print(" cm");
      lcd.setCursor(0, 1);
      lcd.print("Temperature:" + String(temp_round) + " C");
    }
  } else {
    if (distance >= 300 || distance <= 0) {
      lcd.print("Out of range");
    }
    else {
      rounded = round(distance);
      if (distance >= 200) {
        backlightOn();
        lcd.clear();
        lcd.print("Out of range");
      }
      else if (distance <= 200 && distance > 100) {
        backlightOn();
        lcd.clear();
        lcd.print("Please keep away");
        lcd.setCursor(0, 1);
        lcd.print("Distance:");
        lcd.print(rounded);
        lcd.print(" cm");
      }
      else if (distance <= 100 && distance > 50) {
        backlightOn();
        lcd.clear();
        lcd.print("Keep away");
        lcd.setCursor(0, 1);
        lcd.print("Distance:");
        lcd.print(rounded);
        lcd.print(" cm");
        delay(200);
        tone(9, 260, 200);
        backlightOff();
        delay(100);
        backlightOn();
        delay(100);
      }
      else if (distance <= 50) {
        backlightOn();
        lcd.clear();
        lcd.print("STAY AWAY!");
        lcd.setCursor(0, 1);
        lcd.print("Distance:");
        lcd.print(rounded);
        lcd.print(" cm");
        delay(100);
        tone(9, 260, 200);
        backlightOff();
        delay(100);
        backlightOn();
        delay(100);
        tone(9, 260, 200);
        backlightOff();
        delay(100);
        backlightOn();
      }
    }
  }
  delay(700);
}

void changeMode() {
  modes = !modes;
}

void backlightOn() {
  digitalWrite(backlight, HIGH);
}

void backlightOff() {
  digitalWrite(backlight, LOW);
}

void buzz() {
  digitalWrite(buzzer, HIGH);
}

void unbuzz() {
  digitalWrite(buzzer, LOW);
}

Is measureDistanceCm() a blocking function call? If so, I have written about how to do non-blocking cooperative multitasking here: https://stackoverflow.com/a/50032992/4561887.

you could use normal serial communication for communicating between the Arduino and esp32.

@xboxgamer is correct. That might be the quickest solution. Nevertheless, the one controller is definitely capable of doing both things at once. You just have to do the proper multi-tasking and do the work to make it happen.

yes the esp32 can do both at the same time. BTW if you don't know the esp32 has 2 cores so multitasking would be even more easier to achieve with the esp32.

@xboxgamer I believe that serial communication would require two separate boards(?) The ESP32-CAM I am having right now can only be connected to the arduino. Will just alternating the boards (Tools - board) work?

You have to switch com ports on the Arduino ide to recive data from different devices.


text:
Arduino modbus program error
I was trying to extract data from a multi-function meter with RS485 connectivity and I am using Arduino as master, Arduino Uno and multi-function meter are connected via MAX485 module.
I have tried some code but it returns an E2 error which means communication error.
Kindly explain me the program and help me to solve it.
#include <ModbusMaster.h>

#define MAX485_DE 3
#define MAX485_RE_NEG 2
ModbusMaster node;

void preTransmission()
{
  digitalWrite(MAX485_RE_NEG,1);
  digitalWrite(MAX485_DE,1);
}

void postTransmission()
{
  digitalWrite(MAX485_RE_NEG,0);
  digitalWrite(MAX485_DE,0);
}

void setup()
{
  pinMode(MAX485_RE_NEG,OUTPUT);
  pinMode(MAX485_DE,OUTPUT);
  digitalWrite(MAX485_RE_NEG,0);
  digitalWrite(MAX485_DE,0);

  Serial.begin(9600);

  node.begin(1,Serial);
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
}

void loop()
{
  uint8_t resultMain;

  resultMain = node.readHoldingRegisters(0x0100,6);
  Serial.print(resultMain,HEX);

  if (resultMain == node.ku8MBSuccess)
  {
    Serial.print(resultMain);
    Serial.print(node.getResponseBuffer(0x32));
  }
  delay(1000);
}

Can you please let us know the energy meter which you are using?

secure ELITE 300

Can you please use software serial for the communication between meter and arduino because your uart can't be shared simultaneously with both the PC and the meter. That could be the reason why it shows you Communication fail error

can you pls send me the example code becaus i have tried that also but ir shing the same error

"means communication error".  More specifically a timeout.

You have node.begin(1,Serial); where 1 appears to be the modbus slave ID.  Is that in fact the ID of your meter?

yes that's the slave id

See whether or not it makes any difference with your A and B signals swapped.

ya i tried that also but same error my register no is 40100 it is an holding register and its length is 32 bit   its hexa value is 0064 i am i making mistake in this anywhere ?

First, use another Serial port for the RS485; if you have an Arduino Mega, you can just use that instead to minimize code changes since it has multiple hardware UARTs. You'll only need to change node.begin(1, Serial) to something like node.begin(1, Serial2). Next, make sure your hardware connections are correct; in addition to the 2 RS485 connections (A and B), there MUST also be a common GND connection between your Arduino and the meter. Verify your connections by using the RS485 connection to send data between 2 Arduinos, without the Modbus layer. Just send strings back and forth.

source: Stack Exchange

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

sort: votes


text:
Does Linux have software protection on USB? Or has the magic smoke escaped?
I'm making a GUI in Python that will control an Arduino via serial monitor. I have 6 input pins grounded and I'm taking 5V from the board (powered from USB) whilst serial monitoring and everything's going beautifully.
I'm so impressed by all these flickering 0's and 1's that I drop my flying lead straight onto the tiny cap behind the USB connector on the UNO. Everything is definitely not going beautifully now.  My serial data is frozen mid-string.
I try to connect again with my serial monitor software:

Error: Could not open device /dev/ttyUSB0

Power off and on my PC and the Arduino, same result. So, I connect another board a nano this time.
The Arduino Web Editor recognizes that I have connected a Nano, but when I try to upload my code the Arduino Web Editor says this:

avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied

So, I put this in to terminal:
sudo chmod a+rw /dev/ttyACM0
chmod: cannot access '/dev/ttyACM0': No such file or directory
sudo chmod a+rw /dev/ttyusb0
chmod: cannot access '/dev/ttyusb0': No such file or directory

Thought I might have fried my USB but it's still accepting flash drives being plugged in, and I have connected to both front and back USBs with the same results. And I have power-cycled my PC.
So, not sure if I fried my Arduino, (but having 2 Arduinos with the same fault seems unlikely, especially as one was not attached when I dropped the flying lead).
Magic smoke escaped from my PC USB ports, but again it seems unlikely that front and back would be dead whilst allowing USB sticks to communicate.
Is there some kind of software fusing preventing communication that needs to be/can be reset? Or could something have become corrupted maybe?
I'm on Ubuntu 20. If anyone knows of a command I can give that will bring ttyusb0 back to life, that would be great.

If you run dmesg -w and then plug in your board, what new messages show on its output?

/dev/ttyUSB0 is not the same as /dev/ttyusb0.  Take care of the error messages: cannot access '/dev/ttyusb0': No such file or directory. Did you change the users group settings. Enter groups in a shell and check if you are a member of the dialout group. If the user is not a member try sudo adduser $USER dialout. Perhaps the name of device has changed from ttyUSB0 to ttyUSBx. ls -l /dev/tty* lists all devices. Make also sure that the group for device file is dialout. e.g. crw-rw---- 1 root dialout 4, 73 Jan  5 11:02 /dev/ttyUSB1

These occurred to me also, but the way the question is worded makes it difficult to not answer it here or to not put questions in the answer.  The thing about the device group-owner is that their board previously worked.  So, presumably they are already in the dialout group.  Otherwise it would make sense as an explanation for the permission error, though not the "No such file or directory" error.

@timemage There plenty of other possibilities. I just named a few. I also was not correct with the ttyUSB file system entry the user attribute of the file is the user like crw-rw---- 1 pkiefer dialout 188,  0 Jan  5 15:42 /dev/ttyUSB0. So I assume that is controlled by the automatic device creation when the USB/Serial adapter is plugged in. Reconfiguration should be cleared with a reconnect. My fault, sorry.

Yeah, I was hoping they'd come back and clarify some things. As it stands the theories I have would run on for 1000 words or so.  Much it would probably be made irrelevant by some new nugget of information. Their first board is probably dead regardless.

The fact that you're referencing ttyUSB0 tells me you have cheap Chinese clones and not genuine Ardunios.  These are usually based around the CH340 USB interface chip which is notoriously unreliable.
Your UNO is dead.
My supposition is that plugging it in cripples the CH340 driver.  Any other boards that you subsequently plug in can not be recognised because the driver is in a bad state.
To prove this:

Unplug the UNO
Reboot (power cycle) the computer
Plug in the Nano

It should recognise the Nano fine.

Unplug the Nano
Plug in the UNO

It should fail now.

Unplug the UNO
Plug in the Nano

The Nano should now also fail.
If that sequence is correct then the Uno is definitely dead. Throw it away, or at least never plug it in through USB ever again (you could program over serial through the TX/RX pins or using ICSP as if it were a breadboard Arduino though).

The fact im referencing ttyUSB0 tells you i'm using Linux. The UNO is genuine direct from Arduino even got the gold SMT fuse. My UNO isnt dead its running fine now I have fixed the permissions. Thanks though.

@dogfood Genuine Arduinos use /dev/ttyACM0 not /dev/ttyUSB0. Unless it's a very old Arduino UNO (Rev 1) based on the FT232...

its r2 the USB interface is an atmega 8u2, be over a decade old by now (im not in the habit of dragging wires randomly across PCBs haha)

@dogfood I too have the R2. The 8u2 identifies as /dev/ttyACM0 not /dev/ttyUSB0.

running:
sudo usermod -a -G dialout $USER
cleared the issue it was the first time I have used that machine with an Aduino not sure how it was running before with out permissions set up correctly or why it failed when I dropped that 5v, I assume that just reset the board and when it tried to reconnect it failed. Both board and PC all working fine, phew.
Thanks

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


text:
Host a webserver on an ESP32D that has a hyperlink that triggers an Arduino song through a buzzer
I would like to use my ESP32D to create a wireless access point and host an HTML page that has a hyperlink and a few other things on it that triggers an Arduino song (rickroll), and plays it through a buzzer.
I just need to know how to host the webserver and make the trigger hyperlink work, right now the HTML is set to send "trigger" whenever the link is pressed.
HTML file: https://pastebin.com/sGmPPVYG
Arduino-song: https://github.com/robsoncouto/arduino-songs/blob/master/nevergonnagiveyouup/nevergonnagiveyouup.ino

Just to be clear the hyperlink is supposed to make the song play

this might help ... http://www.martyncurrey.com/esp8266-and-the-arduino-ide-part-6-javascript-and-ajax/

this is more current technology ... https://randomnerdtutorials.com/esp32-websocket-server-arduino/

Re “Rick Roll!/a>”: you mean “Rick Roll!”.

This is a partial answer. I assume you already know how to build a Web
server on you ESP32, and how to react to client requests. If not, there
are tutorials available on the Internet. Here I will specifically
discuss the issue of the hyperlink.
You wrote:
Click Here To Trigger The Rick Roll!/a>

Not only the closing tag is incorrect (it should be ), but such a
link is likely not what you want. The semantics of an hyperlink is “go
fetch that resource and display it here, replacing the current page”.
Unless you do have a displayable resource (Web page, image...) on your
server actually named “trigger”, you do not want an hyperlink. You want
a clickable item that may look like an hyperlink and, when clicked,
triggers a request to the server, but without replacing the current
page.
So I would start by replacing the link by a generic container:

Click Here To Trigger The Rick Roll!

Then, style it like a link. I don't quite like the underlining, but you
can add it if you wish:
#trigger {
  color: blue;
  cursor: pointer;
}

Then, within a


text:
how do i connect my Arduino Nano to my Linux Laptop
update:
I uninstalled the portable package of Arduino IDE, completely, and installed the IDE using sudo apt install arduino. yes, I verified that my Nano was plugged in, the status on the bottom right says Arduino Nano w/ ATmega328 on COM1, but sadly the IDE won't explain to me why the Tools > Serial Port section is still unavailable.
Also, the online version doesn't recognize the board even though it's plugged in and configured in the settings to look for a "Nano". I also used a reliable USB Hub I use for my drawing tablet, because that was one of the remedies to troubleshoot the lack of connection, and because the Hub seems to do a lot of good things around here.
end of update
I received an Arduino Nano as a gift a couple months ago and had to place it on a shelf as a mere dust collector, because it was not as easy as I thought it would be to get it working.
I plugged the Nano into my computer with a cable, and attempted to load an example "blink" program and it gives errors saying "no device connected" in the errors.
It does light up and flash, so I know it is receiving power, so how do I specify where the Nano is?
I am familiar with the /dev category and how to use code in Linux, but I don't know how to communicate with the Arduino, as in, know which block device the Nano is in /dev
now that Thomas has brought to my attention the "port" setting in the drop down menus, I just realized that the port is greyed out. that could be a good detail in troubleshooting this issue.

https://www.arduino.cc/en/Guide/Linux#toc6

Hey I just thought of an interesting Idea: what if I can use something like moserial to see a raw output from the Arduino? maybe then, I can see if it is at least talking to the laptop

I'm having the same issue on my installation with Ubuntu 22.04. My Arduino Mega 2560 was working normally, but the Arduino Nano was not recognized.
I managed to solve it with this answer here about "CH34x USB to serial converter chip": https://askubuntu.com/a/1048980/1631587

I have to sadly conclude that this issue posted was for nothing. the board I was using most likely has an underlying defect (of all odds, the 45 boards my teacher was using, he gives me 1 defect board? believable.) rendering the board inoperable. I plugged the board into an entirely different laptop, downloaded and installed a full IDE for it, ran it normally, ran it in Administrator, downloaded and installed the plugin, ran the Online IDE to test that... same exact issues: greyed out serial port settings, and no device detected upon plugging in.
again, I apologize for this being a waste of time. I wished this was not the case and that I could make some pretty cool stuff during this quarantine mess.
I salute to all you programmers out there.... and wish you all good luck in your own endeavors in Arduino.

Is any of this helpful? https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/arduino/readme--arduino.md. If the Arduino runs fine on another computer, I promise you it is capable of running fine on Linux too.

In the Arduino IDE, the mcu will show up in Tools > Port.
Your Arduino Nano will probably be visible at /dev/ttyUSB0 or /dev/ttyUSB1 following whatever is already plugged on USB. Make sure to select it.
Select Nano in Tools > Board.
Last step is  Verify/Compile your code (^R), then Upload (^U).
This link sounds to be a good read to start.

+1
that is a legitimate answer... and that also brings up the kicker. I forgot about the exact errors and issues I was having, because this was months ago, but it's all flooding back to me. the board is next to me now. the green light is steady, and the port drop-down is greyed out/ not clickable. what do I do?

If you have managed your Linux security well, a normal user may not have access to the port where Arduino is plugged into. If so, try from terminal with "sudo arduino". (At least works for me)

in my conclusion, i stated I ran it both normally, and in super user mode (sudo arduino), but gave no results.

I hate to be that person who kicks down every answer and return it with another issue. i am not doing this for attention. I legitimately don't know what is wrong.

actually the more i think of it, i think the cable was not made for data transfer. it was a cable i found in a pile of wires so it may just be a charge cable for something else. I will try to find one guarenteed for data transfer and see if it gives better results


text:
Saving Power :: Reducing Power Consumption
For Arduino Nano 33 IoT, I want to turn off everything except Bluetooth and Wireless since I don't use them.
My question please: Can I switch off / deactivate the IMU sensors completely? If yes, How please?


text:
How to address +HTTPACTION:0,600,0 Not HTTP PDU response
I am using the SIM900A gsm module and trying to connect with my site using a GET request. My issue is that when submitting AT+HTTPACTION=0, I receive a status the response as +HTTPACTION:0,600,0. In this case, the GET request is raised successfully but the response size is 0. In this case, I am not able to fetch a response from the server. The datasheet says the 600 code means "Not HTTP PDU" but I am not aware of how I need to address this. I also sometimes receive code 200, but it is very rare.
following is the response of the AT commands:
AT

OK
AT+COPS?

+COPS: 0,0,"Vi India"

OK
AT+CGDCONT=1,"IP","internet"

OK
AT+CGDCONT=?

+CGDCONT: (1-3),"IP",,,(0),(0)

OK
AT+SAPBR=3,1,"CONTYPE","GPRS"

OK
AT+SAPBR=3,1,"APN","internet"

OK
AT+SAPBR=1,1

OK
AT+SAPBR=2,1

+SAPBR: 1,1,"100.103.109.188"

OK
AT+HTTPINIT

OK
AT+HTTPPARA="CID",1

OK
AT+HTTPPARA="URL","mysite.co.in/newlist.php?K=THS&a=35.97&b=18.84"

OK
AT+HTTPACTION=0

OK

+HTTPACTION:0,600,0
AT+HTTPTERM

OK

Thanks in advance for the support.
Edit I have tried further, I have observed that still, the status code still remains the same 0,600,0 status code. However, when I changed the URL to www.google.com, it returns the expected +HTTPACTION:0,200, xxx status code. Please provide some guidance to get the issue resolve.

How good a signal do you have?

@Majenko  I just checked AT+CSQ returns +CSQ: 31,0, so I understand, signal strength is good enough


text:
ESP8266-01 & Arduino Uno Problem
I am having a problem when I want to run code like this on a Arduino Uno with esp8266-01. It's not working. In serial monitor nothing about esp.

#include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  esp8266.begin(9600);
  esp8266.print("AT+RST");
  delay(1000);
  esp8266.print("AT+CWMODE=1");
  esp8266.print("AT+CWJAP=\"ssisd\",\"pass\"");

}

void loop() {
  // put your main code here, to run repeatedly:

}

But when I load to Arduino empty code and to serial monitor write "AT" it working or I can connect to
my wifi, but only with empty code.

RX is in pin 2 and TX is in pin 3.
And i flashing esp with this Tutorial

It should be a cross-connection like TX -> RX, RX -> TX, your wiring is wrong.

The wiring also doesn't match the code.  The code is using SoftwareSerial on pins 2 and 3 to talk to the ESP8266.  In the drawing it is connected to the hardware serial pins 0 and 1.

to communicate with the esp-01, if you have an empty sketch in Uno, you connect the esp-01 to RX/TX of the USB chip on Uno. this chip is connected with TX to RX pin of Uno and with RX to Tx pin of Uno.

I had before TX and RX conected to pin 2 nad 3 i wrote this under picture. I tryed switch RX and TX still nothing.  I tryed RX in pin 0 and TX in pin 1 and change code, but still nothing.

Try changing baud to 115200 ?? Sometimes it's not 9600, I talk about esp8266.begin ...


text:
Stopping the program after 1 second
I am a Beginner in Arduino Programming.
I am working on a project where I control A DC motor with IR sensor and arduino.
Until here it is fine. But I want the Motor to stop after one second even though the IR sensor detects the Obstacle
Here's My Program
Pin 2- IR Sensor
Pin 4,5,6- Motor
enter code here
//Included Libraries
#include <motor.h>

//MACROS are defined here
Motor Motor1(4, 5, 6);

void setup() {
    //put your setup code here, to run once:

    pinMode(2, INPUT);

}

void loop() {
    //put your main code here, to run repeatedly:

    if(digitalRead(2)) {
        Motor1.moveMotor(2.55*0);
    }
    else {
        Motor1.moveMotor(2.55*100);
    }
}

Can anyone help out in this Program. I Just want the Motor to stop after one second.
Thank you in advance!

First, edit your question, select all of your code, and tap the {} button to format it.

Also, you need to explain your goal more clearly. What should start your motor? The IR sensor? You say "I want the Motor to stop after one second as soon as the sensor detects the Obstacle." I don't understand what that means. You want it to run for at least one second no matter what, and after a second passes, have the IR sensor stop it if it detects and obstacle?

“after one second” alongside “as soon as” is a contradiction.

You show code that reads pin 2. Is that your IR sensor? What do the 2 different motor calls do? Does moveMotor(0) stop the motor, and moveMotor(255) cause the motor to move?

I am sorry, I dint make my point Clear. I edited the Question. Thanks

For doing timed things, learn how to use the millis() functions. Look at the BlinkWithoutDelay example and google for tutorials about that function. When you are understanding how these examples and tutorials work, you will be able to adapt that for your code.

The moveMotor(0) stops the motor and the moveMotor(2.25*100)  makes the motor run.

You improved a few things, but we still can't understand your goal. Please post a complete statement of how you want your sketch to behave. The phrase "I want the Motor to stop after one second as soon as the sensor detects the Obstacle" does not make sense. The "After one second" part is contradicted by the
"as soon as the sensor detects an Obstacle" part.

Does Motor1.moveMotor(2.55*100); delay(1000); Motor1.moveMotor(0); work for you?

look at example sketches in the Arduino IDE ... look at the one named StateChangeDetection

You need to use read the time (millis()) when you start the motor and read it frequently while the motor is running to know when to stop it. You also need to keep track of the sensor, and don't start the motor again until after you've seen the sensor turn off (detect no obstacle). Here is an outline of the logic in psuedo-code; turn this into a detailed loop() function in C++:
if the motor is ON {
  if (millis() - motorStartMillis) > 1000 {
  stop the motor;
}
else if sensor is ON {
  if the sensor was OFF {
    start the motor;
    motorStartMillis = millis();
    sensorWasOn = true;
  }
}
else {      // sensor must be off
  sensorWasOn = false;
}


text:
Problem using Adafruit nRF8001 (BLE) with Ethernet module on Arduino Nano
I'm working on Arduino Nano and I have to use both the Bluetooth LE module Adafruit nRF8001 and ENC28J60 Ethernet module using Ethercard
The idea of the project is to receive data from smartphone via BLE and send it via Ethernet to check with server if the data is valid then the Arduino will send an ON signal out of digital pin 4
But the problem is when uart.begin() (BLE) command invoked. I can no longer use the Ethernet module anymore.
I tried remove the uart.begin() part and Ethernet works fine.
I tried swap uart.begin() to run before ether.begin(). Ethernet cannot be initialized anymore.
Either way, the BLE module seems to work fine and the Arduino can respond to messages from smartphone. But sometimes it returns error code which I cannot understand. And after I pressed reset button on the Arduino it begins to work again.
ACI Command 40
Evt Cmd respone: Error. Arduino is in an while(1); loop

This version doesn't include the data verification part yet. Only send open from smartphone to trigger the Ethernet request and the server will always return you-are-good
Here is my sketch
//BLUETOOTH
#include <SPI.h>
#include "Adafruit_BLE_UART.h"

#define ADAFRUITBLE_REQ 8
#define ADAFRUITBLE_RDY 2
#define ADAFRUITBLE_RST 9

Adafruit_BLE_UART uart = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);
static bool isBTConnected = false;

//ETHERNET
#include <EtherCard.h>
#define ETH_CS 10
#define FORCE_STATIC_IP true

static const byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 };
byte Ethernet::buffer[140];
const char website[] PROGMEM = "192.168.1.104";
const char website_path[] PROGMEM = "/check";

//TIMER AND OUTPUT
#define OUTPUT_PIN 4
#define OUTPUT_ON  LOW
#define OUTPUT_OFF HIGH

static uint32_t timer;
static const uint16_t interval PROGMEM = 5000; // 5 seconds
static bool isOn = false;

//ETHERNET
static void ethCallback (byte status, word off, word len) {
  Serial.println(F(">>> Response"));

  Ethernet::buffer[len + off] = 0;
  Serial.print((const char*) Ethernet::buffer + off);
  Serial.println(F("..."));
  checkPermission(len + off);
}

// check if the server returns exactly string "you-are-good"
void checkPermission (word len) {
  byte c;
  uint16_t i = 0;
  uint8_t found = 0;

  const byte target[] PROGMEM = "you-are-good";
  const uint8_t targetlen PROGMEM = 12;

  do {
    c = Ethernet::buffer[i];

    if (c == target[found]) {
      if (++found >= targetlen) {
        Serial.println(F("OK"));
        outputON();
        return;
      }
    } else {
      found = 0;
    }
  } while (i++ <= len);

  Serial.println(F("NOT OK"));
  outputOFF();
}

void sendRequest() {
  Serial.println();
  Serial.println("<<< REQ ");

  char params[64];
  String prm = "?p=PARAMS_HERE";
  prm.toCharArray(params, 64);

  ether.browseUrl(website_path, params, website, ethCallback);
}

void initEthernet () {
  Serial.print(F("ETH:"));
  if (ether.begin(sizeof Ethernet::buffer, mymac, ETH_CS) == 0)
    Serial.println(F("Failed"));
  else
    Serial.println(F("OK"));

  Serial.print(F("DHCP:"));
  if (FORCE_STATIC_IP || !ether.dhcpSetup()) {
    Serial.println(F("Failed\r\nStatic: "));

    byte ip[] = {192, 168, 1, 12};
    byte gw[] = {192, 168, 1, 1};
    byte dn[] = {192, 168, 1, 1};
    byte ms[] = {255, 255, 255, 0};
    ether.staticSetup(ip, gw, dn, ms);
  } else {
    Serial.println(F("OK"));
  }

  ether.printIp(F("IP:  "), ether.myip);
  ether.printIp(F("GW:  "), ether.gwip);
  ether.printIp(F("DNS: "), ether.dnsip);

  if (!ether.dnsLookup(website)) {
    Serial.println(F("Lookup failed"));
    while (1) {
      digitalWrite(OUTPUT_PIN, HIGH);
      delay(500);
      digitalWrite(OUTPUT_PIN, LOW);
      delay(500);
    }
  }

  ether.printIp(F("SRV: "), ether.hisip);
}

//BLUETOOTH
void initBluetooth () {
  uart.setRXcallback(rxCallback);
  uart.setACIcallback(aciCallback);
  uart.setDeviceName(PSTR("BLEUART")); /* 7 characters max! */
  Serial.print(F("BT:"));
  if (uart.begin())
    Serial.println(F("OK"));
  else
    Serial.println(F("FAILED"));
}

void aciCallback(aci_evt_opcode_t event) {
  switch (event)
  {
    case ACI_EVT_DEVICE_STARTED:
      Serial.println(F("Advertising started"));
      break;
    case ACI_EVT_CONNECTED:
      isBTConnected = true;
      Serial.println(F("Connected!"));
      break;
    case ACI_EVT_DISCONNECTED:
      isBTConnected = false;
      Serial.println(F("Disconnected or advertising timed out"));
      break;
    default:
      Serial.print(F("ACI OPCODE:"));
      Serial.println(event);
      break;
  }
}

void rxCallback(uint8_t *buffer, uint8_t len) {
  uint8_t target_len = 4;
  const char* target = "open";
  uint8_t counter = 0;

  Serial.print(F("Received "));
  Serial.print(len);
  Serial.print(F(" bytes: "));
  for (int i = 0; i < len; i++) {
    char ch = (char)buffer[i];
    Serial.print(ch);
    if (ch == target[counter]) {
      counter++;
    }

    if (counter == target_len) {
      sendRequest();
    }
  }
}

//OUTPUT
void outputOFF() {
  digitalWrite(OUTPUT_PIN, LOW);
  isOn = false;

  Serial.println(F("Locked"));
}

void outputON() {
  timer = millis() + interval;
  digitalWrite(OUTPUT_PIN, HIGH);
  isOn = true;

  Serial.println(F("Unlocked"));
}

//ARDUINO
void setup () {
  pinMode(4, OUTPUT);
  Serial.begin(9600);
  Serial.println(F("BT+ETH"));

  initEthernet();
  initBluetooth();
}

void loop () {
  uart.pollACI();
  ether.packetLoop(ether.packetReceive());

  if (isOn && millis() > timer) {
    outputOFF();
  }

  // debugging commands
  if (Serial.available()) {
    char c = Serial.read();
    if (c == '0') {
      Serial.println(F("Still OK"));
    } else if (c == '1') {
      sendRequest();
    } else if (c == '2') {
      Serial.println(isBTConnected);
    }
  }
}

PS. I don't know if it has something to do with the problem. But the Arduino compiler reports that Global variables use 1,538 bytes (75%) of dynamic memory. I'm planning to get another Arduino model to make sure it works fine after I added data verification part. Don't know if it will help with the problem.

Check the amount of memory you need to run this sketch and library functions. My guess it that you are way over the budget (2K).

Are you toggling the slave select of the SPI slave you are not using LOW?

@MikaelPatel, I'm not sure how to check the memory needed to run the sketch. But my guess is same as yours.

@Avamander, I don't control the SS pin myself. I don't know if the libraries of the two slaves conflicted or not.

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


text:
Pro Micro clone worked fine, now RxLED stays on and can't program it
I have burned out a few Pro Micro clones now. Initially I ran them using a 12VDC external raw power supply but two Pro Micro clones burned out pretty quickly this way. Another thread suggested that the Pro Micro clones use regulators that are not very robust. Since then, I've been using just USB power for my 5V/16MHz Pro Micro clones.
The third clone has been working fine on USB power only. I estimate that I uploaded a sketch I was working on about a dozen times. Suddenly the RxLED stayed lit and I can't upload to it anymore.
When I plug it in, Windows assigns a COM port successfully. The Arduino IDE sees the port and I can select it. This tells me the Pro Micro is not entirely dead. When I enable verbose mode for uploading in the Arduino IDE, here's what I get:
Sketch uses 3,914 bytes (13%) of program storage space. Maximum is 28,672 bytes.
Global variables use 148 bytes (5%) of dynamic memory, leaving 2,412 bytes for local variables. Maximum is 2,560 bytes.
Forcing reset using 1200bps open/close on port COM3
PORTS {COM3, } / {COM3, } => {}
[repeating 19 more times]
Uploading using selected port: COM3
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\Bartman\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.2/avrdude.conf -v -patmega32u4 -cavr109 -PCOM3 -b57600 -D -Uflash:w:C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Users\Bartman\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.2/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .

and after some time:
avrdude: butterfly_recv(): programmer is not responding
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

On my working Pro Micro clone, I get the following after instead:
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% -0.00s

avrdude: Device signature = 0x1e9587
avrdude: reading input file "C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex"
avrdude: writing flash (3914 bytes):

Writing | ################################################## | 100% 0.30s

avrdude: 3914 bytes of flash written
avrdude: verifying flash memory against C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:
avrdude: load data flash data from input file C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:
avrdude: input file C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex contains 3914 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...
avrdude: 3914 bytes of flash verified

avrdude done.  Thank you.

On the now non-functional one, I tried using a jumper from RST to GND, tapping this twice quickly in succession and uploading from the IDE in an attempt to recover the Pro Micro but this doesn't work.
I don't think it's a bootloader problem since the Pro Micro does get a COM port assigned to it but never-the-less, I tried burning a new bootloader from my working Pro Micro. Here's my Pro Micro to Pro Micro wiring:

In the IDE, I've selected:

Board: SparkFun Pro Micro
  Processor: ATmega32U4 (5V, 16 MHz)
  Port: [current COM port of working Pro Micro]
  Programmer: Arduino as ISP

But when I select Tools->Burn Bootloader, I get the following error:
Arduino: 1.6.7 (Windows 10), Board: "SparkFun Pro Micro, ATmega32U4 (5V, 16 MHz)"

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\Bart_S\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.3/avrdude.conf -v -patmega32u4 -cstk500v1 -PCOM6 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xCB:m -Uhfuse:w:0xD8:m -Ulfuse:w:0xFF:m

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Users\Bart_S\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.3/avrdude.conf"

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

avrdude done.  Thank you.

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

Is it permanently damaged? What are the next steps to troubleshoot this Pro Micro clone?

Try re-flashing the bootloader using another Arduino as ISP.

Is avr109/butterfly actually correct for use with a Pro Micro?  Avrdude man page says  "avr109/butterfly uses serial port to communicate with PC"  vs communicating via USB

SparkFun board support package is installed, Pro Micro board selected, 5V/16MHz processor selected. Works fine for my other Pro Micro

On that working setup, is the verbose output any different than above?

Of course it's different: there's a ton more output since it successfully programs. I'll add the working output to the question.

I've bricked my micros plenty of times. It turns out the bootloader mode only lasts about two seconds, instead of seven or eight "like they used to", so it's a bit of a trick to fix them. Squirrled away deep within the Sparkfun pages is this guide. If it works I'll solution-ify this.

I've seen this so called trick but I'm skeptical that the problem is with the bootloader since it boots up and generates a COM port in Windows.

results of trying to burn bootloader have been added to my question

Did you use a capacitor to avoid reset on the Arduino as ISP?

I didn't (I read this was required for the UNO as an ISP host) so I tried it with a 10uF tantalum between RST and GND on the ISP Pro Micro and get the same results.

Here is a solution https://petervanhoyweghen.wordpress.com/2012/09/16/arduinoisp-on-the-leonardo/. Cheers!

looked promising but the information there from 3 1/2 years ago of course no longer works with Arduino IDE 1.6.7 - I get no additional Programmer option in my IDE after adding the new hardware folder etc.

After many hours of unsuccessful bootloader reprogramming attempts, I was able to revive the Pro Micro by trying different timing of double tapping RST while the IDE was compiling/uploading a sketch. After several attempts the Pro Micro suddenly took a sketch and seems to be working now. Not sure how long it will stay this way or how often I will loose it and have to go through these shenanigans again.
Thanks to all for the help.

To make things simpler, try flashing the Pro Micro firmware with another UNO (or compatible) hardware. I prefer an UNO clone with CH340 chip or a pro mini with a FTDI cable. Just to keep things simple.
Flash the UNO with Arduiono as ISP sketch. Use connection guidance from Arduino tutorial:
Using an Arduino as an AVR ISP

Once this is done, AVRDUDE will see the source Arduino as AVR ISP and you can flash the firmware on the target Arduino.
You can also use this post for guidance as well.

I voted this up since I did successfully reprogram the bootloaders of all my Pro Micros using an UNO whereas I was unable to program them with another Pro Micro

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


text:
Is Teensy compatible with the Arduino keyboard library?
I am thinking about buying some Teensy micro-controllers, but I want to know if the teensy are compatible with the arduino keyboard library.

It looks like the Teensy designer uses the standard Arduino mouse and keyboard library:
https://www.pjrc.com/teensy/td_keyboard.html
On another note, I'm sure Teensy is a fine product, but I prefer other open hardware solutions like Pro Micro which can be had on AliExpress.com for  under $4 ea.


text:
Arduino and Raspberry Pi - initiate I2C communication as slave
I would like to interconnect Raspberry Pi and Arduino over I2C.
RPi will act as MASTER while Arduino is SLAVE.
I understand that I2C is designed that only master can send messages to slaves and then wait for responses.
I have sensor connected to Arduino, Arduino check periodically sensor value. My intent is, when sensor value exceed defined limit, inform RPi - send message to it. I want RPi as MASTER, because it also can query Arduino anytime. Can I start communication as SLAVE device?
Is it possible somehow? Do I need to use different bus than I2C?

See answer below.  With pigpio, the Pi does not have to be a master, and  you can have ore than one on the same I2C bus.

You need to use a separate signalling method to alert the Pi that a sensor value is ready to be collected.
This is usually done using an interrupt signal. Your Arduino changes the state of a GPIO pin which is connected to a GPIO pin (through suitable logic level translation as necessary) on the Pi. When the Pi sees that pin change state it requests the data from the Arduino.
It is most common to have the transition from HIGH to LOW as an interrupt signal (aka Active Low) since that allows a simple wired-OR arrangement (open drain GPIOs with a pullup resistor) to allow more than one device to raise the same interrupt.

Yes you can!
The new pigpio library allows the Pi to act as a slave so all devices are equal.
Before this recent release, the Pi was always a master and had to poll the others, interrupting them.
But now you can let the other devices work on their own time schedules without the interrupts.
Here is where you get it

authors: อดิพงษ์ ทองอยู่


text:
Will the L9823 work at 3.3 V with Wemos boards?
Or is it 5 V only?
https://www.st.com/en/automotive-analog-and-power/l9823.html
I see in the data sheet it says under Absolute Maximum:

Supply Voltage:  VDD -0.3 V to 7 V

Then, under Electrical Characteristics:

4.5 V < VDD < 5.5 V; unless otherwise specified.

Is the Electrical Characteristics section just listing values for an example voltage of 5 V, or does the chip need 5 V to work properly?

the datasheet states that the chip may perform an undervoltage reset when supply voltage drops below 3.95 V ... but the undervoltage reset is not not guaranteed until the voltage drops to 2.5 V ... i assume that it is a manufacturing variation .... you would have to screen devices to find one that allows the voltage to drop below 3 V before resetting ... even then, it is unclear if the device would operate at 3.3 V

No. The undervoltage puts it in reset at 3.95V per the ST data sheet. It is a  5v only part with a wide tolerance on VCC. It was designed many years ago as an automotive part. It is a very nice part and performs well.

The Absolute Maximum section in a datasheet describes what will damage a component, or shorten its life span; it does not state the acceptable range of values that will make the component work as expected. It is not a design guideline.
You can deduce from these Absolute Maximum data that a Vdd of 3.3 V will not damage the IC, but not that it will work well at that voltage.
In this case, the datasheet says that all Electrical Characteristics are specified at a Vdd of about 5 V. This by itself does not necessarily mean the IC won't work at lower voltages, but it is a hint.
But, further on in the Electrical Characteristics, it is stated that the IC could reset at any Vdd between 2.5 V and 3.95 V, so the IC will very probably not work reliably at 3.3V.


text:
(Arduino Uno) PWM output (and servo plugged on it) becomes unstable if I use 1Wire on another pin
Unnecessary context but hey I'm guessing you might be interested
Hi, I want to build a PID temperature regulator with a servo that presses on a silicon pipe to adjust the flux of liquid passing through. The liquid is hot beer that must be cooled very quickly from 100°C to 25°C, and it passes through a heat exchanger where also passes in the other direction a constant flux of cold water. The lesser the flux of beer, the colder it becomes. But it is cumbersome to regulate it by hand and I'd like to automate it, because I (think I) can.
Overview of the system
My system is mainly composed of an Arduino Uno, a servo motor (PWM on pin 11), a BS18B20 1Wire temperature probe (on pin 2), and a few buttons. In 'manual' mode I can choose the position of the servo with the buttons and it is very stable.
I also have a buzzer on pin 13 and will add an I2C screen when the core works.
My problem
As soon as I start to request the temperature at regular intervals (like every 200 ms), the servo flickers all the time, which is boring, looks bad, and probably will reduce its life expectancy. I think every time I request a temperature something happens on the PWM, like a brief reset or something, and the servo reacts and then gets back to its original position.
The only power I've tested so far is the USB cable from the computer. In case you wonder, the code is here:
#include <AceButton.h> // https://github.com/bxparks/AceButton
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Servo.h>

Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards

#define ONE_WIRE_BUS 2 // pin for thermometer

using namespace ace_button;

// The pin number attached to the button.
const int BUTTON_SET_PIN = 12;
const int BUTTON_MORE_PIN = 4;
const int BUTTON_LESS_PIN = 0;

const int BUTTON_MODE2_PIN = 5;
const int BUTTON_MODE3_PIN = 7;

const int LED_PIN = LED_BUILTIN;
const int SERVO_PIN = 11;

const int MODE_THERMOMETER = 1;
const int MODE_REGULATOR = 2;
const int MODE_MANUAL = 3;
int mode;

// LED states. Some microcontrollers wire their built-in LED the reverse.
const int LED_ON = HIGH;
const int LED_OFF = LOW;

// Both buttons automatically use the default System ButtonConfig. The
// alternative is to call the AceButton::init() method in setup() below.
AceButton buttonSet(BUTTON_SET_PIN);
AceButton buttonMore(BUTTON_MORE_PIN);
AceButton buttonLess(BUTTON_LESS_PIN);

ButtonConfig modeConfig;
AceButton buttonMode2(&modeConfig);
AceButton buttonMode3(&modeConfig);

// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// variables for tune
float value = 50;
unsigned long tuneStart;
float max = 175;
float min = 10;

void handleModeEvent(AceButton *, uint8_t, uint8_t);

void handleModeEvent(AceButton *button, uint8_t eventType, uint8_t /* buttonState */) {
  switch (eventType) {
  case AceButton::kEventPressed:
    if (button->getPin() == BUTTON_MODE2_PIN) {
      mode = MODE_REGULATOR;
      printMode();
    }

    if (button->getPin() == BUTTON_MODE3_PIN) {
      mode = MODE_MANUAL;
      printMode();
    }
    break;
  case AceButton::kEventReleased:
    if (button->getPin() == BUTTON_MODE2_PIN) {
      mode = MODE_THERMOMETER;
      printMode();
    }
    if (button->getPin() == BUTTON_MODE3_PIN) {
      mode = MODE_REGULATOR;
      printMode();
    }
    break;
  }
}

void printMode()
{
  Serial.print("Mode ");
  Serial.println(mode);
}

void handleButtonEvent(AceButton *, uint8_t, uint8_t);

void setup() {
  Serial.begin(9600);
  while (!Serial); // Wait until Serial is ready - Leonardo/Micro
  Serial.println(F("Test 3 boutons - la suite en 115200 bps"));
  delay(300);

  // servo
  myservo.attach(11);

  // thermal probe
  sensors.begin();
  sensors.setWaitForConversion(false);
  sensors.setResolution(10);

  Serial.begin(115200);
  while (!Serial); // Wait until Serial is ready - Leonardo/Micro
  Serial.println(F("setup(): begin"));

  // Initialize built-in LED as an output.
  pinMode(LED_PIN, OUTPUT);
  pinMode(SERVO_PIN, OUTPUT);

  // Buttons use the built-in pull up register.
  pinMode(BUTTON_SET_PIN, INPUT_PULLUP);
  pinMode(BUTTON_MORE_PIN, INPUT_PULLUP);
  pinMode(BUTTON_LESS_PIN, INPUT_PULLUP);

  pinMode(BUTTON_MODE2_PIN, INPUT_PULLUP);
  pinMode(BUTTON_MODE3_PIN, INPUT_PULLUP);

  buttonMode2.init(BUTTON_MODE2_PIN);
  buttonMode3.init(BUTTON_MODE3_PIN);

  // Configure the ButtonConfig with the event handler, and enable all higher
  // level events.
  ButtonConfig *buttonConfig = ButtonConfig::getSystemButtonConfig();
  buttonConfig->setEventHandler(handleButtonEvent);
  buttonConfig->setFeature(ButtonConfig::kFeatureClick);
  buttonConfig->setFeature(ButtonConfig::kFeatureLongPress);
  buttonConfig->setFeature(ButtonConfig::kFeatureRepeatPress);

  // Configs for the tune-up and tune-down buttons. Need RepeatPress instead of
  // LongPress.
  modeConfig.setEventHandler(handleModeEvent);
  modeConfig.setFeature(ButtonConfig::kFeatureClick);
  // These suppressions not really necessary but cleaner.
  modeConfig.setFeature(ButtonConfig::kFeatureSuppressAfterClick);

  // Check if the button was pressed while booting
  if (buttonMode3.isPressedRaw()) {
    mode = MODE_MANUAL;
    printMode();
  } else if (buttonMode2.isPressedRaw()) {
    mode = MODE_THERMOMETER;
    printMode();
  } else {
    mode = MODE_REGULATOR;
    printMode();
  }
  Serial.println(F("setup(): ready"));
}

long timer_200 = 0;
long timer_1000 = 0;

void loop() {
  // Should be called every 4-5ms or faster, for the default debouncing time of ~20ms.
  buttonSet.check();
  buttonMore.check();
  buttonLess.check();
  buttonMode2.check();
  buttonMode3.check();

  // every 200 ms
  long now = millis();
  if (now > timer_200 + 200) {
    timer_200 = now; // to reinit timer
    if (mode == MODE_MANUAL) {
      myservo.write(value);
    }
  }

  // every 1s
  if (now > timer_1000 + 1000) {
    timer_1000 = now; // to reinit timer
    // get temperature requested last time
    Serial.print("Temperature for Device is: ");
    Serial.println(sensors.getTempCByIndex(0));
    // and request a new one
    sensors.requestTemperatures(); // Send the command to get temperatures
    if (mode == MODE_THERMOMETER) {}
  }
}

// The event handler for both buttons.
void handleButtonEvent(AceButton *button, uint8_t eventType, uint8_t buttonState) {
  switch (eventType) {

  case AceButton::kEventClicked:
    if (button->getPin() == BUTTON_MORE_PIN) {
      value = value * 1.01;
      if (value > max) {
        value = max;
      }

      Serial.println(value);
    }

    if (button->getPin() == BUTTON_LESS_PIN) {
      value = value * .99;
      if (value < min) {
        value = min;
      }
      Serial.println(value);
    }

    if (button->getPin() == BUTTON_SET_PIN) {
      Serial.println(F("set"));
    }
    break;

  case AceButton::kEventLongPressed:
    if (button->getPin() == BUTTON_SET_PIN) {
      Serial.println(F("set long press"));
    }

    if (button->getPin() == BUTTON_MORE_PIN || button->getPin() == BUTTON_LESS_PIN) {
      tuneStart = millis();
    }
    break;
  case AceButton::kEventRepeatPressed:

    if (button->getPin() == BUTTON_MORE_PIN) {
      tuneUp();
    }

    if (button->getPin() == BUTTON_LESS_PIN) {
      tuneDown();
    }
    break;
  }
}

void tuneUp() {
  unsigned long duration = millis() - tuneStart;
  float ratio = 1 + (0.00001f * 4 * duration);
  value = value * ratio;
  if (value > max) {
    value = max;
  }
  Serial.println(value);
}

void tuneDown() {
  unsigned long duration = millis() - tuneStart;
  float ratio = 1 - (0.00001f * 4 * duration);
  value = value * ratio;
  if (value < min) {
    value = min;
  }
  Serial.println(value);
}

It's still quite a prototype.
What could cause this and how can I prevent it?

What are you using for your controller?  Some devices don't have hardware PWM and even some that do use "bit banging" if you don't choose the correct pin.

I'm sorry, I forgot the main component, the arduino Uno. I've edited my question.

I suspect the 1Wire libary disables (and enables) interrupts when it sees fit. This will cause servo "hickups" because the servo library uses interrupts.
If I'm right then your best bet is using a servo library that doesn't use interrupts. I always use a hardware PWM library for driving servos, so I have no servo library recommendations to make, but maybe somebody else has.
Also: you are doing a Serial.begin() twice, and the variables you use for timing (using millis()) should be unsigned long, not long.

Thanks, this is very interesting ! I really don't need the Servo library, outputting a regular PWM will likely work seamlessly for my application. I'll try that tomorrow and let you know.

Is that a problem to use Serial.begin twice ? I do it on purpose, because I like to know what is currently loaded on a given arduino board, so I start by a message in 9600 bps with the name of the sketch and the speed of the next messages, then I reinit with the said speed. It seems to work :)

It's not necessarily a problem, but why would you, if the receiving application apparently can handle the higher baudrate anyway? If you do it on purpose though, it's fine.

The idea was to always start at 9600 as a standard whichever sketch I upload, and then choose freely the communication speed. Otherwise I may not remember later on what speed I have to set in the console to communicate with it. It's quite a fresh idea I had, I don't know if it's gonna be that useful.

You were very probably right. I made a custom code to output the signal I needed, which is actually not PWM, see https://forum.arduino.cc/index.php?topic=530091.0 and it solved the problem. Thanks a lot !

You are most welcome. A servo signal is PWM, though, usually left-aligned, and with a fixed frequency, but let's not discuss that now.


text:
24v LED strip with common anode?
I have a 5m strip of 24v tunable white LEDs and I'm trying to figure out what I need set it up. There's a pad for V+ and then one for brightness and one for warmth. If I plug the V+ in V+ on a 24v supply and the two others to V-, the whole thing lights up full intensity. The strip draws 16 Watts per meter (80 for the whole thing). As I understand it, you vary the two anodes by varying the resistance to ground. I've seen some instructions that this can be done with PWM pins, but I'm assuming that given the voltage and current, no arduino or similar can handle that much. Do I need transistors then? What specs do I look for to understand the limitations?

please post a link to the product datasheet

I linked the product. It doesn't actually have a straightforward data sheet but it has all the specs.

There's a pad for V+ and then one for brightness and one for warmth. ... that is not quite correct ... the pads are V+, W and C ... W controls the warm color LEDs and C controls the cold color LEDs ... you will need a transistor to drive each of the two channels ... find a tutorial about driving RGB LED strips ... instead of three colors, you have only two colors

Your strip has 2 LEDs with different color temperature directly besides at the same spot for every element of the strip. So the adjusting of the overall color temperature is done by changing the relative brightness of both LEDs. If the LED with the warmer light is brighter, the overall color temperature will also be warmer. Common Anode means, that V+ is the connected to the positive pin (anode) of both LEDs, so it has to be connected to +24V. The electrical circuit is completed by connecting the pins W and C (Warm and Cold) to ground. To control the individual brightness of the warm and cold LED groups, you have to use PWM.
You are right, that an Arduino cannot handle currents this big. You need a transistor for this. I would suggest using a MOSFET, since this is the easiest and most efficient possibility. By one MOSFET for every channel (Warm and Cold), which is capable of handling the needed power (Important! Or you will fry the MOSFET). Also it should be a logic level MOSFET, that is well in saturation of the gate voltage for the output voltage of your Arduino. Connect the MOSFETs Drain pin to the channel on the strip, the Source pin to ground of your power supply and the Gate pin to a PWM pin of the Arduino. Also connect the ground of the power supply with the ground of the Arduino.
Now you can control the brightness of the Warm and of the Cold LEDs by adjusting the PWM duty cycle with the Arduino.

Or rather, by adjusting the ratio of the duty cycles between the warm and cool LED sets. If you set the cool pin to 100% and the warm pin to 0%, you'll get all cool light (100:0) If you set both to 100%, you'll get a 50/50 mix of warm and cool light (ratio of 1:1 between duty cycles)

So, presumably if I tie warm straight to ground and just air gap cool, I'd get warm

@jiggy Yes, thats correct


text:
SIM7600 A-H not responding directly when connected through pins
I am working on a project which utilizes three components:

Arudino Pro Mini(5v)
Breakout SIM7600 A-H from AND technologies
9V Battery (connected to RAW and GND on the Arduino board)

I am trying to communicate through the device using the pins provided on the SIM board, which unfortunately is not successful.
I am able to connect to the board directly using an usb-c cable. After installing the right drivers, I am able to communicate with the board using AT commands from my Windows PC.
However, I want to be able to send AT commands through the arduino. The set up looks like this:
I connect the following pins of arduino mini and SIM 7600A-H.

SIM 7600 TXD --> Arduino Pin 2
SIM 7600 RXD --> Arduino Pin 3
SIM 7600 Supply -->  5V
SIM 7600 GND -->  GND

The code that I am using, I tried it with every possible baud rate:
#include <SoftwareSerial.h>

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

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

After sending an AT command, there is no response, the module has both LED's on, indicating that it is up and running.

please describe the 9 V battery

First a warning: Have you read the datasheet from the link above. The TX and RX pins of the SIM 7600 are 3.3V and your mini is a 5V one. The worst case scenario is that the mini killed the RX pin hardware. The best case failure scenario is that the SIM TX Pin has not enough volts to safely signal a HIGH Level to the mini RX pin.

If you powered the SIM over the VCC of the mini then you have only 150mA current available (for the mini and the SIM module). That would be a problem. The SIM module needs a peak current of about 2A (I got the value from other forums, I found no reliable specification).  That is not drawn for a long time only for sending. But I fear the 150 mA would also not suffice for the standby mode.

If you could connect over USB you know the Baud rate to the SIM module. The Baud rate of the mini's connection to the PC  must be set to the rate that you selected in the Arduino IDE or the Serial Terminal you use. There is no need to try out others.

About your code: I personally would move the mySerial.begin(115200); right below the  Serial.begin(115200);. Just to keep and see them together. The while (!Serial) { statement could be a problem. As written in the comment beneath the statement, it is only necessary for native USB connection but on a pro mini you have a 328P MCU that is connected to a USB to Serial converter and not to a native USB. Perhaps it blocks and your code is not executed.

Sorry for the late response and thank you so much for your thorough answer! I took your advice but unfortunately no success! I have implemented a level logic converter, and changed the code. I checked and the right voltages appear for both the module and the board. The module still does not respond although it works when connected through usb

The SIM7600 UART interface works with 1.8 levels:

I'm guessing that the AND board has a level shifter from 3.3 to 1.8 to work with the 7600. Since your Arduino Por Mini is a 5V board your UART levels must be at 5V too, try adding a voltage divider to bring down the UART to 3.3V.
Also try lowering the SIM7600 baudrate, the software_serial library doesn't work good with high speeds.

Did you ever get your Mini Pro to communicate with the SIM7600?  I am now experiencing this using a SIM7600x core board(3.3v ttl).  Other 5V MCUs work perfect (with level shifter) with the SIM7600, but using a 3.3V Pro Mini directly does not.

Is your issue resolved? If not...
I'm using the same module and having the same problem.
Jump the resistors on the R and T pins on the module, they seem to be introducing high impedance on the line. After doing that on my module, the UART worked.
Now my problem now is the module is sending some weird characters, maybe my baud rate is not same or etc, still under investigation.

After further investigation, use shorter wires or connections between your module and arduino or mcu.


text:
delay() problem for 74HC595 and 7-segment
I'm trying to run a 3-digit 7-segment using single 74HC595 based on Arduino. But I have a serious problem with delay() function. When I want to count from 000 to 999 with delay(1000), this delay function causes all digits to be off! My code is as below and I uploaded a video Click Here to understand my purpose. This problem can affect some applications like reading the temperature of DS12b20 which requires a delay itself.
//                 2        1         0
//               ----      ----      ----
//              |    |    |    |    |    |
//               ----      ----      ----
//              |    |    |    |    |    |
//               ----      ----      ----

int latch = 8; //74HC595  pin STCP
int clock = 9; //74HC595  pin SHCP
int data = 10; //74HC595  pin DS

// Each annode pin (for those that don't know think of it as an on switch when it's assigned HIGH)
int dig1 = 2; // digit0
int dig2 = 3; // digit1
int dig3 = 4; // digit2
int digit[4]={dig1, dig2, dig3};

int timer=3;
// these are bits to make the 8 bit byte accepted by the segment display the 9th is the demical point
// 0-9 then invald numbers
byte table[] = {
  B00111111, B00000110, B01011011, B01001111, B01100110,
  B01101101, B01111101, B00000111, B01111111, B01101111, B01111111
};

void setup(){
  pinMode(latch, OUTPUT);
  pinMode(clock, OUTPUT);
  pinMode(data, OUTPUT);
  pinMode(dig1, OUTPUT);
  pinMode(dig2, OUTPUT);
  pinMode(dig3, OUTPUT);
}

//this sends the data to the digit
void RunNum(int num, int SelectDigit){
  digitalWrite(latch, LOW);
  shiftOut(data, clock, MSBFIRST, table[num]);
  digitalWrite(latch, HIGH);
  digitalWrite(digit[SelectDigit], LOW);
  delay(timer);
  digitalWrite(digit[SelectDigit], HIGH);

}

//main program
void loop() {
  for (int i=0; i<10; i++){
    for (int j=0; j<10; j++){
      for (int k=0; k<10; k++){
        RunNum(k, 0);
        RunNum(j, 1);
        RunNum(i, 2);
        delay(1000);  //  <====    This line affects the project
      }
    }
  }
}

I updated my code (only void loop()) as below using millis(). You can watch the results (Click Here). But, the delay problem has not been solved so far!
const long interval = 1000;   //  1000 ms = 1 s
long previousMillis = 0;
unsigned long currentMillis=0;

//main program
void loop() {
  for (int i=0; i<10; i++){
    for (int j=0; j<10; j++){
      for (int k=0; k<10; k++){
        while (currentMillis - previousMillis < interval){
          currentMillis=millis();
          RunNum(k, 0);
          RunNum(j, 1);
          RunNum(i, 2);
        }
        previousMillis = currentMillis;
      }
    }
  }
}

So then don't use delay(). To do timed things, you need to learn a non-blocking coding style, like in the BlinkWithoutDelay example via the millis(). Look a the example and at tutorials about millis(). When you fully understand them, you will be able to replace the delay with non-blocking code

Thanks @chrisl. I already used of millis function. But it's useful for digital counting only like for making a digital clock. It's too bad for other applications like for DS18b20 temperature.

@soheil What are you talking about? I don't see, why millis()should be too bad to use here. delay() also just uses millis()in the background. And I also don't see how it should affect the temperature measurement. It is absolutely the way to go for handling the 1s delay there.

@chrisl This is a good question. Suppose that you have a DS18B20 temperature sensor. The sensor response time is about 0.5 sec (may be up to 0.75 sec). If you want to display it using 74HC595, during this time (exactly like a delay) the 7-segments are turned off! and after that they are turned on to display temperature. This appears like a flash (carefully watch the uploaded video). Some chips like MAX7219 doesn't interrupt the output when they don't have input (they run previous commands) while it seems that 74HC595 continuously needs the commands to keep the its output active.

@soheil So your problem is with the temperature sensor. Then you need to show a code, that really uses your temperature sensor. Currently you are asking about the 1s delay, for which Juraj provided a fitting answer. We can only understand how that might collude with the temp sensor, when we see the temp sensor code.

The 74HC595 doesn't need constant commands. If you stop shifting data out to it, it will keep the current state of the outputs. Though since you are reusing the same pins of it for all three digits, you need to constantly provide fitting data for each digit. That is not a property of the shift register, but of your circuit, which forms a matrix

If the 74HC595 sensor library you're using has delay() functions in it of more than a few milliseconds, you're going to have to modify your library function that reads the temp sensor to be non-blocking. (by following the model of blinkWithoutDelay.)

Either that or you are going to need to rewire your display to latch all 3 digits at once, and keep the whole display lit at once, or use a display driver that can multiplex all 3 digits automatically for you. You could use a MAX7221 for example. You'd feed the digits you need it to display using a serial interface, then read a new value from your temp sensor and feed the new value to the display driver. The display driver would continue to display the old value until the new value was sent.

@chrisl Thank you so much. But the temperature sensor is just one example which requires delay. Delay in my code simulates the raised problem of such usages. I can just say that how to avoid flashing in displaying numbers in such applications?

@chrisl Exactly. I think that one of the reasons is that in my code: first it should active the first digit and display its number and then inactive it and active the second digit and display its number and then inactive it and so on. This process should continuously be done to show all numbers without flashing. But, any delay (may be more than 20 ms) stops this process (of course for our eyes) and causes flashing in display. How do you think?

Thanks @Duncan-C. The delay is for sending and receiving data and can be up to 750 ms. MAX7219 and MAX7221 are great. Your idea is rewiring. How?

Remove the 74HC595 from your project and replace it with a Max7221 instead. The 7221 is able to drive up to 8 7-segment characters (plus decimals, for a total of 8 segments per character.) It is driven with a serial interface, so you send it commands to display values. A quick Google search reveals Arduino libraries for using it.

With the displays which use shift register to light multiple seven segment digit blocks, the register lights up only one digit at a time. The illusion of multiple digits lit is created by fast switching the digits in round. Small delays in this cause the number to look dim, larger delays create flickering and long delays show only one digit lit. So a sketch handling this type of display must run without delays.
In this type of sketch, everything must be handled without delays, so if some sensor requires a delay, start the reading and a millis timer and after the elapsed time read the result.
There are displays using specialized chips, for example TM1637D, which handle the seven segments even if your sketch stops in delay.

adoption of the BlinkWithoutDelay basic example for your algorithm:
unsigned long previousMillis = 0;
const long interval = 1000;
int i, j, k;

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

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    k++;
    if ( k == 10) {
      k = 0;
      j++;
      if (j == 10) {
        j = 0;
        i++;
        if (i == 10) {
          i = 0;
        }
      }
    }
    Serial.print(i);
    Serial.print(j);
    Serial.println(k);
  }
}

Thank you so much. But this isn't the correct answer! I already tried it. Please, carefully read the question.

Just a note, there is no temperature sensor or library included for one in the code presented.  For the question as presented this is the correct answer.  If there is some problem where your temperature sensor takes too long to read then that is a separate issue.  That's not the same as having a delay in your code.  Instead of trying to code around that time, fix the library for the sensor so it doesn't take so long.

delay() just simulates the required delay of such sensors. In real applications, this delay causes the flashing in display.

@soheil, I enhanced the answer

Thank you. I think changing chip is the best idea. I even used of two 74HC595 combined with ULN2803. But its result became worst. In fact, some segments of an inactive digit were a little bright!!!!!! 74HC595 can't handle the delay().

The use of millis() is suitable for digital clock, timer, ...

@soheil, with millis we do timed events. see this sketch https://github.com/jandrassy/lab/blob/master/KitchenTimer/KitchenTimer.ino

I updated your code based on millis().

@soheil, that code was wrong. you can't embed the timer inside 3 for loops. the main loop must run

I ran that and it worked fine. No problem.

@soheil, if that is all what your sketch should do, then it is ok

In loop() as you've shown it in your code, you can move RunNum(i,2); down to outside of the 'j' and 'k' loops. Likewise you can move RunNum(j,1); down to outside of the 'k' loop. This won't fix your problem but it will speed up each update of the display.
Then, know that you can tell one (or all) of your DS18B20 sensors to start a temperature conversion without waiting for the conversion to finish. Then you use millis() to tell you when the conversion is done, and you can get the result very quickly. Some libraries provide the amount of time you need to wait for the conversion; some provide some kind of an "is it done yet?" boolean function. Either one of those will let you remove the 'wait til done' delay.
Update:

This strategy doesn't work properly!...

Sorry if I missed something - it looked like there were opportunities to optimize there.

About temperature sensor, I should say that reading the temperature takes about 750 ms itself. In other words, it acts as a delay and causes turning off the display for 750 ms.

It is temperature measurement and conversion to a 12-bit result - which takes place entirely within the DS18B20 sensor itself - that takes 750ms. The Arduino is not involved in that process and could be doing other tasks such as maintaining your display during that time.
Reading the temperatures, once the conversion is done, is much quicker.  If your library doesn't provide the ability to start a conversion and return, without waiting for the results, and separate entry to read the results, look for a library that does.
Update:
Miles Burton's Arduino-Temperature-Control-Library provides a 'wait for conversion' flag that you can set false so ::requestsTemperatures() will return immediately, and an ::isConversionComplete() call to check whether the data is ready. (Of course, knowing that the device takes 750ms
for a 12-bit conversion, you could just as well use millis() to decide that.)

Thank you. This strategy doesn't work properly! because if you do that, digits 1 and 2 are turned off until digit 0 counts from 0 to 9. Then digit 1 quickly displays number 1 and is turned off and again digit 0 counts from 0 to 9 and so on.

About temperature sensor, I should say that reading the temperature takes about 750 ms itself. In other words, it acts as a delay and causes turning off the display for 750 ms. As another example, suppose that you need to call a php script using ESP8266 D1 Mini (it can similarly be programmed using Arduino IDE) and then display some returned numbers using 74HC595. Calling a php script may take over 15 s and during this time all digits are turned off.


text:
Mega: attachInterrupt on pin 18/19/20/21 not working
Task:
I'm trying to create a fan-control with the arduino mega. I'm generating a PWM signal on pin 6 and 7 and want to use interrups to measure the rpm of the fans.
Problem:
On pin 2 and 3 everything wors fine, but I cannot get it working on any of pins 18-21. The numbers are jumping around wildly. BUT: The numbers are correct on 0% and 100% duty!
What I've aleady tried:

Changed my timer from 1 to 4 (currently it's 4)
Replaced the display to get rid of U8g2lib.
Changing connection order of the signal cables (and thus the connected fan).
Check the signal with an digital oscilloscope (looks fine on all ports)
Set the global ISR variables to volatile and byte to prevent update hazards.
Bang my head on the table.

Nothing solved my problem. What am I missing?
    #include <Arduino.h>
    #include <U8g2lib.h>
    #include <Bounce2.h>

    #ifdef U8X8_HAVE_HW_SPI
    #include <SPI.h>
    #endif
    #ifdef U8X8_HAVE_HW_I2C
    #include <Wire.h>
    #endif

    U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);

    #define PIN_CONTROL_S 6
    #define PIN_CONTROL_L 7
    #define PIN_SENSE_1 18
    #define PIN_SENSE_2 19
    #define PIN_SENSE_3 3
    #define PIN_SENSE_4 2
    #define PIN_BUTTON 22

    #define UPDATE_CYCLE 1000 // Refresh interval of the display/measurement.
    #define SIGNAL_PER_RND 2  // 2 Signals per revolution
    #define DUTY_INC 10       // Increate of the duty in % per button press
    #define PWM_MAX 320       // PWM mode counts up 320 then down 320 counts (25kHz)
    #define lineOffset 10     // Offset (y) per line on display

    word duty = 0;  // 0-100 duty cycle
    word dutyS = 0; // 0-320 = 0-100% duty cycle for small fans
    word dutyL = 0; // 0-320 = 0-100% duty cycle for large fans

    volatile byte counterFan1 = 0;
    volatile byte counterFan2 = 0;
    volatile byte counterFan3 = 0;
    volatile byte counterFan4 = 0;

    unsigned long lastDraw = 0;

    Bounce btnBouncer = Bounce(PIN_BUTTON, 50);

    void setupPwm() {
        // Steuerung
        pinMode(PIN_CONTROL_S, OUTPUT);
        pinMode(PIN_CONTROL_L, OUTPUT);

        // Sensoren
        pinMode(PIN_SENSE_1, INPUT_PULLUP);
        pinMode(PIN_SENSE_2, INPUT_PULLUP);
        pinMode(PIN_SENSE_3, INPUT_PULLUP);
        pinMode(PIN_SENSE_4, INPUT_PULLUP);

        // Clear timer register
        TCCR4A = 0;
        TCCR4B = 0;
        TCCR4C = 0;
        TCNT4 = 0;

        TCCR4A |= _BV(WGM41);  // Set PWM mode, phase correct. TOP is ICR1.  (Mode 10)
        TCCR4B |= _BV(WGM43);  // Start BOTTOM, TOP from OCR1x to OCR1x.

        TCCR4B |= _BV(CS40);   // Prescaler 1:1

        TCCR4A |= _BV(COM4A1); // High output OC1A on compareMatch when up-counting / low when down-counting
        TCCR4A |= _BV(COM4B1); // High output OC1B on compareMatch when up-counting / low when down-counting

        OCR4A = dutyS;         // set initial duty
        OCR4B = dutyL;         // set initial duty

        ICR4 = PWM_MAX; // TOP for TCNTx. 320 => @16Mhz CPU -> 25kHz PWM
    }

    void setupDisplay() {
        u8g2.begin();
        u8g2.setFont(u8g2_font_6x10_tf);
        u8g2.setFontRefHeightExtendedText();
        u8g2.setDrawColor(1);
        u8g2.setFontPosTop();
        u8g2.setFontDirection(0);
    }

    void attachInterrups() {
        attachInterrupt(digitalPinToInterrupt(PIN_SENSE_1), isrFan1, RISING);
        attachInterrupt(digitalPinToInterrupt(PIN_SENSE_2), isrFan2, RISING);
        attachInterrupt(digitalPinToInterrupt(PIN_SENSE_3), isrFan3, RISING);
        attachInterrupt(digitalPinToInterrupt(PIN_SENSE_4), isrFan4, RISING);
    }

    void detachInterrups() {
        detachInterrupt(digitalPinToInterrupt(PIN_SENSE_1));
        detachInterrupt(digitalPinToInterrupt(PIN_SENSE_2));
        detachInterrupt(digitalPinToInterrupt(PIN_SENSE_3));
        detachInterrupt(digitalPinToInterrupt(PIN_SENSE_4));
    }

    void setup() {
        setupDisplay();
        setupPwm();
        attachInterrups();

        pinMode(PIN_BUTTON, INPUT_PULLUP);
    }

    void draw(void) {
        char output[22]; // One line of the display can show 21 characters.
        float uPerSekS1 = counterFan1; // * 60000 / measureDuration / SIGNAL_PER_RND;
        float uPerSekS2 = counterFan2; // * 60000 / measureDuration / SIGNAL_PER_RND;
        float uPerSekL1 = counterFan3; // * 60000 / measureDuration / SIGNAL_PER_RND;
        float uPerSekL2 = counterFan4; // * 60000 / measureDuration / SIGNAL_PER_RND;
        int y = 0;

        sprintf(output, "Duty    :    %3d", duty);
        u8g2.drawStr(0, y, output);

        y += lineOffset;
        sprintf(output, "U/sec S1: %6d", (int) uPerSekS1);
        u8g2.drawStr(0, y, output);

        y += lineOffset;
        sprintf(output, "U/sec S2: %6d", (int) uPerSekS2);
        u8g2.drawStr(0, y, output);

        y += lineOffset;
        sprintf(output, "U/sec L1: %6d", (int) uPerSekL1);
        u8g2.drawStr(0, y, output);

        y += lineOffset;
        sprintf(output, "U/sec L2: %6d", (int) uPerSekL2);
        u8g2.drawStr(0, y, output);
    }

    void measure() {
        unsigned long measureDuration = millis() - lastDraw;
        if (measureDuration >= UPDATE_CYCLE) {
            // Deactivate interrupt while we are calculating
            detachInterrups();

            u8g2.clearBuffer();
            draw();
            u8g2.sendBuffer();

            // reset state
            counterFan1 = 0;
            counterFan2 = 0;
            counterFan3 = 0;
            counterFan4 = 0;
            lastDraw = millis();

            // Reactivate interrupt
            attachInterrups();
        }
    }

    void loop() {
        measure();
        btnBouncer.update();
        if (btnBouncer.fell()) {
            // Button was pressed. Increase duty.
            if (duty > 90) {
                duty = 0;
            } else {
                duty += DUTY_INC;
            }

            dutyS = duty * PWM_MAX / 100;
            dutyL = duty * PWM_MAX / 100;

            OCR4A = dutyS;
            OCR4B = dutyL;
        }
    }

    void isrFan1() {
        counterFan1++;
    }

    void isrFan2() {
        counterFan2++;
    }

    void isrFan3() {
        counterFan3++;
    }

    void isrFan4() {
        counterFan4++;
    }

Edit:
I've tried my best to create a readable circuit diagram. The 4-pin connectors represent the fans.

Ok, maybe it is an electronical issue? I just double checked my statements and connected the oscilloscope simultaneously to the arduino and it looked like the osci is stabilizint the results...
I'm using a 5KΩ pull up resistance. Is that ok?

I can't understand what the duty cycle has to do with reading the pulses. What happens if you unplug 6 and 7 and turn the fans with your hand? Are you sure the 8 bit counters do not overflow when the fan turns fast?

@EdgarBonet If i unplugg 6/7 the fans will go up to 100%. I've forgotten to mention I'm using 4pin PC fans. They are connected to 12V and get regulated by the 25KHz PWM I'm generatingion the third pin. The fourth pin is the signal pin with two signals per round.

@EdgarBonet  ...and 8 bit are not overflowing. The measurement interval is currently 1 sec, and I get up to 50 signals per measurement cycle.

what is wired to interrupt pins and how?

Ok, I did not solve the problem regarding pin 18-21, but I found an other solution: using PinChangeInterrupts and the PinChangeInterrupt libary
I did not change anything about my hardware setup, excep moving the wires from pin 18/19 to A8/A9. I've changed my code to use PinChangeInterrups for two of the fans, maybe I'll change all 4 fans.
Here is the new code:
#include <Arduino.h>
#include <U8g2lib.h>
#include <Bounce2.h>
#include <PinChangeInterrupt.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);

#define PIN_CONTROL_S 6
#define PIN_CONTROL_L 7

//#define PIN_SENSE_1 18
//#define PIN_SENSE_2 19
#define PIN_SENSE_1 A8
#define PIN_SENSE_2 A9

#define PIN_SENSE_3 3
#define PIN_SENSE_4 2
#define PIN_BUTTON 22

#define UPDATE_CYCLE 1000 // Refresh interval of the display/measurement.
#define SIGNAL_PER_RND 2  // 2 Signals per revolution
#define DUTY_INC 10       // Increate of the duty in % per button press
#define PWM_MAX 320       // PWM mode counts up 320 then down 320 counts (25kHz)
#define lineOffset 10     // Offset (y) per line on display

word duty = 0;  // 0-100 duty cycle
word dutyS = 0; // 0-320 = 0-100% duty cycle for small fans
word dutyL = 0; // 0-320 = 0-100% duty cycle for large fans

volatile byte counterFan1 = 0;
volatile byte counterFan2 = 0;
volatile byte counterFan3 = 0;
volatile byte counterFan4 = 0;

unsigned long measureDuration;
unsigned long lastDraw = 0;

Bounce btnBouncer = Bounce(PIN_BUTTON, 50);

void setupPwm() {
    // Steuerung
    pinMode(PIN_CONTROL_S, OUTPUT);
    pinMode(PIN_CONTROL_L, OUTPUT);

    // Sensoren
    pinMode(PIN_SENSE_1, INPUT_PULLUP);
    pinMode(PIN_SENSE_2, INPUT_PULLUP);
    pinMode(PIN_SENSE_3, INPUT_PULLUP);
    pinMode(PIN_SENSE_4, INPUT_PULLUP);

    // Clear timer register
    TCCR4A = 0;
    TCCR4B = 0;
    TCCR4C = 0;
    TCNT4 = 0;

    TCCR4A |= _BV(WGM41);  // Set PWM mode, phase correct. TOP is ICR1.  (Mode 10)
    TCCR4B |= _BV(WGM43);  // Start BOTTOM, TOP from OCR1x to OCR1x.

    TCCR4B |= _BV(CS40);   // Prescaler 1:1

    TCCR4A |= _BV(COM4A1); // High output OC1A on compareMatch when up-counting / low when down-counting
    TCCR4A |= _BV(COM4B1); // High output OC1B on compareMatch when up-counting / low when down-counting

    OCR4A = dutyS;         // set initial duty
    OCR4B = dutyL;         // set initial duty

    ICR4 = PWM_MAX; // TOP for TCNTx. 320 => @16Mhz CPU -> 25kHz PWM
}

void setupDisplay() {
    u8g2.begin();
    u8g2.setFont(u8g2_font_6x10_tf);
    u8g2.setFontRefHeightExtendedText();
    u8g2.setDrawColor(1);
    u8g2.setFontPosTop();
    u8g2.setFontDirection(0);
}

void attachInterrups() {
//    attachInterrupt(digitalPinToInterrupt(PIN_SENSE_1), isrFan1, RISING);
    attachPCINT(digitalPinToPCINT(PIN_SENSE_1), isrFan1, RISING);

//    attachInterrupt(digitalPinToInterrupt(PIN_SENSE_2), isrFan2, RISING);
    attachPCINT(digitalPinToPCINT(PIN_SENSE_2), isrFan2, RISING);

    attachInterrupt(digitalPinToInterrupt(PIN_SENSE_3), isrFan3, RISING);
    attachInterrupt(digitalPinToInterrupt(PIN_SENSE_4), isrFan4, RISING);
}

void detachInterrups() {
//    detachInterrupt(digitalPinToInterrupt(PIN_SENSE_1));
    detachPinChangeInterrupt(digitalPinToPCINT(PIN_SENSE_1));

//    detachInterrupt(digitalPinToInterrupt(PIN_SENSE_2));
    detachPinChangeInterrupt(digitalPinToPCINT(PIN_SENSE_2));

    detachInterrupt(digitalPinToInterrupt(PIN_SENSE_3));
    detachInterrupt(digitalPinToInterrupt(PIN_SENSE_4));
}

void setup() {
//    cli();
    setupDisplay();
    setupPwm();
    attachInterrups();

    pinMode(PIN_BUTTON, INPUT_PULLUP);
//    sei();
}

void draw() {
    char output[22]; // One line of the display can show 21 characters.
    float uPerSekS1 = counterFan1 * 60000 / measureDuration / SIGNAL_PER_RND;
    float uPerSekS2 = counterFan2 * 60000 / measureDuration / SIGNAL_PER_RND;
    float uPerSekL1 = counterFan3 * 60000 / measureDuration / SIGNAL_PER_RND;
    float uPerSekL2 = counterFan4 * 60000 / measureDuration / SIGNAL_PER_RND;
    int y = 0;

    sprintf(output, "Duty    :    %3d", duty);
    u8g2.drawStr(0, y, output);

    y += lineOffset;
    sprintf(output, "U/sec S1: %6d", (int) uPerSekS1);
    u8g2.drawStr(0, y, output);

    y += lineOffset;
    sprintf(output, "U/sec S2: %6d", (int) uPerSekS2);
    u8g2.drawStr(0, y, output);

    y += lineOffset;
    sprintf(output, "U/sec L1: %6d", (int) uPerSekL1);
    u8g2.drawStr(0, y, output);

    y += lineOffset;
    sprintf(output, "U/sec L2: %6d", (int) uPerSekL2);
    u8g2.drawStr(0, y, output);
}

void measure() {
    measureDuration = millis() - lastDraw;
    if (measureDuration >= UPDATE_CYCLE) {
        // Deactivate interrupt while we are calculating
        detachInterrups();

        u8g2.clearBuffer();
        draw();
        u8g2.sendBuffer();

        // reset state
        counterFan1 = 0;
        counterFan2 = 0;
        counterFan3 = 0;
        counterFan4 = 0;
        lastDraw = millis();

        // Reactivate interrupt
        attachInterrups();
    }
}

void loop() {
    measure();
    btnBouncer.update();
    if (btnBouncer.fell()) {
        // Button was pressed. Increase duty.
        if (duty > 90) {
            duty = 0;
        } else {
            duty += DUTY_INC;
        }

        dutyS = duty * PWM_MAX / 100;
        dutyL = duty * PWM_MAX / 100;

        OCR4A = dutyS;
        OCR4B = dutyL;
    }
}

void isrFan1() {
    counterFan1++;
}

void isrFan2() {
    counterFan2++;
}

void isrFan3() {
    counterFan3++;
}

void isrFan4() {
    counterFan4++;
}


text:
Arduino Nano-combo NRF2401
I am using two nano-combo for a RC car and when the remote emitter battery is too down if the car was running and battery finally empty the car was still running...is there any way by programming to check communication between the two nanos and solve this problem??. Thanks.
here is the code:
//Receiver program
#include <SPI.h>;
#include "Mirf.h"
#include "nRF24L01.h"
#include "MirfHardwareSpiDriver.h"
Nrf24l Mirf = Nrf24l(10, 9);
void setup()
{
Serial.begin(9600);
Mirf.spi = &MirfHardwareSpi;
Mirf.init();
Mirf.setRADDR((byte *)"FGHIJ"); //Set your own address (receiver address) using
5 characters
Mirf.payload = sizeof(datos);
Mirf.channel = 90;             //Set the used channel
Mirf.config();
//Serial.println("Listening...");  //Start listening to received data
void loop()
{
if (Mirf.dataReady()) { //When the program is received, the received data is
output from the serial port
Mirf.getData(datos);
delay(5);
if (datos[7] >= 150) {     //motor forward
analogWrite(3,0);
analogWrite(5,255);

}
if (datos[7] <= 90) {    motor back
analogWrite(3,255);
analogWrite(5,0);

}
if (datos[7] > 90 && datos[7] < 150 or datos[7] == 0) { //motor stop
analogWrite(5,0);
analogWrite(3,0);

}
}
}
it works perfect I can control dc motor no problem but if remoto control battery is low or empty then no communication with NANO receiver and the motor spin itself non stop.
I try different things in the void loop like:
if (!Mirf.dataReady()) {
analogWrite(5,0);
analogWrite(3,0);  }
but still the same problem. So that´s why must be something inside Rf library to check if remote control NANO comms is off I don`t know...
Thanks

Surely. You can program your Arduino to stop, if no data was received for a specific amount of time. Though we cannot really give you more advice without more information from you. Please include your code into the question (and format it correctly as code). Also please give us more information, how everything is connected.

use a heartbeat signal

You can do somthing like:
while(radio.hasData()){
}

This works in the NRFLite library. I don't know about other libraries like RF24 etc.


text:
Arduino Due 9-bit serial - Can core Due Libraries be modified to get this functionality similar to Mega and Uno?
Need help to see if I can get an Arduino due to receive and send 9-bit com as already implemented on AVRs like Uno, Mega and even teensy boards, by modifying hardware serial cores. Have not found any similar references for this for the due? Is the due capable of 9-bit com?

What I mean by Hardware Serial Cores are files in the Arduino IDE. Ex. Serial.Hardware.cpp, etc.

If it's using UART then it's not possible (=> pins 0/1). If it's using USART (all other serials), then it's possible.