text:
Arduino Pro Mini PWM issue
I want to create a small LED strip driver/controller with 2 channels (Cold/Warm white) using Arduino Pro Mini (5V/16MHz). I have connected the parts per the following diagram
I have pins 5 and 6 setup as output, control them via analogWrite, and it all works great on Arduino UNO.
The problem comes with Arduino mini pro. When one channel is set to 255 and the other is 0, the LED strip does light only in one color, which is OK and when I swap the PWM channel's values, the other light color starts to shine. So far so good. When I set both to 0, the strip keeps on shining at about 30% (I don't have a scope, so I can't tell what the pwm signal is doing). Varying the channels' pwm in the range 0-255 does affect the light somehow but it never goes down to a complete off.
Looking at the arduino uno and pro mini I can't see anything obvious that should make them act differently from the hardware perspective so I'm guessing there's a problem in the libraries or perhaps my arduino pro mini (a clone) is somehow messed up.
Has anyone observed this kind of behavior in Arduino pro mini and has a solution for it?
Edit: Added some measurements per @Abel's request. I measured both DC and AC with and without the LED strip connected.
Connecting the LED strip really does mess things up, but WHY? UNO can handle it, but the pro mini can't! I thought mini was basically just shrunk down arduino uno (both have the same SMD version of MEGA328P), but apparently there are some differences.

check your led strip specs.  you may have to change the pwm frequency.

@Abel, does the pwm frequency differ between the UNO and the pro mini? Like I said in my question, the same code works just fine in an UNO board but doesn't on pro mini. I used pins 5 and 6 in both cases.

@Juraj - the problem is with pro mini  - a link to the particular board is in my question - click on the "clone" word.

theres a lot that can be wrong.  without led strip specs I can't determine.  1) frequency may be throwing off something in your strips own voltage regulation (you are basically swinging the "ground" side around). 2) pro mini logic voltage may be lower (people mix 3.3v and 5v all the time).  add in your pull to ground on the logic, and your power mosfets may not be reacting properly.  (shouldnt need to pull output logic)

@Abel the strip is this: https://www.aliexpress.com/item/33005175470.html (5050 CCT, 12V). With my first try I didn't use the MOSFETS. I used TIP120 Darlington transistor which did not have the 10k pull down and that's when I first observed the strange behavior. I didn't try it with the Arduino UNO back then and decided to switch to the MOSFETS. As for the variant of Arduino mini. I'm pretty sure I have the 5V (I checked voltage on pins and signage on the crystal). I tried to change the board type to 3.3V in the Arduino IDE - apart form the timing on the serial line, nothing changed.

if the crystal checks out, its most likely 5V.  if you have a meter, put it in AC mode and see what's happening on the pwm signals.  It'll report VRMS, but it's still better than nothing.  Compare what you see on uno vs mini pro.

Showing the actual wiring may reveal something.

Double check you wiring, and resistor values. Double check you solder joints on your pro-mini (assuming you soldered the headers yourself). Wiggle all you connections in your breadboard.

Thanks to comments I received from several people here I quadruple checked the wiring and eventualy found the problem. My recent Arduino Uno tests were done on a breadboard, but I had the Pro Mini prototype soldered on the prototyping board which has the holes connected in columns on the copper side. I made the cuts in all the necessary places ... but one! That one omission caused a short between pin 6 and the drain from the other channel's mosfet. The problem with these boards is that the parts are on one side and while flipping the board to the copper side, it is too easy to get lost in all the columns and miss something.
The morales of this story are: "Never be too certain about your wiring/soldering" and "Arduino is pretty resistent to my attempts to fry it :)".

Nice clean design! Let's determine for sure what voltage it is outputting to the MOSFETs. Write a very simple sketch that cycles a pin every few seconds and measure the voltage. You should get ground and VCC. If it is less than 4.5 volts (guard band included) your FETs will give you problems as they will not be properly enhanced.  Here is why: The IRF520 is a Power Mosfet with 9.2A collector current and 100V breakdown voltage. The mosfet has a low gate threshold voltage of 4V and hence commonly used with microcontrollers like Arduino for switching high current loads. You may have to get a different MOSFET with a lower gate threshold. Note there is some variation in the devices so they will not all but the same but will meet the specification. The 10K pull down resistors is a great addition and guarantees your state during reset until it is set up.

Get a good digital O'scope. They are incredibly cheap these days, and pay for themselves pretty rapidly in reduced frustration and time spinning one's wheels.  I recently got a Hanmatek DOS1102 dual-channel 110MHz, and I haven't used my old analog Tek2236 since


text:
What is the purpose of F() and FPSTR() in ESP8266WebServer -> FSBrowser?
I found this code sample from the FSBrowser (Flash File System) example in the ESP8266WebServer library:
replyServerError(FPSTR(FS_INIT_ERROR));
replyBadRequest(F("DIR ARG MISSING"));

I was a bit confused at what F() and FPSTR() do, so I looked up the source (WString.h) and found this:
#define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))
#define F(string_literal) (FPSTR(PSTR(string_literal)))

Which raised more questions. How does this code work and what does this added complexity gain over just using char* or String as is?
EDIT: Added Metrics
Here's the memory usage before and after I removed all 25 instances of F() from a file system class, measured by PlatformIO Project Inspector:

With F()
Without F()
Difference

RAM Used
29,488 bytes (36.0%)
29,792 bytes (36.4%)
+304 bytes

Flash Used
355,312 bytes (34%)
355,188 bytes (34.0%)
-124 bytes

Total (uncompressed)
359,472 bytes
359,344 bytes
-128 bytes

Adding F() decreases RAM usage by 1% and increases Flash by around half that. That's for a single class with 25 instances of F(). For a program containing 20x this code, the difference can be significant. However, you'll run out of RAM before you get there. The space savings will be limited to around 5-8%. Still not nothing.

On the ESP32 (as well as most 32-bit boards), the macros are nothing but a cast, on AVR-based boards (i.e. Arduino Uno), special low-level functions are required to read data from flash. The macros are hiding this difference from the user, so that the code can be written such that it compiles and runs on both platforms.

@PMF thanks for clarifying the use case. Does that mean I don't need to use F() or FPSTR() in my own code if I only plan on using the ESP8266?

I think not, but it may still depend on the compiler (it may still do a copy from Flash to Ram on bootup). You can find out by adding/removing a few F()'s and check the resulting RAM usage (last line of the compiler output). If it doesn't change, you don't need it.

On the ESP8266 for sure, F() macros can save heap space.

@dandavis Thanks! I added an edit with some metrics. The code author sometimes uses F(), sometimes FPSTR(), and sometimes neither. What is a good criteria to decide when to use each approach?

it will save more ram with longer strings, like web page error messages for example. Use F() pretty much only on string literals.

The purpose of the PSTR() macro is to configure the string to be used directly from flash memory. The string is then not loaded to dynamic memory at runtime as it would be without PROGMEM specifier set by the macro.
The purpose of the FPSTR() macro is to cast a string to 'dummy' FlashStringHelper type to help compiler choose the right overloaded function if dynamic memory and flash memory version of a function is available. An example would be the print function.
The F() macro combines this two macros. It makes the string a PROGMEM string and casts it to FlashStringHelper.

Thanks for the reply! How does FlashStringHelper help function overloading? Does it cast itself to either a dynamic string or flash string depending on its input parameter?

@DV82XL, PROGMEM string is const char* too. in C there are functions like sprintf_P for PROGMEM strings , but Arduino decided to use a special 'dummy' type for the PROGMEM string and uses print(const char*) for normal string and print(flashstringhelper*) for PROGMEM string. there is no Serial.print_P in standard Arduino API (some cores have it). to use the right function the C++ compiler evaluates the parameters of functions with same name https://github.com/arduino/ArduinoCore-avr/blob/9f8d27f09f3bbd1da1374b5549a82bda55d45d44/cores/arduino/Print.h#L65

source: Stack Exchange

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

sort: votes


text:
defining a macro with variables
I am working on Marlin 3D program. I made some changes for xyz prop and I do not make a definition as #define PRB_GCODE_END "G92 X-" XOFF "Y" XOFF "Z" ZOFF "\ n" to send the final xyz coordinates as gcode at the end of the promulgation procedure. It is required. If anyone has any idea how to use float type variables during macro definition please help.
void _user_gcode_exe(const char * const cmd) {
  lcd_return_to_status();
  enqueue_and_echo_commands_P(cmd);
}

void user_gcode_exe_1() {
  float XOFF = (25.00 + PRB_XOFFSET + (TOOL_DIA / 2.00));
  float YOFF = (25.00 - (PRB_YOFFSET + (TOOL_DIA / 2.00)));
  float ZOFF = (10.00 + PRB_ZOFFSET);

#define PRB_GCODE_END "G92 X-" XOFF " Y" XOFF " Z" ZOFF "\n"

#define PRB_GCODE "M117 Z-XY Probing now..\nG38.2 F120 Z-20.00\nG92 X0.00 Y.00 Z0.00\nG0 Z5.00 F1200\nG0 X-20.00 F1200\nG0 Z-5.00 F1200\nG38.2 F120 X25.00\nG92 X0.00\nG0 X-5.00 Y-25.00 F1200\nG0 X15.00 F1200\nG38.2 F120 Y25.00\nG92 Y0.00\nG0 Y-5.00 F1200\nG0 Z10.00 F1200\nG0 X-25.00 Y25.00 F1200\n"

#define MSG__OK "M117 Z-XY Probing done..\n"
  _user_gcode_exe(PSTR(PRB_GCODE PRB_GCODE_END MSG__OK));
}

While defining PRB_GCODE_END, ensuring that float type variables are included in this definition. For example: Considering that the variables XOFF, YOFF and ZOFF are calculated as 12.85, 11.25 and 10.50 respectively. PRB_GCODE_END should occur as follows:
G92 X-12.85 Y 11.25 Z10.50 \n

why are you asking a c++ programming question at an arduino site? ... how is your question related to the arduino?

this program is running on arduino mega

You can't. Variables and macros are completely different concepts and handled by completely different parts of the compiler toolchain.
Instead you will need to build your string up into a char array (or whatever format the _user_gcode_exec() function accepts) with the likes of sprintf.

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


text:
ESP-01 and HC-SR04 problems booting up
I have a problem in a project that I am working, basically I need to use a ESP-01 to receive the measurements from a HC-SR04 and send it to another ESP-01 (which I won't cover here).
Basically my ESP doesn't boot 95% of times, it just stays with the blue LED on all the time, on the remaining 5% of cases it boots normally and reads the sensor and also sends the information to another ESP.
I have done a lot of research and I am aware of these points:

HC-SR04 works in 5V and ESP in 3.3v, so a level convertor would be needed for the GPIO pins.  But, I have seen that the manufacturer (Espressif) stated that the ESP is resistant to 5V logic and it should work.  Also, I asked my professor and he said that it wouldn't be a problem.

Both IO pins need to be HIGH to boot, and the sensor seems to supply low, but like I said the ESP01 does boot, but not all the times.

That said, I would like to know why it works sometimes and others not, trying to get a little more of stability for presentation purposes...
Also it's worth noting that I have another ESP-01 connected with a DHT11 sensor with basically the same settings and it works normally.
The connections go like this:

ESP-01
HC-SR04

GPIO0
Trigger

GPIO2
Echo

GND
GND

Component
Power

ESP-01 Vcc, CH_PD
3.3v

HC-SR04 Vcc
5v

The code:
// pins of the esp8266 connected to the sensor
#define trigPin 0  //GPIO0
#define echoPin 2  //GPIO2

// intialize the variables for storing the measurement
float timeElapsed;
float distance;

void setup() {
  // Init Serial Monitor
  Serial.begin(115200);

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

}

void loop() {
  // do the measurements of the sensor
   digitalWrite(trigPin, LOW);  //para generar un pulso limpio ponemos a LOW 4us
   delayMicroseconds(4);

   digitalWrite(trigPin, HIGH);  //generamos Trigger (disparo) de 10us
   delayMicroseconds(10);
   digitalWrite(trigPin, LOW);

   timeElapsed = pulseIn(echoPin, HIGH);
   distance = timeElapsed/58.3;

   delay(1000);

  if ((millis() - lastTime) > timerDelay) {
     // code to send the information over wi-fi

  }
}

I have tried already:

Changing the ESP and HCSR04
Inverting GPIO0 and GPIO2
Boot without the sensor and connect it after, no succes
Different values in Arduino IDE during compilation of code

Thanks for your attention!

You powered the SR04 with 3.3 Volt. That does not work reliably. https://www.raspberrypi.org/forums/viewtopic.php?t=124216. The ultrasonic sender need more voltage to work well.

You should power up the HC-SR04 sensor with 5V, not 3.3V, as the sensor do not work properly with 3.3v supply

Sorry for the misunderstanding, the HCSR04 is powered by 5V, i just typed incorrectly.


text:
SIM7000G Connectivity Issue
I'm using botletics / SIM7000-LTE-Shield with Arduino Uno. I ran LTE-Demo example with the following adjustments based on this source:

fona.setNetworkSettings(F("jawalnet.com.sa"));
fona.setPreferredMode(2);
fona.setPreferredLTEMode(3);
fona.setOperatingBand("NB-IOT", 12);
fona.enableRTC(true);

But I'm getting no where and there is no registered network. I even tried Band (CAT-M) with no luck
I'm powering the shield from UNO with no external battery. 2 Green leds are led + blue led is flashing
Any Idea what am I doing wrong?
FONA basic test
Initializing....(May take several seconds)
Configuring to 9600 baud
Attempting to open comm with ATs
    ---> AT
    <--- AT
    ---> ATE0
    <--- ATE0
    ---> ATE0
    <--- OK
    ---> ATI
    <--- SIM7000G R1529

OK

    ---> AT+CPMS="SM","SM","SM"
    <--- +CPMS: 0,100,0,100,0,100
FONA is OK
Found SIM7000
    ---> AT+GSN
    <--- 869951031081155
Module IMEI: 869951031081155
    ---> AT+CFUN=1
    <--- OK
    ---> AT+CGDCONT=1,"IP","jawalnet.com.sa"
    <--- OK
    ---> AT+CNMP=2
    <--- OK
    ---> AT+CMNB=3
    <--- OK
    ---> AT+CBANDCFG="NB-IOT",12
    <--- OK
    ---> AT+CLTS=1
    <--- OK
    ---> AT&W
    <--- OK
-------------------------------------
[?] Print this menu
[a] Read the ADC; 2.8V max for SIM800/808, 0V-VBAT for SIM7000 shield
[b] Read supply voltage
[C] Read the SIM CCID
[U] Unlock SIM with PIN code
[i] Read signal strength (RSSI)
[n] Get network status
[1] Get network connection info
[c] Make phone Call
[A] Get call status
[h] Hang up phone
[p] Pick up phone
[N] Number of SMSs
[r] Read SMS #
[R] Read all SMS
[d] Delete SMS #
[s] Send SMS
[u] Send USSD
[y] Enable local time stamp (SIM800/808/70X0)
[Y] Enable NTP time sync (SIM800/808/70X0)
[t] Get network time
[G] Enable cellular data
[g] Disable cellular data
[l] Query GSMLOC (2G)
[O] Turn GPS on (SIM808/5320/7XX0)
[o] Turn GPS off (SIM808/5320/7XX0)
[L] Query GPS location (SIM808/5320/7XX0)

-------------------------------------

FONA> C
    ---> AT+CCID
    <--- 8996601730099550895f
SIM CCID = 8996601730099550895f
FONA> n
    ---> AT+CREG?
    <--- +CREG: 0,2
Network status 2: Not registered (searching)
FONA> l
    ---> AT+CIPGSMLOC=1,1
    <--- ERROR
Failed!
Fail code #2
FONA> n
    ---> AT+CREG?
    <--- +CREG: 0,2
Network status 2: Not registered (searching)
FONA>  n
---> AT+CREG?
<---
Network status 0: Not registered
FONA>

what's your question?

@jsotola how to make it work?

Im working on a similar project and running into the same issue with the flashing blue network LED. Im guessing its cycling power since there is no battery for the shield. Guess ill have to wait until my battery arrives.


text:
Controlling Offline ESP8266 from secure website
I want to control my ESP8266 device from my secure website via 2 different ways:

if ESP8266 is connected to internet, commands between website and device will sent over MQTT which as working perfectly as I want to be.
if ESP8266 is disconnected from internet, commands should be handled through HTTP request to local webserver. (Given I'm connected to the same router).

So the website coded this way:
if ( there is internet ) {
Publish MQTT command
} else {
Send HTTP request
}
When I tested sending HTTP requests: http://192.168.100.100/?led=on
I get error message saying Mixed content is blocked given my website is secure while local webserver is not.
Then I tried setting up a secure local webserver on my ESP8266:

With Firefox: It's working perfectly.

With Chrome:
GET https://192.168.100.100/?led=off net::ERR_CERT_AUTHORITY_INVALID

With IPhone Safari: It is not working and I have no mean to debug right now. But I'm suspecting security issues with local webserver.

As I'm targeting IPhone users, and looking for a solution to improve local webserver security or trying another approach.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServerSecure.h>

const char *dname = "esp8266";
const char* ssid = "SSID";
const char* password = "PASS";

BearSSL::ESP8266WebServerSecure server(443);
ESP8266WebServer serverHTTP(80);

int ledPin = 2;

WiFiClient espClient;
PubSubClient client(espClient);
WiFiManager wm;

int value;

static const char serverCert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIC6jCCAlOgAwIBAgIUZIw0cBcWDPJZe8ZIDu6bDqdwwvwwDQYJKoZIhvcNAQEL
BQAwejELMAkGA1UEBhMCUk8xCjAIBgNVBAgMAUIxEjAQBgNVBAcMCUJ1Y2hhcmVz
dDEbMBkGA1UECgwST25lVHJhbnNpc3RvciBbUk9dMRYwFAYDVQQLDA1PbmVUcmFu
c2lzdG9yMRYwFAYDVQQDDA1lc3A4MjY2LmxvY2FsMB4XDTE5MDQxMzE1NTMzOFoX
DTIwMDQxMjE1NTMzOFowejELMAkGA1UEBhMCUk8xCjAIBgNVBAgMAUIxEjAQBgNV
BAcMCUJ1Y2hhcmVzdDEbMBkGA1UECgwST25lVHJhbnNpc3RvciBbUk9dMRYwFAYD
VQQLDA1PbmVUcmFuc2lzdG9yMRYwFAYDVQQDDA1lc3A4MjY2LmxvY2FsMIGfMA0G
CSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiZmrefwe6AwQc5BO+T/18IVyJJ007EASn
HocT7ODkL2HNgIKuQCnPimiysLh29tL1rRoE4v7qtpV4069BrMo2XqFvZkfbZo/c
qMcLJi43jSvWVUaWvk8ELlXNR/PX4627MilhC4bLD57VB7Q2AF4jrAVhBLzClqg0
RyCS1yab+wIDAQABo20wazAdBgNVHQ4EFgQUYvIljCgcnOfeRn1CILrj38c7Ke4w
HwYDVR0jBBgwFoAUYvIljCgcnOfeRn1CILrj38c7Ke4wDwYDVR0TAQH/BAUwAwEB
/zAYBgNVHREEETAPgg1lc3A4MjY2LmxvY2FsMA0GCSqGSIb3DQEBCwUAA4GBAI+L
mejdOgSCmsmhT0SQv5bt4Cw3PFdBj3EMFltoDsMkrJ/ot0PumdPj8Mukf0ShuBlL
alf/hel7pkwMbXJrQyt3+EN/u4SjjZZJT21Zbxbmo1BB/vy1fkugfY4F3JavVAQ/
F49UaclGs77AVkDYwKlRh5VWhmnfuXPN6NXkfV+z
-----END CERTIFICATE-----
)EOF";

static const char serverKey[] PROGMEM =  R"EOF(
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKJmat5/B7oDBBzk
E75P/XwhXIknTTsQBKcehxPs4OQvYc2Agq5AKc+KaLKwuHb20vWtGgTi/uq2lXjT
r0GsyjZeoW9mR9tmj9yoxwsmLjeNK9ZVRpa+TwQuVc1H89fjrbsyKWELhssPntUH
tDYAXiOsBWEEvMKWqDRHIJLXJpv7AgMBAAECgYA5Syqu3mAKdt/vlWOFw9CpB1gP
JydvC+KoVvPOysY4mqLFjm4MLaTSjIENcZ1SkxewBubkDHVktw+atgvhfqVD4xnC
ewMpuN6Rku5A6EELhUoDrgMEt6M9D/0/iPaMm3VDtLXJq5SuKTpnM+vyE4/uM2Gu
4COfL4GQ0A5KWTzGcQJBANfpU/kwdZf8/oaOvpNZPGRsryjIXXuWMzKKM+M1RqSA
UQV596MGXjo8k8YG/A99rTmVhbeTMC2/7gIyGTePe/kCQQDAjZg2Ujz7wY3gf1Fi
ZETL7DHsss74sZyWZI490yIX0TQqKpXqEIKlkV+UZTOoSZiAaUyPjokblPmTkKfu
uMyTAkBIBjfS+o1fxC+L53Y/ZRc2UOMlcaFtpq8xftTMSGtmWL+uWf93zJoGR0rs
VkwjRsNQYEaY9Gqv+ESHSvsKg7zRAkEAoOLuhpzqVZThHe5jqumKzjS5dkPlScjl
xIeaji/msa3cf0r73goTj5HLIev5YKi1or3Y+a4oA4LTkifxGTcRvwJBAJB+qUE6
y8y+4yxStsWu362tn2o4EjyPL2UGc40wtlQng2GzPZ20+xVYcLxsJXE5/Jqg8IeI
elVVC46RfjDK9G0=
-----END PRIVATE KEY-----
)EOF";

void showWebpage() {
  int ledStatus = digitalRead(ledPin);

  if (server.hasArg("led")) {
    String status = server.arg("led");
    if (status == "off") {
      digitalWrite(ledPin, HIGH);
      ledStatus = 1;
    }
    else if (status == "on") {
      digitalWrite(ledPin, LOW);
      ledStatus = 0;
    }
  }

  String content = "<!DOCTYPE html>";
  content += "<title>ESP8266 Test Server</title>";
  content += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">";
  content += "<link rel=\"shortcut icon\" href=\"data:image/x-icon;base64,AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA/4QAAAAA/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARAiIgEQAiAQASAAEAEgAhABAgAQASACARAAIBEQIiAQASACAQACABABIAIAEAAgARACIAABAAIAAAAAAAAAAAAAAAAAAAAAEREAERAAEAAQAAAAAQAQABAAAAABABAAERAAARAAERAQAAAQAAAQARAAABAAABABEREAAREAERCQmQAAZ2YAAGtmAACdEQAAZrsAAGbdAACZ7gAA//8AAP//AAAMdwAAf7cAAH+3AAAecQAAffYAAH32AAAOMQAA\" />";
  content += "";
  content += "";
  content += "
ESP8266 HTTPS Server
<form action=\"/\" method=\"get\">
ledPin LED Status:";

  if (ledStatus) content += " Turned off";
  else content += " Turned on";

  content += "
";

  if (ledStatus) content += "<input type=\"submit\" value=\"on\" name=\"led\">";
  else content += "<input type=\"submit\" value=\"off\" name=\"led\">";

  content += "</form>";

  content += "
";
  time_t now = time(NULL);
  content += ctime(&now);
  content += "
";

  content += "
For more information see OneTransistor.
";

  server.sendHeader("Access-Control-Allow-Origin", "*");
  server.sendHeader("Access-Control-Max-Age", "10000");
  server.sendHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS");
  server.sendHeader("Access-Control-Allow-Headers", "*");
  server.send(200, "text/html", content);
}

void secureRedirect() {
  serverHTTP.sendHeader("Location", String("https://esp8266.local"), true);
  serverHTTP.send(301, "text/plain", "");
}

void setup() {
  Serial.begin(115200);  pinMode(ledPin, OUTPUT);  digitalWrite(ledPin, LOW);

    // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {    delay(1000);    Serial.println("Connecting to WiFi..");  }
  Serial.print("Connected to WiFi: ");  Serial.println(WiFi.SSID());
  Serial.print("IP: ");  Serial.println(WiFi.localIP());

  Serial.print("Server can be accessed at https://");
  Serial.print(WiFi.localIP());
  if (MDNS.begin(dname)) {
   Serial.print(" or at https://");
   Serial.print(dname);
   Serial.println(".local");
  }

  serverHTTP.on("/", secureRedirect);
  serverHTTP.begin();

  server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey));
  server.on("/", showWebpage);
  server.begin();

}

void loop() {
  serverHTTP.handleClient();
  server.handleClient();
  MDNS.update();
  delay(1000);
}

Are you using self-signed certificates?

@Majenko Yes it is self signed

That's probably your problem then: you don't have a valid CA. You should get a proper certificate. letsencrypt.org do them for free, but I usually use certbot to generate and install them automatically - not sure how you'd get the raw certificate files.

The commonly accepted method for this seems to be to either run your own CA and import that into the systems that will access your devices, or manually import and trust each certificate for your devices into the phone/computer that wants to access it. There is no simple way of using a public CA since they generally need authentication against the domain live on the server, which you can't do.

Where is your website hosted? Did any of the suggestions to your previous question help in any way?

@Gerben it's hosted on a VPS server with SSL. no none of the suggestions were helpful. I believe I have to have secured local webserver but don't know how?

I would suggest not using SSL on your ESP8266 at all. Instead make "background" connections (for example with curl in PHP) from your web server to the esp8266.

@Majenko the whole point of this is to be able to communicate while offline. thus, can't use php.

Why are you even trying to use SSl for an internal site anyway?

@Majenko removing SSL will be my last resort if this can't be sorted.

Well, you can't really use a public CA on internal sites, and you don't want to run your own CA or import certificates into your browsers, so that only leaves ditching SSL. Which is pointless in a closed network anyway.


text:
SIM808 Doesn't detect SMS if sent while offline
I'm running UNV SIM808 Shield with Arduino Uno using DFRobot_SIM808. The shield has no issues detecting incoming SMS while powered on. I just found out if the shield is off while sending the SMS, it won't detect it when it becomes online again.
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

#define MESSAGE_LENGTH 160
char message[MESSAGE_LENGTH];
int messageIndex = 0;

char phone[16];
char datetime[24];

#define PIN_TX    3
#define PIN_RX    2

SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);

  //******** Initialize sim808 module *************
   while(!sim808.init())  { Serial.println("Starting Sim808...");   sim808.powerUpDown(9); }

  delay(3000);
  Serial.println("Init Success, please send SMS message to me!");
}

void loop() {
  //*********** Detecting unread SMS ************************
   messageIndex = sim808.isSMSunread();
    Serial.print("messageIndex: ");
    Serial.println(messageIndex);

   //*********** At least, there is one UNREAD SMS ***********
   if (messageIndex > 0) {
      sim808.readSMS(messageIndex, message, MESSAGE_LENGTH, phone, datetime);

      //***********In order not to full SIM Memory, is better to delete it**********
      sim808.deleteSMS(messageIndex);
      Serial.print("From number: ");
      Serial.println(phone);
      Serial.print("Datetime: ");
      Serial.println(datetime);
      Serial.print("Recieved Message: ");
      Serial.println(message);
   }
}

I'm sharing the serial monitor data after powering off the shield. I sent a this message (2:24) at 2:24 AM local time. 10 mins later, I powered the shield on and waited for the message to be detected but with no luck for 15 mins. I sent another message (2:49) local time while the shield is on and it was detected right away along with the previous message.

It runs every 3 seconds but I cleaned the data

02:34:56.342 -> Starting Sim808...
02:35:06.958 -> Init Success, please send SMS message to me!
02:35:09.602 -> messageIndex: -1
02:40:00.686 -> messageIndex: 0
02:45:02.311 -> messageIndex: 0
02:49:26.940 -> messageIndex: 0
02:49:29.560 -> messageIndex: 0
02:49:32.216 -> messageIndex: 0
02:49:33.565 -> messageIndex: 7
02:49:36.269 -> From number: +***********
02:49:36.322 -> Datetime: 21/04/21,02:24:20+12
02:49:36.369 -> Recieved Message: 2:24
02:49:37.624 -> messageIndex: 8
02:49:40.373 -> From number: +***********
02:49:40.373 -> Datetime: 21/04/21,02:49:28+12
02:49:40.426 -> Recieved Message: 2:49
02:49:43.029 -> messageIndex: 0
02:49:45.691 -> messageIndex: 0
02:49:48.314 -> messageIndex: 0

Here is code for sim808.isSMSunread(); function. Maybe there is something can be tweaked within the code can mitigate this issue:
char DFRobot_SIM808::isSMSunread(){
    char gprsBuffer[48];  //48 is enough to see +CMGL:
    char *s;

    sim808_check_with_cmd("AT+CMGF=1\r\n","OK\r\n",CMD);    delay(1000);
    sim808_send_cmd(F("AT+CMGL=\"REC UNREAD\",1\r\n"));
    sim808_clean_buffer(gprsBuffer,31);
    sim808_read_buffer(gprsBuffer,30,DEFAULT_TIMEOUT);

    if(NULL != ( s = strstr(gprsBuffer,"OK"))) {
        delay(50);
        return 0;
    } else {
        sim808_wait_for_resp("OK\r\n", CMD);
        sim808_send_cmd("AT+CMGL=\"REC UNREAD\",1\r\n");
        sim808_clean_buffer(gprsBuffer,48);
        sim808_read_buffer(gprsBuffer,47,DEFAULT_TIMEOUT);
        if(NULL != ( s = strstr(gprsBuffer,"+CMGL:"))) {
            s = strstr(gprsBuffer,":");
            if (s != NULL) {
                sim808_wait_for_resp("OK\r\n", CMD);
                return atoi(s+1);
            }
        } else {
            return -1;
        }
    }
    return -1;
}

What i'm looking for is to make the shield detect any unread messages if it was sent while off?

you will have to build a time machine

sounds like your provider does not store SMS messages and transmits when your device comes online ... test it with your cell phone ... turn off your phone and send SMS to your phone .... then turn on your phone

@jsotola Once I put the sim in my phone, I got the SMS immediately.

then you need to learn how the phone retrieves stored messages ... it has nothing to do with the arduino

do the sim808 have at commands like in this page https://www.developershome.com/sms/readSmsByAtCommands.asp ?

@user30878 I'm not quiet sure if I understood you, but yes the module is responding to AT commands and this how to it works.

Check the page I'm linking to.

@user30878, as I understand it, they're having problems retrieving messages that were queued on the network after having just powered up; not problems with reading messages generally.

@timemage the command "CMGR" is said to receive SMS from storage area. I don't know what the storage is, but the comments above said it might be the solution.

this question is worth a look https://stackoverflow.com/questions/29867646/minicom-atcmgr-n-not-showing-the-sms-content   the URL given in the answer has the details about storage https://www.smssolutions.net/tutorials/gsm/receivesmsat/

@user30878 I tried all possible storage types but end up with the same issue. AT+CPMS="SM" and then ME, MT, SM_P, ME_P and MT


text:
I have a problem trying to limit motor speed to a certain RPM using a MOSFET trigger switch module

I am using the potentiometer to control the duty cycle of a PWM signal to the MOSFET trigger switch module, thus controlling the motor speed.
In my code, I have used the map function to utilize the full resolution of my potentiometer (0 - 1023) and thus create a proportional PWM signal using analogWrite function (0 - 255).
However, in my setup I want to limit the speed of the motor from going beyond a MAX_RPM value, despite any further increase in analog value input from the potentiometer.
This means I have to continously check the RPM value (the RPM code works fine, so I will not include it).
If the motor speed hits the MAX_RPM value, any further potentiometer input should be ignored. To achieve this, I figured I need to hold the analogWrite function value constant thus holding the speed constant.
In the event that I turn the potentiometer in the reverse direction, this should decrease the PWM value thus also decreasing the speed.
I have written the code to achieve the process described above to no avail i.e., increasing potentiometer input causes the speed to go beyond the MAX_RPM value which is undesired.
In this project, I am developing a rev limiter of sorts.
Please help me figure out the problem in my code.
#define MAX_RPM 500
    #define MAX_RPM_PWM_MAPPED_VALUE 15

    //In this case, I first ran the motor while monitoring the speed and the potentiometer value
    //While doing this, I noted the potentiometer value at which the MAX_RPM is obtained
    //I then defined this potentiometer value as MAX_RPM_PWM_MAPPED_VALUE
    //With MAX_RPM_PWM_MAPPED_VALUE, I would directly limit the value written to the analogWrite function
    //

    MOSFETMODULE = 4;
    potentiometer = AO;

    void setup()
    {
        pinMode(MOSFETMODULE, OUTPUT);
    }

    void loop()
    {
        val = analogRead(potentiometer);  //Read potentiometer value - represents accelerator input
        mappedValue = map(val, 0, 1023, 0, 255); //Map the 10 bit value to 8 bit equivalent

        if(RPM >= MAX_RPM)
        {
            analogWrite(MOSFETMODULE, MAX_RPM_PWM_MAPPED_VALUE);
        }
            else
            {
              mappedValue = constrain(mappedValue, 0, MAX_RPM_PWM_MAPPED_VALUE);
              analogWrite(MOSFETMODULE, mappedValue); //Output a PWM signal to the MOSFET trigger module
            }
    }

Note the the actual RPM doesn't just depend on the PWM duty cycle, but also the load on the motor. Just like pressing the gas pedal on a car. If you don't change the gas pedal position, but you suddenly go up a hill, your speed will decrease.

Thanks, I totally understand the loading scenario. In fact, my setup aims to mimic a car operation - throttle position and engine speed. I aim to create a device that restricts the motor speed from exceeding various max speed levels depending on the load condition.

Try using analogWrite(MOSFETMODULE, 0); when the RPM exceeds the maximum value. Of maybe use 1 instead of 0. That way the code will throttle way back, if the RPM ever exceeds it's maximum. If will return to using the pot value, when the RPM goes back down. It may result in some weird oscillations, but cars make some weird noises too, when they are at their max RPM, so +1 for realism.

To clarify why your code isn't working. Currently, it's mapping the value of the pot (0-1023) to the 0-15 PWM duty cycle. But when the RPM exceeds it's limit you set the PWM to 15, which is the same value you get when you turn the pot to it's maximum. You want to turn down the PWM duty cycle, instead of setting it to it's max. (Imagine going down hill in a car. You don't press the throttle, but due to going downhill the RPM exceeds 500. Now your car will set it's throttle to full. Oops ;-p )

I agree with both responses, they totally make sense. Lemme try to implement them in my code. This problem makes me think deeply about how electronic throttles work in modern cards. Thank you.

Your problem is that you don't know what ADC value maps to the maximum RPM. If you did you wouldn't need to know the RPM.
What you have here is a "feedback loop", and what you need is some method of using the detected RPM to control the speed of the motor.
You need to decouple the potentiometer from the analogWrite completely - the potentiometer should be setting the desired RPM, not the value being sent to set the RPM.
So if you want an RPM range from, say, 0 to 100RPM you can map() the analogRead() to the values 0-100. Then you can examine the actual RPM and adjust the value you send to the PWM accordingly - if the motor is too fast then slow it down. If it's too slow then speed it up.
There's a special method that is used for this: PID. And there's a library that does it for you too:

https://playground.arduino.cc/Code/PIDLibrary/

The potentiometer provides the "set point", the RPM detection provides the "input", and the PID library gives you the "output" to feed to the analogWrite().  You need to then provide the special magic "tuning" parameters to give the best control over your motor.

Thank you for the detailed response. In this setup, I am aiming to mimic a car driving scenario, whereby the potentiometer is the gas pedal, while the MOSFET reps the fuel injector, and the motor speed reps engine speed. In essence, I wanted a setup that would restrict the motor/engine speed from exceeding a certain point i.e., the MAX RPM, regardless of an increasing input rather than holding the speed constant. As the pot is reversed/pedal released, I also want the motor/engine speed to drop appropriately. I just want to set an engine speed limit. A PID holds a constant speed value instead.

am trying to develop a rev limiter of sorts

@Curiousone maybe something like if (rpm>max) analogWrite(mosfet, PID_output); else analogWrite(mosfet, analogRead(pot_pin)>>2) could work


text:
Problem with my usb plug
First of all, we connected our usb plug to arduino board (starter kit). After that, we completed Project 1 successfully (circuit with led and switch.) We tried unplug the usb cable, but it was very difficult, we had to pull very hard, but we couldn't unplug it. Finally, I managed to take it away with the help of my partner. I was pulling the usb and my partner was keeping the arduino board stable. The result wasn't very nice, we probably broke the usb cable. You can see what I mean in these images, the metallic coating part of the cable is still stuck on the board.
https://ibb.co/6wtf02J
https://ibb.co/4pZg2w0
https://ibb.co/WPchtgN
https://ibb.co/gPHZYnt
Nevertheless, we put the remaining cable back where it was, and the board seems to be working normally.
My question is if it safe to use it. Is there any chance of electrical damage or something like that?
Thank you!
P.S. In addition, we are planning to buy a new arduino starter kit. How can we avoid this problem with the new board?

And shield from the usb plug can't be pulled out now? I don't think it's a dealbreaker, maybe just some ultra cheap cable..

Yes, it can't be pulled out. Maybe we could try with pliers, but I think we shouldn't, I believe if we do, we could probably damage the inside of the board. If it is safe to use it this way, we are willing to keep the shield inside the arduino usb port.

at most you can damage usb connector.. Maybe a little squeeze in the middle (just a little in weakest place). Anyway usb connector can be replaced, if you don't destroy something else

@KIIV, was considering making an answer to this, but with your second comment you seem to be covering everything I'd say anyway.  So it makes sense that if it's to be answered, it would be by you rather than me.  I'd tack my own thoughts into a comment if there's anything to add beyond what you say.

Without the center part of the USB plug, it should be possible to make some deformations of that shield without damaging rest of the usb connector and pull it out. Aim for the weakest spot - seam (usually in the middle of bottom).
But even if you damage on board connector, it can be replaced (but it might be better to give it to someone with soldering experience - at least for unsoldering it)
And as noted in comments, even without working usb connector it can be programmed either by connecting USB-TTL serial converter to D0/D1 (but without auto-reset, unless you provide 100nF capacitor between reset and RTS), or it can be programmed by another Arduino as SPI (it needs bit more wires, and by default it doesn't burn bootloader, so if you fix USB, you'll have to burn bootloader).
Easier might be swapping Atmega328p between boards, however it needs some practice, so you won't bend or rip pins)

One thing I had to add is just that in the meantime until fixing it, it's unlikely the USB cable shield sitting in the USB jack will cause any actual electrical problem.  So, it could powered by the barrel jack and programmed by a USB->TTL serial converter via D0 and D1, until it is fixed.


text:
Can't Turn Off Internal I2C Pull-Ups on ESP32
I've designed a custom ESP32 board around the WROVER-IE module. To keep power low, I'm using a GPIO-controlled high-side FET to turn off unused peripherals when in deep sleep mode.
The issue: I've pulled up an SSD1306 I2C OLED to this AUX rail. It works great when the device is awake. On setup() I start the OLED via ssd1306.begin() and from that point on, the SCL and SDA pins (22, 21) are always tied to 3.3V until I reset the ESP32.
The I2C bus always being tied to 3.3 ends up bleeding through the pull-up resistors and into the AUX rail, resulting unwanted current draw when in sleep mode.
Is there any way to turn off the internal I2C pullups on the ESP32?
Things I've tried so far:

Setting SDA, SCL as OUTPUT and writing LOW (does not work)
Setting SDA, SCL as INPUT and/or writing LOW (does nothing)
Calling gpio_hold_dis(gpio_num_t(SDA));(does nothing)

I'm now trying to dissect the esp32-hal-i2c.c lib but am not finding any fixes. Any help is greatly appreciated!
Edit, added diagram:

-N

"The I2C bus always being tied to 3.3 ends up bleeding through the pull-up resistors" - how do you know that? The pullups don't consume any power as long as you don't communicate on the bus.

If I remove the OLED display, the AUX voltage on the AUX rail dissipates. I will create a digram

I have solved this problem. For anyone who would like to turn off the internal pullups on the I2C bus of the ESP32, you need to disable the entire driver before putting the device to sleep.
First, include the peripheral driver library from the IDF:
#include "driver/periph_ctrl.h"

Next, call the following before sleep:
rtc_gpio_isolate(gpio_num_t(SDA));
rtc_gpio_isolate(gpio_num_t(SCL));
periph_module_disable(PERIPH_I2C0_MODULE);
digitalWrite(SDA, 0);
digitalWrite(SCL, 0);

This will stop the ESP32 from pulling up pins 21 and 22 while in deep sleep. Calling display.begin() or wire.begin() will restartthe driver upon wake.


text:
Simulink resets arduino
I am working on servo motors control through serial communication protocol, I am sending data from Simulink to arduino and vice versa, The problem I am getting is that once I open Simulink Servo motors start turning while no command is sent or received from both, I tought that Simulink is initializing (reseting) arduino, so I decided to add a capacitor between Gnd & reset (I also tried with a resistor between 5v & reset), It actually works when I try to use Arduino IDE, Arduino is not reseting, but When i use it with Simulink it doesn't make change, Servo motors still turning randomly (I think that when I start or close simulation, Servo Are going to their initial position, I am not sure). I tried to add initial Position in Setup() function but in vain, It doesn't make sens!
I tried using different arduino cards (MEGA, ESP32...Etc.) but in vain.
Does anyone have an idea about how to figure out this problem?
Here is Simulink control code : & Arduino code :

#include <SCServo.h>
SCSCL sc;

//Estructura Union
typedef union {
  float number;
  uint8_t bytes[4];
} valor;
valor velocidad;

unsigned long timeold;
int vel = 0;
float value;
void setup() {

  Serial1.begin(1000000);
  sc.pSerial = &Serial1;
  Serial.begin(9600);
}

void loop() {
  //Pregunta si tenemos un dato a recibir
  if (Serial.available() > 0) {
    value = recepcion();
  }

  //Transforma el valor del voltaje (0-5) a velocidad
  vel = map(value, 0, 5, 0, 1023);
  //Activa el motor dirección Backward con la velocidad
  sc.WritePos(3,  value, 0);

  velocidad.number = sc.ReadPos(3);

  Serial.write('V');
  for (int i = 0; i < 4; i++) {
    Serial.write(velocidad.bytes[i]);
  }
  Serial.write('\n');
  delay(50);
}

//Recibir Flotante
float recepcion() {
  int i;
  valor buf;
  for (i = 0; i < 4; i++)
    buf.bytes[i] = Serial.read();
  return buf.number;
}
//Función para la lectura del encoder

Thank you !

first thing to try is to connect Simulink without sending any data at all

I tried to use Simulink to receive Servo motor angle from arduino, it works great, the servo is not turning randomly, I am getting the servo motor angle in real time. but when I start sending from simulink, the servo motor starts to turn to max & the min angle!

sounds like a software issue

Without knowing what code you're running on your arduino or what you're actually trying to do (or what this "simulink" thing is you're talking about) we will be hard pressed to help you.

Did you check your hardware handshake lines? AFAIK one of them is used to reset the Arduino.

I added The simulink control code @Majenko

@thebusybee actually, I have no idea about how to this, I google it but I found nothing about the handshake lines for arduino!

@jsotola seems to be like that but I can't figure out what is i t

https://majenko.co.uk/blog/our-blog-1/reading-serial-on-the-arduino-27

I don't know but it seems to work now! I just added a delay(100) after the serial.available() loop  & it works, anyone can explain this for me pleasE


text:
How to build and run AUnit tests
I found this example on how to create a project with AUnit tests: https://www.thecoderscorner.com/electronics/microcontrollers/embedded-testing/getting-started-unittesting-arduino/
According to it and projects I have found on github my project structure should look like this:
Application
    src
        SomeComponent.cpp
        SomeComponent.h
    tests
        TestSomeComponent
            TestSomeComponent.ino
    Application.ino

But when I try to run TestSomeComponent.ino with Arduino IDE or VSC with Arduino plugin it does not see contents of src folder. I am assuming that it is treated as a separate sketch. What is a proper way to build and run tests?
[edit]
Some context (not sure what matters):

Our target board is ESP32 DevKit v1
Optimally if our developers could run tests on Windows and Linux machines
I have not gotten yet to continuous integration. I will start automating once I have any test building and running

[edit 2]
I have tried command line tools. Got AUniter running and tried like this (hoping for some automagic done by tools):
me@mypc:~/workspace/Application/Application/tests$ auniter.sh test esp32:/dev/ttyUSB0 TestSomeComponent/

I have tried any sane path combination in include path directive, for example:
#include "SomeComponent.h"
#include "app/SomeComponent.h"
#include "../../src/app/SomeComponent.h"
#include <SomeComponent.h>
#include <app/SomeComponent.h>
#include <../../src/app/SomeComponent.h>

But I keep getting this:
TestSomeComponent:4:42: fatal error: ../../src/app/SomeComponent.h: No such file or directory

I never came up with an acceptable solution to this, either. Closest I got was mkdir ~/Documents/Arduino/libraries/SomeComponent cp -R src/* ~/Documents/Arduino/libraries/SomeComponent/ and then include <SomeComponent.h> in the test .ino files. That rankles because it means you can't actually unit test a library before installing it. I suspect that's how AUnit/AUniter's author was doing it, though, before they switched away from Arduino IDE/arduino-cli to EpoxyDuino - given all of the AUnit examples use the #include <Foo.h> style.

I eventually switched to PlatformIO. It took me less than half an hour to rearrange sources, fix some compiler issues, build and flash my device.
Tests work really well. You just need to keep tested sources in lib folder. I even got GoogleTest package so I can use gmock in my tests.


text:
How do I measure the analog PPG signals from my Arduino Nano that's wired up to the Heart Rate 3 Clicker
I'm trying to find a code that would take the PPG signals from the MIKROE-2036 Heart Rate 3 Clicker and process the information through the Arduino Nano to find a person's Oxygen Saturation. Basically, by using this code how do I measure Oxygen Saturation from the given analog inputs from the LEDs?
This is the test code that the Arduino Nano could use, but it's more of a template:
/*
 * AFE4404 Basic Read library example.
 * https://github.com/rakshithbk/AFE4404-Library
 *
 * On Arduino Uno -  | AFE4404 | Uno Pin
 *                   | I2C_Dat | A4
 *                   | I2C_Clk | A5
 * get_led_val() will return uint32_t values.
 *
 * Advanced - you can modify the sample period and other
 * parameters in the library files (refer AFE4404 datasheet)
 */

#include <Wire.h>
#include <AFE_connect.h>

AFE A;

void setup() {
  Serial.begin(115200);
  Serial.println("AFE4404 basic readings -\n");
  A.init();
}

void loop() {
  Serial.print("LED 1 Val = ");
  Serial.print(A.get_led1_val());
  Serial.print("\t LED 2 Val = ");
  Serial.print(A.get_led2_val());
  Serial.print("\t LED 3 Val = ");
  Serial.print(A.get_led3_val());
  Serial.println();
}

This is the library I found that uses the Heart Rate 3 Clickers LEDs: https://github.com/rakshithbk/AFE4404-Library

The code above already measures the PPG signal. I don't know the sensor, that you have. But most likely taking just the signal from the first LED (with the corresponding function) will get you the PPG signal. I guess your real question is about how to calculate SPO2 (Oxygen Saturation) from the LED signals. Have you tried googling for that? I don't know that, so I would also just google for it.

@chrisl The sensor I'm using is the MIKROE-2036 Heart Rate 3 Clicker and essentially what you asked is exactly what I've been trying to look for. Basically, by using this code how do I measure Oxygen Saturation from the given analog inputs from the LEDs? I tried searching for that answer for nearly a month and haven't gotten close.


text:
Best practice for wiring two sensors that have SCL and SDA connections
I have two different sensors which have SCL and SDA connections which I am trying to connect to an Arduino nano. From what I understand, connecting both of these sensor to the A5 and A4 pins doesn't make any sense, considering that I need to collect data continuously from both sensors. Moreover, there are no other pins with the same functionality as A5 and A4. I am a beginner learning about microcontrollers, but it seems to me like the best practice to follow here would be to use two Arduino nanos. Is this this the only way, or is there another method I am not aware of?

you can't even collect data continuously from one sensor ... the data is transmitted serially ... there is always a delay between readings

which sensors are you talking about? ... what data throughput are you expecting?

I2C is a bus, it allows multiple sensors to be connected (as long as they have different address) to the same bus using the two wires. Y

@jsotola I have two different temp sensors. By continuous I meant I need to be collecting data every 10 ms.

@hcheung , but wouldn't the data I collect be a jumbled up version of the data collected by the different sensors?

Read the I2C wikipedia to understand how I2C works first. At any giving point, the I2C Host(Master) talk to one I2C Client(Slave), that is, those I2C sensors who was not addressed will not interfere the communication on the bus. The best way is for your to try it out in addition to the reading.

@hcheung , wouldn't this would mean that I couldn't get simultaneous data from the two sensor, or would the time difference not be significant? Also, what do you mean by "using the two wires"?

Define "simultaneous", if you run an I2C clock at 400kHz, each bit take 1/400000=2.5uS(microsecond) to send. Reading a temperature sensor would probably take about 7.5uS, more than sufficient for reading it in every 10 millisecond.

Your question does not have enough detail for a good answer. Please edit the question (don't reply in a comment) and add the following information: (1) What are the part numbers of the two sensors? (2) How far apart are they from the Arduino, and each other. (3) How often do you want to collect the data?

The whole point of the I2C bus is to allow multiple sensors or devices to be connected, as long as they have different I2C addresses. The addresses are usually built into the part, and often they have some provision for selecting an address from a range.
Whilst you can't simultaneously collect data from two sensors at once, you can certainly query them in quick succession. You need to connect SDA, SCL, Ground and +5V to each sensor, and the Arduino.
Your code would do something like:

Query sensor at address 42
Query sensor at address 43
Do something with the data
Wait a bit before doing it again

You could look at Wikipedia for some general information about I2C, and I also have a page about I2c that might help you.
Note that you also need a pull-up resistor on both SDA and SCL (that is, two resistors), a typical value would be 4.7k (connect the 4.7k resistors between SDA/SCL and your +5V line).


text:
How to reduce codes numbers
I am new in Arduino projects, i made a digital counter that counts from 00 to 99.
Here is my code below
void setup()
{
pinMode(0,OUTPUT);
  pinMode(1,OUTPUT);
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
}

void loop()
{
/* segment starts from 00*/
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,HIGH);
digitalWrite(0,LOW);
digitalWrite(3,LOW);
/* segment will now be 10, the 0 will continue counting up to 1*/

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(5,HIGH);
digitalWrite(4,LOW);
/* the segment will now be 20 */

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,HIGH);
digitalWrite(5,HIGH);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,LOW);
digitalWrite(6,HIGH);
digitalWrite(5,LOW);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,HIGH);
digitalWrite(6,HIGH);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(5,HIGH);
digitalWrite(4,LOW);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,HIGH);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,LOW);
digitalWrite(7,HIGH);
digitalWrite(6,LOW);
digitalWrite(5,LOW);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,HIGH);
/* the segment will now be 9 0 */

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,LOW);
digitalWrite(7,LOW);
/* when it gets here the segment resets to 00*/
}

It works pretty fine but the problem i have is the code is too long, is there a method i can use to reduce the length of the codes?

What you are writing here is some sort of binary counter: a BCD
(binary-coded decimal) counter to be precise. It turns out that the
processor inside the Arduino already works in binary. It's its native
language, so you do not have to tell it how to do binary. You just have
to know what operators to use in order to access the individual bits.
My approach would be to write a function that can display any number n
between 0 and 99. The first step is to do the decimal decomposition:
divide by 10, and take the quotient (first digit) and the remainder
(second digit). These digits will be represented in binary within the
machine. The next step is to access the individual bits. This is a two
step process:

Shift the bits of the number to the right until the bit you want is
at the far right. This is accomplished with the right-shift operator.

Compute the bitwise AND with the number 1 (0000000000000001 in
binary). This will clear all the bits but the one you want, and
result in either 0 (the same as LOW) or 1 (i.e. HIGH).

For example, if you want to get bit 1 of the number 7, you do
0000000000000111 = 7  initial number
0000000000000011 = 3  shifted one potion to the right
0000000000000001 = 1  bitwise AND-ed with 1

In code:
void display(int n)
{
    int digit0 = n % 10;
    int digit1 = n / 10;
    digitalWrite(0, (digit0 >> 0) & 1);
    digitalWrite(1, (digit0 >> 1) & 1);
    digitalWrite(2, (digit0 >> 2) & 1);
    digitalWrite(3, (digit0 >> 3) & 1);
    digitalWrite(4, (digit1 >> 0) & 1);
    digitalWrite(5, (digit1 >> 1) & 1);
    digitalWrite(6, (digit1 >> 2) & 1);
    digitalWrite(7, (digit1 >> 3) & 1);
}

Edit: If you need more that 2 digits, you have to successively
divide by 10:

Divide the number to be displayed by 10: the rest of the division is
the rightmost digit

replace the original number by the quotient of the division

divide again by 10: the rest of the division is the second rightmost
digit

replace the original number by the quotient of the division

etc.

For example, for three decimal digits:
void display(int n)
{
    int digits[3];  // digits[0] is the rightmost digit
    digits[0] = n % 10;
    n /= 10;
    digits[1] = n % 10;
    n /= 10;
    digits[2] = n % 10;

    // Now make sure that n < 10 (otherwise we are missing digits),
    // then display digits[0], digits[1] and digits[2].
}

The main program now only has to loop through the numbers 0 to 99, and
display each one in turn:
void loop()
{
    for (int n = 0; n < 100; n++) {
        display(n);
        delay(500);
    }
}

Thanks a lot although I have little knowledge on it

Thanks a lot for the help.But how did you get digit0=n%10  digit1=n/10, and if i want to add another bcd to it what calculations do i need to make to get it i have been trying digit2=n/100 but it didnt work well.

@JosephAfodu: Re “how did you get digit0=n%10 [...]”: I learned decimal counting in primary school, and then I learned the meaning of the / and % operators in C++. Re “and if i want to add another bcd”: see amended answer.

@JosephAfodu, The greater part of your confusion may be in not recognizing % as something you're probably already familiar with which is not conventional in math but is fairly conventional in coding.  You'll need to be familiar with the bitwise operators as well.

Is there a way i can make it with 3 bcd's without the middle one displaying letters , I tried but when the last one counts 1, the middle one will be displaying letters.

@JosephAfodu: You must have a mistake in your code. If you compute digits[1] as n % 10, it should not display letters, unless the wiring is wrong.

If i do it that way digit[0] and digit[1] will show the same number at a time

If i need number 999 i use: digit0=n%10; digit1=n/10; digit2=n/100; . Also i changed : for (int n=0; n<100; n++) to for (int n=0; n<1000; n++) because i need numbers up to 999. When it gets to 99 and the third bcd shows 1, insted of the second to show 0, it will show A until it counts to f before it restarts at 1 and maybe by then the 3rd  bcd have already shown 2. Which will make the numbers not get to 999 when it gets to 930 it will restarts from 000. I just need to get rid of the letters displaying on the second bcd.

@JosephAfodu: See my edit from two days ago: the code right after “For example, for three decimal digits”.

I suggest you look up how to do loops in a C or C++ programming tutorial. For example you can replace:
void setup()
{
  pinMode(0,OUTPUT);
  pinMode(1,OUTPUT);
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
}

with:
void setup()
{
  for (int i = 0; i <= 9; i++)
    pinMode(i,OUTPUT);
}

Also, what Edgar Bonet said. :)


text:
Making library for arduino
I'm learning library making on arduino , I want to make a library that works with arrays a user sets, e.g:
User sets array of int,
when  a certain function is been called the library will check if some instance are true or not ann set the return function accordingly as the array.
Code example:

    //in project example

#include <Keyss.h>

int rows=4;
int cols=2;
int a=0;
int b=1;
int c=2;
int inp=3;
int keyss[4][2]={
{0,1},,
{2,3},
{4,5},
{6,7}
};

Key key((keyss),rows,cols,inp,a,b,c);

void setup(){
Serial.begin(9600);
int keyprint=key.getkey();
Serial.println(key print);
}
void loop(){
}

And this will be the library files
Keys.h

#ifndef KEYSS_H
#define KEYSS_H
#include <Arduino.h>

class Key {

public:

Key(int (*keys)[4],int rows,int cols,int inp,int t1,int t2,int t3);
int getkey();
int waitforkey();

private:

int *_keys;
int _rows;
int _cols;
int _inp;
int _t1;
int _t2;
int _t3;

};

#endif

And
Keys.CPP

#include <Keyss.h>

//initialization

Key::Key(int (*keys)[4],int rows,int cols,int inp,int t1,int t2,int t3){

 _keys=keys[4];
 _rows=rows;
 _cols=cols;
 _inp=inp;
 _t1=t1;
 _t2=t2;
 _t3=t3;

 pinMode(_inp,INPUT);
 pinMode(_t1,OUTPUT);
 pinMode(_t2,OUTPUT);
 pinMode(_t3,OUTPUT);

}

//getkey()

int Key::getkey(){

int _a;
int _b;
int _i=0;
int _keymap=false;
int _val;
int _dt=500;
int _s1;
int _input;

for(_a=0;_a<_rows;_a++){

 for(_b=0;_b<_cols;_b++){

  _s1=_i;
  digitalWrite(_t1,(_s1>>0)&1);
  digitalWrite(_t2,(_s1>>1)&1);
  digitalWrite(_t3,(_s1>>2)&1);
  delayMicroseconds(_dt);

  _input=digitalRead(_inp);

  if(_input==true && _keymap==false){

   _val=_keys[_a*_cols+_b];
   _keymap=true;
}

  _i++;

}
}

if(_keymap==false){
   _val=-1;
}

return _val;

}

//waitforkey()

int Key::waitforkey(){

int _waitfor=getkey();

while(_waitfor<0){

_waitfor=getkey();

}

return _waitfor;

}

Where I have problem now is I don't know how to
use or assign an array in a library
I don't know how to use functions to refer to an array a user inputes, like here
int keyss[4][2]={
{0,1},
{2,3},
{4,5},
{6,7}
};

How do I use a function or inside the library to refer to the array a user sets?
Please how do I achieve that?
Its giving this error

Your keys variable is a 2D array of int, i.e. it is an array of
arrays. In C++, when an array is assigned to a variable or passed as an
argument, it implicitly decays to a pointer to its first element.
Note, however, that the decay-to-pointer behavior is not recursive.
In this case you end up with a pointer to an array of three int.
Your code should work if you give the proper type to the _keys class
member and the keys constructor parameter:
class Key {
public:
    Key(int (*keys)[3], int trig1, int trig2, int trig3, int inpin);
    int getkey();

private:
    int (*_keys)[3];  // pointer to array of 3 int.
    int _trig1;
    int _trig2;
    int _trig3;
    int _inpin;
    int _keye;
};

Edit: You have completely changed the question, to the point that my
answer may not be relevant anymore. In the previous version of the
question, it looked like you wanted to use a 3×3 2D array of numbers in
the class. In the current version, you are using an array of arbitrary
sizes represented as a flattened 1D array. These are quite different
approaches.
If you want to use a 2D array, the number of columns has to be a
compile-time constant. You have to declare the member variable as a
pointer-to-array like this:
int (*_keys)[2];  // there are two columns, not four!

assign it like this:
_keys = keys;  // do NOT subscript keys

and use it like this:
_val = _keys[_a][_b];  // it is a 2D array

This approach cannot work if you do not know the number of columns
beforehand.
If you want to use a flattened (1D) array, then the parameter of the
constructor has to be a simple int*, and you have to give it the
address of the first element of the original 2D array:
Key key(&keyss[0][0], rows, cols, inp, a, b, c);

The drawback of using a flattened array is that, in order to access the
elements, you have to perform explicit index calculations:
_val = _keys[_a*_cols + _b];

I tried it but I don't know the correct way to do it

Thanks bro  I didn't understand it that much earlier and also I am   new to  programming, but now I have understand it more


text:
Mains-Frequency Clock Library
I have an arduino thing, and the hardware I plan to connect to it (a triac zero-crossing based dimmer) provides a synchronization signal from the mains power phase it connects to.
Main power does of course vary some from the nominal 60Hz, however the exact frequency gets adjusted over the course of the day to ensure there are almost exactly 5184000 cycles per day and pretty much exactly 36288000 cycles per week, and is used by mains-powered wall clocks to keep time.
Since my application will need to keep accurate time-of-day across weeks or months without adjustment, it would be advantageous to be able to use this time source.
I can of course write my own code to increment a counter every time the arduino receives a pulse, but if a library that can handle this already exists, I would prefer to use that, in particular since then I won't have to write code to track days and months, handle DST, or any of that stuff.
What libraries exist (if any) to handle timekeeping based on a fixed-pulse-rate input source?

I don't think these exist, but you could use a general library to covert a seconds counter to time an date. Then use a different library for counting the crossings. Though this is so basic, that you can problem write it with just a few lines of code. Where do you live, because not every country tries to make the average frequency 60/50 Hz.

You could use the Arduino Time library. You will have to write your own time provider function based on pulse counting, but then you benefit from all the time-handling routines of the library.

@Gerben I'm in the USA, in a region that does regulate the mains power frequency.

@EdgarBonet That is probably what I will do, there just doesn't seem like a 'natural' way to integrate the pulse counting as a time provider except by keeping a separate redundant count of the time.

Counting the pulses is child's play and doesn't need a library (hint: use an interrupt input and increment a counter). From that count you can use TimeLib.h to convert seconds since 01/01/1970 to an actual time.  Or just do simple division to convert seconds (count/50) into minutes, hours, whatever division you want.

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


text:
Arduino serial port reset in Serial monitor & Python
So am I using an Arduino with a shield to gain some voltage values for an ECG. I am then plotting that data in Python. However whenever I "observe" the serial port, be that through the Arduino serial monitor or in attempting to plot the values of time (using millis()) against ECG (voltage) the values reset, so millis() resets the zero, which is fine, except that some of the older values still show up. Now this is especially a problem in Python because it means the plot is malfunctioning at the start of the script, because it is plotting some of the older values and then after a couple of seconds it resets and the plot looks normal again.
To demonstrate this I have recorded it on video and put it on YouTube, here it is:
https://www.youtube.com/watch?v=dNpUakcRPec
Now initially I thought the problem was with Python or the Pyserial module so I labelled the video as such, but since it occurs in the serial monitor I realised the solution would be in the Arduino sketch. I have tried flushing, didn't work, I have tried even to not start the data till I send a start byte, but this didn't work on Python.
Ideally I could start the Python plotting script and it would skip, or ignore those initial values from the serial port before beginning again.
Here is the Arduino sketch I am using:
#include <eHealth.h>

unsigned long time;
// The setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);

}

// The loop routine runs over and over again forever:
void loop() {

  float ECG = eHealth.getECG();
  time = millis();
  Serial.print(time);
  Serial.print(" ");
  Serial.print(ECG, 3);
  Serial.println("");

  delay(50);    // wait for 50 millisecond
}

I have recorded the actual RESET pulse at serial connect (it is about 1 ms, depending on trigger levels).

The Arduino is designed to reset when a Serial monitor or script connects to it. The best way to mitigate this would be to send the Arduino some kind of "start sending" signal when you connect to the serial port. It would then send the data when your script was ready.

I understand that, however this is affecting my script because it means the script plots garbage at the start, my question is can I stop this from occuring. From where I see it, it is something I need to change in the Arduino sketch first.

I removed millis() and used a counter instead inside my loop. However when I try to send a start signal to my serial port, using ser.write('S') on Python, the arduino doesn't receieve it

You could try putting something in your setup function, like while (Serial.read() != 'S');

It's fine on the Arduino end of things, when I open the serial monitor, it happily prints, the problem is in Python, when I try to send the 'S' byte, the serial port appears not to receive it.

Take a look at if(Serial)
That makes the Sketch wait for the serial port before continuing.
void setup() {
//Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
; // wait for serial port to connect.
  }
}

I have a sneaking suspicion that may only work on the Leonardo.
If so you could try an alternative:

Have Python send something to Arduino after it connects.
Wait until this is received in setup(): if (Serial.available() > 0) {...}
Execute the loop() normally

e.g.
// send data only when you receive data:
    if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();

            // say what you got:
            Serial.print("I received: ");
            Serial.println(incomingByte, DEC);
    }

I the answer from @TheDoctor. An alternative is for the client listening on serial port to wait for a "successful reset" signal from the Arduino.
void setup() {
//Initialize serial and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect.
    }
    Serial.println('reset successful')
}

There are pros and cons to each solution. In the @TheDoctor solution, it seems like there is an edge cases where the Arduino is already sending when the client connects and you'll get some junk before the reset occurs.

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


text:
Not sure if programmer or ATMega is burned
some time ago i tried doing this with my original arduino uno r3. I guess i had to plug the power cables in wrong order(i think it's called reversing polarity)  because my arduino stoped working. It turns on (the power diode is on) but i cannot upload any sketch on it. I'm thinking about changing the ATMega chip but, before i do that i want to be certain that it's the chip issue ,not the programmer. I have another arduino uno, and i heard that i can upload sketch with it to another uno. So my idea is, if i do this i will be able to say whether it's the programmer or the chip issue. The only problem is that i don't know how to do this and i wasn't able to find any reasonable tutorials online. Please tell me what to do.
Many Thanks,
Jan

Does the uno show up in the Device Manager? You could also have burned the ATMega16u2 that does the usb-to-serial.

I think it does, i will check it when i'm back home.

The Arduino IDE ships with a built in ArduinoISP sketch, and there is a very detailed tutorial with wiring diagrams etc on the Arduino site.

But doesn't it alow me only to burn a bootloader ? I would like to upload a simplest sketch (for example Blink) to check whether does the chip work.

No, you can program anything you want with ISP. When you use a boot loader, you can only program the non-bootloader section, but the converse is not true.


text:
Splitting the power source between an arduino and a servo
I have an Arduino board which is controlling a servo. I think I read that I could only supply about 100 mA through the Arduino's 5v pin. Because of that the power supply I use is able to deliver about 2A I would like to split the power before the Arduino. How do I do that?
Do I have to take some safety for the Aduino in concern or could I just split the wire?

Is your power supply 5V regulated?

It is a supply that is used to load a tablet, an AC/DC adapter. How do I know if it is regulated?

I think 500mA would be a more accurate rating. That is the rating of the fuse on the board. I don't know where you got the 100mA from?

Actually my question rather was: do your power supply output 5V or more than 5V? If it is 5V, it is likely to be regulated. A second question is where do you plug it to your Arduino (USB, power jack, Vin, 5V)?

If you have a 7V to 12V - 2A regulated supply, you can directly power your board using the 2.1mm connector. Do not go above 12V or you may destroy the voltage regulator on the board.
If you have a 5V to 6V - 2A regulated supply, you can supply your servo with this supply and rely on USB to supply the rest of the board (make sure you have a common ground for both the USB and the regulated supply).

"Do not go above 12V or you may destroy the voltage regulator on the board" I don't agree with this. First of all it depends on the board. Then, if we take the UNO as example, if you are you trying to get 800mA from the 5V rail nything above 7.5-8V will cause problems. If OTOH you are you trying to power only a 20mA LED even 20V is fine. Saying that the limit is 12V is correct in a limited amount of cases (max current ess than 200mA)

There is a page with information about the current limits of Arduino pins.  There's also a question on the Electrical Engineering SE site that addresses the current limits of the board overall.
From the accepted answer on that question:

The 5V output pin is good for ~400 mA on USB, ~900 mA when using an external power adapter

So that's more than the 100 mA you mentioned in your question.  (But go read the whole answer; there's more good info there.)
The easiest way to split the power is to use a separate, regulated power supply.
Except for simple tests (e.g., a single small unloaded servo), I use the digital i/o pins only for very low current signals:  buttons, status LEDs, sensors, serial communication, etc.
For example, to control an IR LED that can handle up to 50 mA, I'll supply power to the LED from the Arduino board's Vcc pin and control it with a transistor attached to a digital output pin.  Drawing 50 mA from the board's supply is well under the limit, and the digital output pin draws practically nothing.
For more than one servo, I use a peripheral PWM controller that takes power separately.  That peripheral is powered by a separate 5V 2A power adapter, which supplies the current to actually turn the motors.  I send commands to the controller using I2C from the Arduino, which is running from its own power supply.

Please note that "can source 200 mA (milliamps) from the Vcc pin" is NOT correct. That part comes from the datasheet of the microcontroller, and means that the maximum current that can flow inside the uC Vcc pin or outside the GND pin is 200mA. This means that the sum of all the currents sourced/sinked by the digital pins is 200mA (so 40mA for each pin, but max 200mA total). This is not for the Arduino +5V pin

@frarugi87:  Ah, I misunderstood.  Thanks for the clarification.  I'll try to incorporate that correction into this answer.


text:
Connect to Arduino 2560 using a RS232 Connection
Is it possible to connect to an Arduino 2560 using a RS232 (DB9) connection rather than the regular connection using USB cable?
I am thinking of this connection scheme:
PC -> USB cable -> USB to RS232 Multiplexer -> DB9 Cable -> Adapter board -> Arduino 2560

Yes, perfectly possible.  You need an RS-232 interface chip - the most common and well-known of these is the MAX232. You can get them as breakouts on eBay.
That interfaces between the DB9 and pins 0/1 (or other UART comms pins) on the Arduino.
If you are wanting to program the board through it you will also need to connect (after converting the voltage through the MAX232) the DTR line to RESET through a 100nF capacitor.
... Exactly like you would with a breadboard Arduino.


text:
Budgeting Power for 5V Arduino Pro Mini
In my low power project, I'm using a Arduino Pro Mini (5V, 16 MHz, ATMEGA328) and a low wattage 3W power supply. Everything else on the system other than the Arduino uses a max of 1.98W.
How much power should I budget for the Arduino Pro Mini (without any mods, ie: disconnecting the voltage regulator and LED)?

What voltage is the supply? And you may need a mod or two regardless. And can you get away with a lower voltage for the rest of the project?

@IgnacioVazquez-Abrams Its a 5V power supply. I am using a 2.5V and 3.3V regulator to provide the necessary voltages to the other components. What kind of mods would u suggest?

Well, for starters I'd look to see if you could use a lower voltage power supply with the same power output.

@IgnacioVazquez-Abrams I could use a 3W power supply with 3.3V output rail. Do you think the Arduino can be powered by using a 5V boost regulator?

I wouldn't bother. I'd just power it with 3.3V. Set the CKDIV8 fuse and bump up the prescaler if you need a higher clock speed than 2MHz.

The step up is a good idea. 16Mhz clock require 5v

Arduino mini, and atmega328 in general use less than 10mA with default arduino code. Turning down unused component (ADC and so on), using deep sleep and optimizing pbc would lover this consumption a lot, in the land of uA

That'll be a power consumption of 5V x 10mA = 50mW? The remaining 1W of capacity from the power supply should be sufficient to power the Arduino I guess?

Yes, your calculation are right and your watt enough

The onboard "power on" led will increase the power usage by a bit (guesstimated around 5mA). @Nyxynyx note that a 3W rated power brick doesn't always produce 3W reliably. I've had power bricks that dropped their voltage quite a bit when using more that like 75% of their rating.

@Gerben Thanks for the warning. I'm considering the following: CUI PBK-3-5 and Recom RAC03-05SC. The specs look decent to me, what do you think?

@Nyxynyx Those are absolutely fine. I was talking more of wall-adapters. I found those problems especially in phone chargers (my explanation is; phones don't need exactly 5v to charge their 3.7v battery, so the voltage drop is less of an issue, and makes the charger a few cents cheaper to make).

@Gerben I'm interested in trying out wall chargers for their supposedly lower costs! Do you have any wall chargers that you recommend that is in the 3-4W range and hopefully still compact enough when compared to the Recom RAC03?

Wall normally are cheap and full of ripple, 5v is given if you have an Rtot similar to official charged item. And btw phone and souch use internal regulator

Look at wall adapters that are known to work with Raspberry Pis. Pis are pretty fussy about their power, so if it works for a pi it should be pretty good.


text:
How to write arduino code in a c/c++ script
I'm pretty new to arduino. But I have some knowledge about programming in c/c++. I know that arduino is written in c. But it can't be used as normal c/c++ code.
for example ,
instead of including some libraries and write the code like this..
#include "arduino.h"

int main(){

    pinMode(13, OUTPUT);

    while(1){
    digitalWrite(13, HIGH);
    .....
    }
}

We have to write it using functions defined in arduino.
void setup(){
    pinMode(13, OUTPUT);
}

void loop(){
    digitalWrite(13, HIGH);
    .....
}

But I have some other libraries and programmes and stuff written in c and c++ and I need to use some arduino code in it and compile. So my question is, is there a way to write arduino in pure c/c++ as in first code snippet.
*I may not need arduino for this. My main target is to use servos, sensors in programms written in c/c++. But I would like to know what is the best way.

It is unclear to me, what exactly your problem is. Arduino code is C++ code. The only difference is what the IDE does before compiling (automatically including arduino.h and writing function prototypes for your defined functions, so that they can be placed whereever you want). The "Arduino functions" are defined in the header files, which are included via arduino.h. Are you trying to program an Arduino without the Arduino framework? Or do you just want to know how to avoid pinMode() and digitalWrite()?

Note: Your first code is just invalid C/C++, because you execute code outside of any function (the pinMode() function in this case)

Thanks I didn't noticed it. What I need to do is combine arduino code to my other c++ programs which uses servos and some sensors in some instances. When I use the ide I have to use setup() and loop() functions. What I need to know is can I write the code as in the first snippet and upload it into the board. If possible, how? Because arduino ide only support .ino files. not .cpp . What I meant by "best way" is that, should I use arduino for controlling servos and sensors or find some other way to connect them to my programmes.

So your question is more about the general project layout? What other C++ programs do you have, that need to be integrated with Arduino? When having programs on a PC and needing to interface peripherals like sensors and servos it is common to use an Arduino (or any other microcontroller), write a program for it to use the sensors  and servos and communicate with the PC over Serial/USB. Is that what you want?

Yes, that's exactly what I want. Should I need to upload the code to the board in order to use the sensors. It's certainly not possible. I'm building a device for reading and copying books. I have few c++ libraries written with opencv for image proccessing part and calculations. I planned to use arduino for the book handling device. I'm not sure is that possible as described in the question.

You won't run OpenCV code on the Arduino: it's not powerful enough for that. You will most likely have to write multiple programs that communicate and work together: one running on the Arduino for handling the books, an another one running on your computer for doing the image processing stuff.

Arduino IDE uses C++ not C.
You don't have to use setup and loop. This is a valid Arduino sketch:
#include <Arduino.h>

int main ()
  {
  init ();  // initialize timers
  Serial.begin (115200);
  Serial.println ("Hello, world");
  Serial.flush (); // let serial printing finish
  }  // end of main

But I would like to know what is the best way.

The way that works best for you. The IDE gives you some convenience functions. You don't have to use them. You can look at the datasheet and directly address the hardware registers.
See here for a few more details.

But how do I upload this to the board. If not possible how to connect the board to my c++ programs. ide is only compettible with .ino files.

@Alien5516788: you can easily convert a C++ program into a .ino program: just change the file extension to .ino.

You use the IDE to upload what I posted to the board. That was an Arduino "sketch". Plus, you can put C++ files into the same folder as the .INO files.

Did you read the link I mentioned in my answer? That shows using C++ files.

@Alien5516788, To be clear, only .ino/.pde files are subject to the kind of preprocessing that makes the Arduino "language" different from ordinary C++. The core, core libraries, and system libraries are all written in a mixture of .c/.cpp/.h files (broadly non-INO files) as is the majority (if not entirety) of most non-core libraries. The bulk code going into any typical Arduino project is in fact written in ordinary C++ (or C) code, whether the end user understands this or not. You are likewise not required to write much of any of your own code within .ino files.

Thanks, I read your article. I was trying to upload .cpp files to arduino board. Now it's all clear. Also I need to know how .ino files work. As described in the article, Arduino.h is included in .cpp file and .ino file is empty. How is that gonna work.

The IDE compiles all the .cpp files and links them together. So an empty .ino file isn't a big deal. The #include directives in the .ino file tell the IDE which libraries to include (link).

@Nick Gammon: The solution you gave here http://www.gammon.com.au/forum/bbshowpost.php?id=12625 is good but the justification less so since all 3 of your examples of bad prototype generation have, at least with IDE 1.8.19 and probably earlier, been fixed. If you still need to illustrate this with an example which currently fails, here is one: https://github.com/arduino/arduino-builder/issues/362

@6v6gt Ah, that was written 8 years ago. Like many things in the computer industry, old code does not necessarily travel well.

Indeed. The one positive thing about the Arduino automatic prototype generation feature is that there are simple work-arounds to avoid unwittingly using it. I'm sure that if we could go back in time, with our present knowledge, that feature would not have emerged in its current form.


text:
What should happen when sending analogWrite signal to a non-PWM pin?
I'm a very new to Arduino and any electrical engineering, I'm learning through some Youtube tutorials.
Based on my understanding though, sending analog signals to a non-PWM pin would just check for a threshold and send either LOW or HIGH, as opposed to being able to send variable voltages to a PWM pin.
BUT ... that's not what I'm seeing in practice...
Using Arduino UNO, I made a little project, for changing a blue LED's brightness. At first I did it through a PWM pin (pin 9) and it worked flawlessly. But then I tried seeing what would happen in a non-PWM pin (pin 8), you know cause you learn by trying and experimenting. So I switched to a non-PWM pin and ... it works the same exact way ...
I can change the brightness of the LED 5 different levels ... using analogWrite ... to a non-PWM pin ...
Thanks in advance

I guess your code switches the pin by calling analogWrite repeatedly. add your test sketch to the question

You might want to check the output signal with an oscilloscope. Perhaps they enhanced their library to use a timer and its interrupt to generate PWM by software.

I would also guess that you are just doing the dimming in code somehow. I just tested this with an Arduino Nano and the latest Arduino AVR core (1.8.6) and it is switching exactly between 2 levels: HIGH and LOW. And the code in wiring_analog.c is reflecting that. Please show us the code with which you got those 5 levels.

You need to show your code. Please edit the question and do that. I can change the brightness of the LED 5 different levels ... using analogWrite ... to a non-PWM pin ... . Show us!

Based on my understanding though, sending analog signals to a non-PWM pin would just check for a threshold and send either LOW or HIGH, as opposed to being able to send variable voltages to a PWM pin.

On the Uno you do not send analog signals anywhere. The PWM pins are merely digital outputs which turn on and off rapidly at a frequency and duty cycle that you specify.
You can, therefore, do the same thing to non-PWM pins by sending HIGH/LOW at a variable rate.
To comment more on why your code appears to be "working" we would need to see it.

What is the point of PWM pins if its also possible to send variable high/low signals to non-PWM pins?

Well, the PWM pins output high/low signals asynchronously. That is, without code having to do it. So, if you set up a timer (which is connected to the PWM pins) to output 100kHz then it will do that, regardless of what the code is doing at the time. You might be calculating prime numbers, but the hardware timers will mindlessly toggle that PWM pin on and off at the specified frequency.
If you try to make your own PWM in code, then the code has to do that and nothing else if it is going to output a consistent signal.

Hi Nick, thanks for the response. Yes I understand that concept of what PWM pins do by rapidly sending digital signals. My question was mostly theoretical stuff that's why I didn't show code. Based on your answer it is possible to also send variable signals (high/low) to a non-PWM pin, which is what had me confused. What is the point of PWM pins if its also possible to send variable high/low signals to non-PWM pins?
(This is the only part that has me confused about that)

@BlueStarXD See updated answer. In a lot of coding there is the easy way and the hard way. Manually doing PWM through code is the hard way.

I've got a page about the hardware timers which might help your understanding.


text:
Arduino Nano Doesn't Upload Any Code After Connecting It In Reverse (Rotated 180°)!
I've Made A PCB Which Includes An Arduino Nano. I Soldered Some Female Pin Headers Instead Of Soldering The Arduino Itself, So That I Can Easily Plug/Unplug The Arduino Board.
It Was All Good, Until I Accidentally Plugged The Arduino Nano Rotated 180°, Which Made Arduino Pin(12) Connected To The Vin(11.1v) At The PCB, And Arduino (Tx) Pin Plugged Into Pin(13)'s Place At PCB, And So On ...
The PCB's Power Was On (11.1v @ VIN Place At The PCB).
Now,

When I Power The Arduino Board It Looks Normal, 5v Pin And Vin Pin Works Good, No Power Issues, But The  Arduino IDE doesn't Upload Any Sketches To It, It Gives Me This Error:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I Tried Burning Bootloader With The IDE It Gave Me This:

avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

Error while burning bootloader.

I Tried To Upload Code With The IDE But Used USBsp Programmer, It Gave Me This:

avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

the selected serial port
 does not exist or your board is not connected

I Tried To Program The Board Using USBasp Programmer -with ICSP pins- and avrdude, It Gave Me This:

avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

I Also Tried To Upload Code, Or Burn Bootloader Using Another Arduino, But Didn't Work!

But When I Connect It To The Computer Using The Usb Cable, The IDE Detects It, And It Allows Me To Open The Serial Monitor!

So, What's The Problem? Is It Completely Broken, Or It Can Be Repaired??
I Suppose That The Atmega Is Burnt, As 11.1v Was On Pin(12), And Pin(11) Was Connected To Ground!!

Did you check with another Arduino that your circuit works in principle? Most probably you bricked your Nano.

ya, The Circuit Works Fine, I Tested It With Another Arduino ..

So your Nano is dead.

Fine  ...

Apparently your Nano is dead.
Depending on the specific device and your skills, you can try to replace the AVR on it. Please be aware that you need to flash the bootloader on it.

Buying A New One Is Easier Than Replacing Replacing The Atmega328p! ..

Well, then go ahead. ;-) Time is money under certain circumstances, but not necessarily at hobbyists. -- BTW, please reconsider your style to write any word capitalized.

I Will  ...

As a new user of SE/Arduino your might want to take the [tour] to learn how this site works. It is not a forum. -- For example, if you think an answer solves your issue, you mark it. This way your question will be shown prominently as "solved", you saw this probably already on the list, where the answers marker is colored and check-marked. Never edit the title to add something manually.