text:
HC-05 Module not receiving commands and not pairing
I'm working on a project where I'll need to establish a connection between two HC-05 modules, each connected to an Arduino, but for now I'm just trying to get one to work and connect to my phone, but I'm not sure if I'm doing anything right...
I'm not able to give AT-Commands, and as a result the device is not able to pair with my phone.
My setup looks something like this:

With minor differences being that I'm using an Uno board instead of a Mega, the RX and TX pins are connected to...well, I tried a lot of different pins, from the default RX/TX pins to specifying other pins like the ones in the code, as well as reversing the connections (RX to TX, TX to RX), also this schematic neglected to mention the 'ENABLE' pin, which I connected to my Arduino's 3,3V pin.
I tried a lot of different code samples, the latest one I tried is the following:
#include <SoftwareSerial.h>

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

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(38400);
  Serial.println("Enter AT commands:"); // a prompt in Serial Monitor
  // Deleted while loop, unnecessary

  mySerial.begin(38400);
}

void loop() { // run over and over
  //if (Serial3.available()) { // we don't use Serial3 any more
  if (mySerial.available()) {
    //Serial.write(Serial3.read());
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    //Serial3.write(Serial.read());
    mySerial.write(Serial.read());
  }
}

Which I blatantly ripped-off from this answer, with minor changes.
So, I connect my Arduino to my PC, upload the code, connect my module, set the serial monitor's baud rate to 38400 and...a bunch of gibberish appear on screen, just an alternating sequence of the characters 'x' and '?', to my understanding that's actually the message "Enter AT commands:" written in my code...
Now, with this exact setup, I'm now actually receiving a response to my commands, except the response is also gibberish, this is as far as I've gotten.
EDIT: By following some of the comments and setting the Serial baud rate to 38400, I managed to get other Reponses to my commands, but it's just a new type of gibberish and it's still not actually responding to my commands.
The thing is, all of the tutorials I've seen online are contradicting each other, some connect the RX and TX pins in reverse to the Arduino, some don't, some specify other pins on the board, some don't bother with the ENABLE pin entirely, some don't use a voltage divider, some connect VCC pin to the 3,3V instead of the 5V, some even skip the AT-Command setup entirely!
One last detail I feel like I should mention, there's a red light that blinks on and off every two seconds, I believe that means the module is read to receive commands but I've seen contradicting information about this as well so I'm not sure.
I want to know what I'm doing wrong, and what's the right way to do this?

I spent hours trying to figure this out too. So many pitfalls, RX vs TX, software serial vs pins 1/0, baud rates, NL & CR settings in the serial monitor, having to press the button while powering on the module.

It's been a year since I made this post and I sadly don't remember the setup I did to solve the problem, I think it might have been not using and resistors and just directly connecting the HC module to the Arduino, sorry but I'm not sure.

You have seen contradictory statements, because there are many variables here, that might be different for each of the tutorials.

some connect the RX and TX pins in reverse to the Arduino, some don't, some specify other pins on the board

There are basically 2 ways to communicate between the Serial Monitor and the HC-05:

You can connect the HC-05 directly to the USB Serial chip on the Arduino board, thus you would communicate directly with the HC-05. In that case the TX and RX pins are used, since they are connected to the USB Serial chip. But the labels TX and RX are referring to the Arduinos chip (Atmega328p at the Arduino Uno). Since serial connections need to be connected alternating (RX to TX and TX to RX), the pin labeled TX leads to the RX pin of the USB Serial chip and vice versa.
Thus you would connect TX of HC-05 to the TX pin on the Arduino and RX of HC-05 (through the voltage divider) to the RX pin on the Arduino. Also you should program the Arduino with an empty sketch before doing that, so that the Arduino does not interfere in the Serial communication with its own Serial usage.

Or you can use a SoftwareSerial interface and let the Arduino code translate between the devices. The Arduino received from the PC and sends the data to the HC-05. Also it receives from the HC-05 and sends that data to the PC. This is what you were trying. But you absolutely need to specify a different set of pins for the SoftwareSerial interface, than 0 and 1. These pins are doing the hardware Serial interface, which is connected to the PC. So change these pin numbers (for example to 2 and 3).
In fact: Whenever you see a code for Uno, Nano or Mega using SoftwareSerial on pins 0 and 1, you can be sure, that it is garbage.

I connect my Arduino to my PC, upload the code, connect my module, set the serial monitor's baud rate to 38400 and...a bunch of gibberish appear on screen

Even when you change the pins as described above, your code still uses 9600 baud for the connection to the PC. When you set the Serial Monitor to 38400 while the code uses 9600 baud for that interface, you will get just gibberish. Either change your Serial Monitor to 9600 baud or change your code to Serial.begin(38400). The last option is better, since that makes sure, that you are using the same baudrate for both interfaces.

some don't bother with the ENABLE pin entirely

The ENABLE pin seems to have a pulldown resistor on the HC-05 board, which pulls it to ground, when nothing is connected. Ground means data mode, HIGH command mode. So when they don't connect anything, they want to stay in data mode. Though this also depends on if the specific HC-05 board has a pulldown or pullup resistor there. Pulldown is more likely, but since there is no one single producer of these modules, you cannot be sure. Since you want to get into AT mode, you should use command mode and connect it to 3.3V. For normal operation it would go to ground. Though you can also connect it to a digital output pin of the Arduino and let the code decide in which mode the module should be.

some don't use a voltage divider

The chip on the HC-05 board is a 3.3V device. The actual breakout boards, that can be bought everywhere, mostly only add a voltage regulator from 5V to 3.3V, an LED for status display and break out the necessary pins. The data pins are mostly directly connected to the chip. There are many resources, that claim the HC-05 to be 5V tolerant, but also many that antagonize that. To be sure not to destroy the HC-05, you should also use a voltage divider.

some connect VCC pin to the 3,3V instead of the 5V

This is only done, when the used board does not have a 5V to 3.3V voltage regulator. Depends on the exact board, that you own.

some even skip the AT-Command setup entirely!

When they don't need to configure the HC-05 in a special way, why would they go into command mode. That might be different for you.

Voting yours up.  Seems to say everything mine says and more.  I'm guessing based on the length and detail you started before I did as well.

Ok, I changed the code to Serial.begin(38400), the "Enter AT commands:" message does appear as normal now, and the command responses are...less gibberish now, seem to be a mixture of '?'s and whatever command I typed, but it's definitely still not receiving the commands, I tried changing the device's name and it still appears as "HC-05" (The default name)on my phone, after that I switched the RX and TX pins to  2 and 3 respectively, and now it's not even responding to my commands.

Have you switched the physical connections of the HC-05 to the new pins and also changed the pin numbers in the code? and connected HC-05 TX to the RX of your SoftwareSerial interface?

Btw: Where exactly are you failing to establish the connection? When it appears on your phone, I assume, that the pairing would work. The real connection is then established by a fitting app. The Android bluetooth setting page (where you can pair devices) does not do the real connection.

@chrisl Yes, I have switched the physical pins to the new positions, and tried both combinations (RX to RX & TX to TX, and then RX to TX and TX to RX), still no response, as for how I'm trying to connect, I thought I was supposed to connect through setting page first, that's where I was failing, but I did try using a fitting app I already had installed (Bluetooth Terminal), but no luck, can't connect through that one either.

pins 2 and 3 on Mega don't support pin change interrupt used by SoftwareSerial

@Juraj I'm using an Uno, does that still apply?

@TheRiser You can add the new code version and the new wiring to your question by editing it. Just add it as an update at the end of your question. Then we can look further. Comments are not really made for discussions. Also that way someone else might see the problem, without going through all the comments

Alright, thanks.


text:
Any way a GSM sim 900 can still work (USA)?
so I’m pretty new to arduino and have been working for weeks on a GPS tracker using a sim 900 and a knock off neo 6M. All my code seemed to be working but for some reason I could not get the sim900 to establish a connection. Took me long enough to find out 2G carriers have been pretty much shut down. This is for a project and I don’t have time to start over with a 4G shield. Are there any cell carriers that still support 2G? What are my options? I don’t know what to do
Edit: more detail, I’m using the sim 900 to send an sms with a gps location

we don't either ... you did not say what you are doing, so it is impossible to guess any alternatives

Somehow I got a connection! I live in PA but when I went to Boston for school I got 2G service. Maybe carriers haven’t fully shut it down.

source: Stack Exchange

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

sort: votes


text:
if(Serial.available()>0) VS while(Serial.available()>0)
What's the low level difference between if(Serial.available() > 0) and while(Serial.available() > 0)? On what conditions would you choose one over the other?
I was testing my codes on 4 daisy chained 74HC595 shift registers controlling multiple LEDs. The code takes in a number from the serial monitor and displays it out in binary via the LEDs. Here is the code below that worked:
#define latchPin 8  //ST_CP pin of 74HC595
#define clockPin 9  //SH_CP pin of 74HC595
#define dataPin 7   //DS pin of 74HC595

//number of 74HC595 in daisy chain
#define numOfDaisyChainReg 4

byte registerVal[numOfDaisyChainReg];

void setup() {
    Serial.begin(115200);
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);
    pinMode(dataPin, OUTPUT);
}

void loop() {

  while (Serial.available() > 0) {

    uint32_t num = Serial.parseInt();
    Serial.print(num, DEC);
    Serial.print(" : ");
    Serial.println(num, BIN);

    //breaks the recieved int into 4 unsigned bytes
    //and assigns the byte value into the "registerVal" array
    for (uint8_t a = 0; a < numOfDaisyChainReg; a++) {
      registerVal[a] = (num >> (numOfDaisyChainReg - (a + 1)) * 8) & 0xFF;
      Serial.print("registerVal["); Serial.print(a); Serial.print("] = ");
      Serial.println(registerVal[a], BIN);
    }

    //writes the 4 bytes into the shift register
    digitalWrite(latchPin, LOW);
    for (uint8_t x = 0; x < numOfDaisyChainReg; x++) {
      shiftOut(dataPin, clockPin, MSBFIRST, registerVal[x]);
    }
    digitalWrite(latchPin, HIGH);

  }

}

Originally, I had if(Serial.available() > 0) and that didn't work as no LEDs lit up despite everything else in the code working as it was expected. Switching to while(Serial.available() > 0) solved that problem. Anyone have any idea why that's the case?

Turn up the warning level in File/Preferences with regard to while(Serial.available) without () , as in .available().

despite everything else in the code working as it was expected ... that may not be true

think of a sink full of dirty dishes .... if (dirtyDish.available > 0) {washDishOrNot()} , lets you go to sink, maybe wash a dish or a few, and go play ...... while (dirtyDish.available > 0) {washDishOrNot()} would have you stuck at the sink until there were no dirty dishes, or until you used an emergency escape

I'm hoping that it's just a typo, since it's not in the main listing, and answered the part I could.  And also that it doesn't just come down to not reading about  while and if.

@timemage opps it was a typo. The code section had it as 'Serial.available()' but forgot to put the '()' outside of that. My bad. I'll fix it.

@jsotola I had a feeling it'd be something like that. Curious to what ends/breaks that if(Serial.available() > 0) statement. Based on the logic of the code, I should finish the for loop inside before the if serial statement ends. By finishing the for loop, the shift register should be able to output to the LEDs.

the if statement checks availability of data ... you can assemble the received bytes in a buffer, if you want, or do nothing at all ... you would check each byte for end-of-data value ... normally a newline '\n' ... when end-of-data is received, you process the buffer .... the thing is, you could do other tasks when receiving serial data

@jsotola Let's say if I wanted to use if(Serial.available() > ) instead of `while' so the arduino does other tasks while receiving the int number I put in. What lines of code would I need to add to make it work like it was before?

https://majenko.co.uk/blog/reading-serial-arduino

@jsotola. Thanks! It was an interesting read. I'll implement it into my code for testing :)

I figured out why while(Serial.available()>0) and if(Serial.available() > 0) would or would NOT work in terms of my shift register code. It has to do with the serial monitor line feed and carriage return setting! If it isn't set to no line ending, it will either not register the input number or reset it back to zero right after the input is read. Learned to always check the line return option in the serial monitor! With this solved, the original question is nothing more than a general if vs while statement; which I already know the answer.
Thanks to everyone who contributed to this question! It did help me understand a lot more about Serial.available() in general. @jsotola gave a really good article. Combined with this YouTube video, it makes a lot more sense now.

Some implementations of the Arduino core have features that need loop() to exit regularly.  Although it's not often used, the serialEvent() is an example of one such thing, at least in the AVR Arduino core.
The ESP8266 Arduino core appears to do some task scheduling when loop() exits, among other things.
For your particular use case, it may make no difference at all, probably doesn't.  It may not even generate different code once compiled.  If you were doing something where you could not afford to exit loop(), run other stuff and re-enter loop() to run your code for a second pass, then there might be a performance reason to use your own while loop inside loop().  In your code as it currently is, the eventual blocking on Serial writes will end up limiting the execution to the same speed.

I'm a bit confused here. So you're saying there is a chance loop() function exiting/ending and that might break the code if using the if(Serial.available())?

I'm not sure I understand your question, and it seems like I should if the answer to it were anything other than "no, that wasn't what I was saying."  Since replacing the while in your code with an if results in loop() exiting more frequently, since that is the difference, and you asked "On what conditions would you choose one over the other?", that is what I addressed.  It's the best interpretation of your question that I could come up with.

Okay I get it now. Seems to me that the if statements doesn't behave as I'd expect it to when it's paired with the Serial.available(). It might exit pre-maturely.

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


text:
ESP8266 requires two resets to wake up from deep sleep
I'm working with the following circuit using a NodeMCU:
I have the solder jumper bridged between RST and BTN. In addition to what's in the schematic, pins 2, 3, and 4 of J1 are connected to the cathodes of 3 LEDs powered via pin 1 on the same connector.
I'm using the following code to test waking up from deep sleep:
#include <Arduino.h>

void setup() {
  delay(1000);
  Serial.begin(9600);
  Serial.println("start");
  ESP.deepSleep(0);
  while (1);
}

void loop() {
}

I build the code with -DDEBUG_ESP_PORT=Serial -DDEBUG_ESP_CORE and observe the following behaviour on the serial port after startup:
SDK:2.2.2-dev(38a443e)/Core:2.7.3-3-g2843a5ac=20703003/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
start
bcn 0
del if1
usl
enter deep sleep␀

This looks as expected to me (except maybe for the trailing ␀?). The current consumption is as low as I'd expect from deep sleep. I now pull RST low by pressing the push button once and see a few bits of garbage (different every time) being output in the device monitor - nothing else happens:
SDK:2.2.2-dev(38a443e)/Core:2.7.3-3-g2843a5ac=20703003/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
start
bcn 0
del if1
usl
enter deep sleep␀␀�

At this point current consumption increases from single-digit milliamps to a few tens of milliamps. However, a full reset doesn't seem to happen and my program doesn't appear to execute again from the beginning.
If I now pull RST low again with a second press of the push button I see a bit more garbage being output before a proper reset seems to finally happen:
SDK:2.2.2-dev(38a443e)/Core:2.7.3-3-g2843a5ac=20703003/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
start
bcn 0
del if1
usl
enter deep sleep␀␀�␕{��1S�
SDK:2.2.2-dev(38a443e)/Core:2.7.3-3-g2843a5ac=20703003/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
start
bcn 0
del if1
usl
enter deep sleep␀

This cycle then repeats, always requiring two button presses for a reset.
Similarly, if I try to upload a new program to the ESP8266 after it entered deep sleep initially, the upload will fail with:
A fatal error occurred: Timed out waiting for packet header
*** [upload] Error 2

Trying the upload again right after that does succeed. The next upload after that will fail again, and so on.
Based on those observations it looks to me like the ESP8266 doesn't get fully reset on the first button push, or it does get reset but enters some state in which it's not executing my application for some reason.
What could be the reasons for that? Is it something I can work around either in hardware or code?
Thanks!

Add Serial.flush(); after your print. Otherwise you'll never see it print anything.

@Majenko I do see the serial output I'm expecting before going to sleep, and using other indicators such as the LEDs or buzzer to find out if my program is re-executed after a reset have the same behaviour of requiring two resets.

random ideas: might want to hard pull gpio 0 and 2. might need caps on vcc, rst, etc. might be a noisy switch on 16. Could be a power-hungry attachment; does the problem persist w/o buzzer and LEDs?

I ended up taking the ESP8266 out of the circuit to test the reset behaviour in isolation and to compare it to other ESP8266s. It turns out that only the one unit out of a total of 6 that I tested had that behaviour. Putting a different ESP8266 back into the same circuit works just fine and only one reset is needed. I'm not sure if there perhaps was some damage to that one unit, but just replacing the component was more practical than debugging it further.

add delay(500) after Serial.begin to wait for the CH340 to wake up. else the print is lost. and add flush() after print to wait until it is sent before going to sleep.


text:
Is it safe to power multiple ESP32-CAM circuits from the same battery output?
I have setup two ESP32-CAMs, sharing the signal from a PIR sensor via an optocoupler.
Plus I have a 12V LED ring on a 5V to 12V booster, turned on/off by a relay.
The ESP32s go to deep sleep, wake up on the signal from the PIR sensor, turn on the 12V IR LED ring, take some photos and go back to deep sleep.
When they are on three separate power circuits, they seem to work well.
Is it safe to connect all these to the same USB output from an USB power bank?
Or can it be done safely at all?
(Could be similar to this question but I'm not sure.)
I am new at this and I don't have any intuition about whether that would create odd voltages and currents that might damage the components on the long-term, as they keep turning on/off and draw varying amount of power.
Instead of three USB connections like this:
(trying to illustrate only the power circuits)

I would like to power them on one USB connection:

There is no difference between your circuits. Internally to the powerbank all three outlets are typically wired together just like in your second schematic. One outlet or three outlets it's all the same.

I plugged in a multimeter and tested different configurations. In both cases the current only jumps up to ~150mA which is ok for the esp32. But on one battery USB output, the voltage dips down to 3V as different parts turn on/off, that's too low for the esp32 and it becomes unstable. Adding 4x100uF caps across the power rail didn't help. When they are on separate battery USB outputs, the battery maintains a steady 4.8-5V. I guess there's not much I can do about it, they have to be on separate outputs.

The LED ring is an FY-530, the specs say 200mA. I didn't see a voltage dip when it turned on, perhaps that part is ok. The problem could be that the two esp32 circuits on the same power source act as a voltage divider? Is there a technique to prevent that? The power bank seems to deal with it somehow, as they are designed to charge two or three phones etc. at the same time.

@Gambhiro Things in parallel don't divide the voltage, they divide the current. Maybe there is a mistake in your wiring.

Thanks for the comments, I'm sorry about the clueless question. A proper question would probably have to approach ESP32 power supplies in general. Perhaps it would be best to delete the question.


text:
Interfacing LM35 and MQ2 with Arduino
When I interface LM35 temperature sensor and MQ-2 gas sensor with Arduino - my LM35 sensor gave incorrect values. From research I've found out that MQ-2 gas sensor dragging the AREF voltage down and causing the error due to its 31ohm heater that drawn 161mA current . What'll I do to solve this problem?

A wiring diagram would help! But it sounds like you're powering your sensor from the Arduino's AREF pin. That is not the purpose of AREF; AREF is there for you to provide an accurate +5v or other reference voltage to the A/D convertor.
You need to power the sensor independently from your 5v supply (and not through the Arduino either, because of the sensors current draw); connect the sensor's Analog Out to one of the Arduino's A/D pins, sensor Ground to the supply ground. The digital out appears to be optional, if all you want is a go/no-go output that you adjust with the on-sensor potentiometer.


text:
Using WiFiServer in blocking mode
I am learning ESP32 network programming and I started by writing a simple telnet server. It uses a WiFiServer object to listen on port 23 and just log anything it receives to the serial monitor.
Sample code seems to be along the lines of:
  // Listen on port 23
  WiFiServer server(23);
  server.begin();

  // Loop to handle connections
  while (true) {
    // Wait for a connection
    WiFiClient client = server.available();
    if (client) {
      ...

This works fine, but the call to server.available() is non-blocking so the loop is running continuously and using 100% CPU. On a PC I would use a socket in blocking mode so that calling accept() would suspend the thread until data was available. I do this because it's pretty antisocial to consume 100% CPU on a multitasking OS.
My question is whether there is a way to make Server.available() behave like the sockets accept() function and block until a connection is available. If not, what is considered best practice? Just let the CPU run at 100%, or is there some better way to code this more efficiently? Maybe just use the same BSD sockets API that I would on Linux?

just let the arduino thread run as the RTOS schedules it

@Juraj I am creating tasks (using vTaskCreate()) to hand off the client to, like the accept then fork approach in Linux. If I let the main thread spin won't that starve the other tasks of CPU?

add a small delay if you want. the WiFiServer and WiFiClient are implemented over Berkley/POSIX sockets API of the IDF/LwIP. maybe you want to use it directly

@Juraj Thanks :-)

It seems there is no way to make the WiFiServer available() function block until it receives a connection. If CPU usage is an issue the solution appears to be a short delay after calling the function, as Juraj suggested in a comment.
If anyone is interested the sockets API works fine. I put together the code below as a quick test and it works as expected. If you telnet to the ESP32 it prints a message then closes the connection:
#include <lwip/sockets.h>
#include "WiFi.h"

void ConnectWiFi() {
  WiFi.begin("my_ssid", "my_password", 6);
  int loopcnt = 0;
  while (WiFi.status() != WL_CONNECTED) {
    Serial.printf("Connecting: time %d, WiFi status = %d, signal = %d\n", loopcnt++, WiFi.status(), WiFi.RSSI());
    delay(1000);
  }
  Serial.printf("Connected: %s\n", WiFi.localIP().toString().c_str());
}

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

void loop() {
  // Create, bind and listen on port 23
  int sock_srv = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

  struct sockaddr addr_in;
  memset(&addr_in, 0, sizeof(addr_in));
  struct sockaddr_in* p_addr_in = (struct sockaddr_in*) &addr_in;
  p_addr_in->sin_family = PF_INET;
  p_addr_in->sin_port = htons(23);
  p_addr_in->sin_addr.s_addr = INADDR_ANY;
  bind(sock_srv, &addr_in, sizeof(addr_in));

  listen(sock_srv, 1);

  // Loop to handle connections
  while (true) {
    // Wait for a connection
    sockaddr addr_client;
    memset(&addr_client, 0, sizeof(addr_client));
    int sock_client = accept(sock_srv, &addr_client, NULL);
    Serial.println("Accepted connection");

    // Just end a message then close the socket
    String s = "Welcome and goodbye!\r\n";
    send(sock_client, s.c_str(), s.length(), 0);
    closesocket(sock_client);
  }
}

Hi, and welcome to Arduino:SE.  I'm not sure if this was intended to be an answer to your question or supplementary information (which should probably be edited into your question, rather than posted as an answer).

@sempaiscuba good point, it's an alternative approach not an answer to whether WiFiServer can be made to work in blocking mode. I'll delete it until I have an answer to that.


text:
unexpected behaviour of encoder with increasing rpm
I am using a DC motor with encoder, and I am trying to calculate how many pulses are  recorded in every one second interval. (note that the power source is of 12V for the motor)
Circuit and code:

int encpin=3;
volatile long npc=0; //new pulse count
volatile long opc=0;  //original pulse count
volatile long pulsecount;
unsigned long int newtime;
unsigned long int prevtime=0;
unsigned long int time;
void setup()
{
  pinMode(encpin, INPUT_PULLUP);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(encpin),function,RISING);
}
void function(){
  npc++;
}
void loop()
{
 newtime=millis();
 time=newtime-prevtime;
 pulsecount=npc-opc;
  if(time==1000){
    Serial.println(pulsecount);
    prevtime+=1000;
    opc=npc;
  }
}

It seems to be rather intuitive that increasing the rpm should increase the number of pulses recorded in one second. However, the results are rather erratic:
 RPM  PULSECOUNT
  26    2365
  32    2367
  38    2400
  44    2375
  52    2400
 116    2412
 142    2384
 195    2416
 280    2406
 350    3008
 416    1580
 520    1975
 624    2370
 730    2334
2737    2188

Increasing RPM sometimes increases the pulsecount, but sometimes decreases it....what could be the reason for this behaviour?

You still check for time==x? Seriously??!

One important principle to learn when working with interrupts is that of atomic operations.  It is vital, when working with any data that cannot be manipulated by one single assembly instruction, that you protect against that data being changed midway through any reading of that data.
In your situation you are working with 32-bit values. On an 8-bit microcontroller those take many many instructions to manipulate, and at any time during that manipulation the interrupt can be triggered and change the value, corrupting your readings.
There is a concept in programming called critical sections. These are "blocked off" bits of code where no interrupts are allowed to happen while you do whatever is needed to your shared variables. For obvious reasons you want to keep those sections as brief as possible.
Also you don't need to calculate the pulse count by comparing it to the previous count - just start from 0 each second. And on the topic of a second, it's best to check if at least a second has passed. There's always a chance you may see 1001ms instead of 1000ms. A slim chance, but best to be safe.
Here's an example, using your code as a base:
void loop() {

    if (millis() - prevtime >= 1000) { // you should check for more time passing than you expect
        prevtime += 1000; // Don't assume you always had 1 second, force it instead

        // This block is the "critical section". Keep it as short as possible
        // so just grab the data and reset the count.
        noInterrupts(); // Stop any interrupts happening
        uint32_t currentCount = npc; // Grab this second's count
        npc = 0; // And reset the count to zero
        interrupts(); // Release the block on interrupts

        // And output the results.
        Serial.println(currentCount);
    }

}

I think the problem is in the tinkercad simulation:
The encoder is attached to the motor and the motor is always rotating at the same speed. Selecting a different RPM on the component changes the gear ratio and the RPM of the shaft, but not of the motor. That means that the number output after 1s should be always the same.
Why it is not exactly the same, only the programmers of the simulation can tell.
It might have to do with simulation speed, because I get totally different numbers there.
To tell exactly what is going on, a documentation of the components in the simulation and of the simulation would be necessary.

what numbers are you getting on your end? And more importantly, are they following the expected trend: i.e rising with RPM?

they are in the range of ~1600 and changing randomly depending on the RPM setting of the motor, but they are also not consistent during 1 run


text:
Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to 180 when joy is forward or back
Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to +180 when joy is forward or back.
I just cant seem to figure out the mapping or setup for the code for this part.
I remember seeing it done before but my google skils are failing me and i cant seem to find it again.
Thanks

it is a simple arithmetic problem ... convert -180 0 180 to 180 0 180

jsotola. I know it should be something simple. But cant seem to get it working.  Any help on actually doing it would be appreciated

You could map from -180 to 180 and then take the absolute value of that. I'm sure there is a function for that

use something like this if (val < 0)  val = 0 - val;

Try this one although, the others answered you properly :
#include <Servo.h>
Servo myservo;
int potpin = 1;
int val;

void setup () {
    myservo.attach(9);
}

void loop () {
    val = analogRead(potpin);
    val = map(val, 0, 1023, 0, 360);
    myservo.write(val);
    delay(20);
}

Connect the signal wire of your Servomotor to PWM pin number 9 of Arduino
Connect the output of your joystick to A1 pin of your arduino
Actually i'm not sure about one of that lines and i forgot the correct form, if didn't work, change this line :
val = map(val, 0, 1023, 0, 360);

To this :
val = map(val, 0, 1023, -180, 180);

I think both of them works
Good luck

You can use the map function, see Arduino Map Function.
So in your case, assuming a value of 0..1023 coming from an analog pin, where 0 needs to be mapped to -180 and 1023 to +180, you get
int mappedValue = map(value, 0, 1023, -180, 180);

(note I assume you mean -180 when backwards, +180 when forwards).
UPDATE
It seems value 0 (backward) needs to be mapped to 180, 512 (neutral) to 0, and 1023 (forward) to 180 (again).
For this you need two maps depending on the value:
int mappedValue = 0;
if (value < 512) // Backwards
{
    mappedValue = map(value, 0, 511, 180, 0);
}
else // Forward
{
    mappedValue = map(value, 512, 1023, 0, 180);
}

Im tyring to get the servo to move + 180 when the joy is forward.   And also +180 when the joy is pulled back. And the servo to sit at 0 when the joy is in netural. The servo im using has a range from 0-180

and what are the values of the joystick in forward, neutral and backward positions?

The joystick values are 0 for back. 1023 for forward.   Thank you


text:
Why does Adafruit guide for motors use transistors on ground rather than modulating the power source
I'm going through the Adafruit Motors guide for Arduino, found here, and I'm struggling to understand how each of these parts play in. From what I understood, pulse width modulation is basically a way to send varying levels of power through a digital output source. Additionally, it seems that the guide is using a transistor with the PWM signal as the gate, so it can allow the percentage given by the PWM signal to control how much flow is given to the motor. However, what I'm confused here is that both the power and ground are interfacing with this transistor/diode setup.
This is more specifically what I mean, on the bottom seems really simple: the PWM signal comes on the yellow wire, fed through the resistor so that it doesn't fry the transistor into the gate.
After this though, there's a ground signal being passed into the source leg of the transistor, and the sink leg is connected to both a diode for power AND the ground of the motor? I might be misunderstanding how a diode works but this doesn't seem to make sense as to why the ground signal is being modulated.

My initial thought for this would be a system where only the power of the motor is varied by the PWM signal, sorta like in this way (apologies for the terrible drawing style, I haven't gotten used to some of the Arduino sketching software online):

I've not gotten to try this yet, but I assume it wouldn't work or would destroy components somehow since this does seem to be a simpler solution, and it's not being used. I was sorta trying to figure out 1) why my solution would be bad and 2) how the official solution works, as they haven't really given any actual schematic (not that I would understand it, haha) Any help would be appreciated! Thanks!

Tip: the blue line "going up" that you marked GND, is not really GND but one of the motor connections. The motor is connected between 5V and the diode's Anode (and the transistor's collector). You can use the integrated schematic editor to make a clearer drawing.

There's a schematic on the transistor page.

do keep in mind that electrons flow from negative to positive, so it does modulate the source of power as shown.

I think your confusion does indeed stem from the diode. You can forget the diode, it doesn't feature in the switching of the motor. When a motor runs it can generate large negative voltages caused by the repeatedly collapsing magnetic field. The diode, which is connected backwards, exists to take those negative voltages and prevent them damaging the rest of the circuit.
The transistor arrangement in use is called common emitter, and is also known as a low-side switch when used in saaturation between the load and GND, as in this situation.  It doesn't matter to the motor if you have the switch between the motor and GND (using an N-channel MOSFET or NPN bipolar transistor) or between power and the motor (using a P-channel MOSFET or PNP bipolar transistor), but it does matter to the Arduino.
It is harder to switch a "high side switch" from an Arduino, especially if your power supply is higher than the voltage the Arduino runs at. Since the switching is controlled by the difference in voltage between the "common" point (emitter [BJT] / source [MOSFET]) and the switching signal (Arduino), which is limited to 5V, any "common" point voltage that is higher than that is unreachable by the switching signal, so ends up in being always on and the switching fails.
It is possible to switch the high side, but you need an extra driving stage to allow the higher voltage switching.
For this specific circuit where the power is 5V it's not as susceptible to the problem, but this is a rare case. Normally you will be driving motors at a higher voltage, such as 12V, and there you will need an extra driving stage, or just use the far simpler low-side switch arrangement this circuit teaches you.

this makes a lot of sense but I had one question regarding that flyback diode, does it matter whether the end of it feeds back into the pulse-modulated ground or could I feed it back into a normal ground wire?

@Daneolog Not sure what you mean there--it needs to be explicitly across the motor since it's the motor generating the negative voltage.

Its purpose is to form a circuit between the two pins of the motor in reverse.

oh yeah no I meant like, the other side of it, that's pointing at the same line as the transistor's output, is pointing to a modulated ground

oh, I see, so it's not just a means of emptying out all the negative energy into a ground, it's feeding it back in

@Daneolog I think you're under the impression that "ground" is something special. It's not. It's just a wire in the circuit. There's no "modulated ground", only a switch in series with the motor.

but the thing about that is that there's definitely a difference in signal between the ground that comes directly from the Arduino and the output of the transistor, that's what I'm referring to as some kind of modulated signal

"ground" is nohing more than an arbitrary point in the circuit against which other volatges are refereced.

do you mind if I talked about this in chat for a bit? I'm still a bit confused as to how this diode works as it relates to both ground and power

Let us continue this discussion in chat.

Your schematic
The blue line in your first schematic "going up" that you marked GND, is not really GND but one of the motor connections. If you look at the Adafruit schematic you can see this.
The motor in the Adafruit schematic in the link you provided is connected between 5V and the diode's Anode (and the transistor's collector).
Flyback diode
The diode is a so-called "flyback diode", connected between the motor connections to "soak up" back-EMF that occurs when the motor is turned off and its magnetic field collapses. If the diode would not be there, there would be a voltage spike on the transistor's collector, possibly damaging it.
Low-side switching
The "Adafruit" solution uses an NPN transistor as a switch on the low side of the motor when the I/O pin is high, like the schematic on the right. This is a very common setup as it has almost no disadvantages.
High-side switching
Your own suggestion (called high-side switching, shown on the right) would work as well (with the addition of a flyback diode) but it would need a different type of transistor, a PNP transistor. Also, the I/O inputs would work in an inverted way: when the I/O pin is low, the motor will be on and when the I/O pin is high, it will be off.
Note that high-side switching will only work when the supply voltage is lower or equal to the voltage that's on the I/O pins. You can't turn on a 12V motor this way, for example. With low side switching, you will not have this problem and you can switch higher voltages.

simulate this circuit – Schematic created using CircuitLab

ohhh, I see. so basically motors can run both ways, if you block ground by a specific amount, it would block movement by that amount in the same way you blocked power by that amount, but the method of blocking ground is easier because it allows you to have the same setup for any size motor, just having a power source strong enough for the motor. that makes lots of sense! thank you so much!


text:
ESP32 SocketIO Client is not connecting to Flask-SocketIO Server
I'm trying to connect a ESP32 client using SocketIO with a Flask-SocketIO server and it's not getting connected.
The server uses SSL. The local server address is https://192.168.1.137:3000.Is the https causing issue here?
The following is the output from the ESP32 in the serial monitor. Note that esp32 successfully connects to the wifi.
> ["myEvent",{"now":95506}]
> [IOc] Disconnected!
> [IOc] Disconnected!
> [IOc] Disconnected!
> ...

Esp32 code:
/*
* WebSocketClientSocketIOack.ino
*/

#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>

#include <ArduinoJson.h>

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

WiFiMulti WiFiMulti;
SocketIOclient socketIO;

#define USE_SERIAL Serial

void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
    switch(type) {
        case sIOtype_DISCONNECT:
            USE_SERIAL.printf("[IOc] Disconnected!\n");
            break;
        case sIOtype_CONNECT:
            USE_SERIAL.printf("[IOc] Connected to url: %s\n", payload);

            // join default namespace (no auto join in Socket.IO V3)
            socketIO.send(sIOtype_CONNECT, "/");
            break;
        case sIOtype_EVENT:
        {
            char * sptr = NULL;
            int id = strtol((char *)payload, &sptr, 10);
            USE_SERIAL.printf("[IOc] get event: %s id: %d\n", payload, id);
            if(id) {
                payload = (uint8_t *)sptr;
            }
            DynamicJsonDocument doc(1024);
            DeserializationError error = deserializeJson(doc, payload, length);
            if(error) {
                USE_SERIAL.print(F("deserializeJson() failed: "));
                USE_SERIAL.println(error.c_str());
                return;
            }

            String eventName = doc[0];
            USE_SERIAL.printf("[IOc] event name: %s\n", eventName.c_str());

            // Message Includes a ID for a ACK (callback)
            if(id) {
                // creat JSON message for Socket.IO (ack)
                DynamicJsonDocument docOut(1024);
                JsonArray array = docOut.to<JsonArray>();

                // add payload (parameters) for the ack (callback function)
                JsonObject param1 = array.createNestedObject();
                param1["now"] = millis();

                // JSON to String (serializion)
                String output;
                output += id;
                serializeJson(docOut, output);

                // Send event
                socketIO.send(sIOtype_ACK, output);
            }
        }
            break;
        case sIOtype_ACK:
            USE_SERIAL.printf("[IOc] get ack: %u\n", length);
            break;
        case sIOtype_ERROR:
            USE_SERIAL.printf("[IOc] get error: %u\n", length);
            break;
        case sIOtype_BINARY_EVENT:
            USE_SERIAL.printf("[IOc] get binary: %u\n", length);
            break;
        case sIOtype_BINARY_ACK:
            USE_SERIAL.printf("[IOc] get binary ack: %u\n", length);
            break;
    }
}

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

    //Serial.setDebugOutput(true);
    USE_SERIAL.setDebugOutput(true);

    // USE_SERIAL.println();
    // USE_SERIAL.println();
    // USE_SERIAL.println();

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

    WiFiMulti.addAP("ssid", "mypass");

    //WiFi.disconnect();
    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
    }

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

    // server address, port and URL
    socketIO.begin("192.168.1.137", 3000, "/socket.io/?EIO=4");

    // event handler
    socketIO.onEvent(socketIOEvent);
}

unsigned long messageTimestamp = 0;
void loop() {
    socketIO.loop();

    uint64_t now = millis();

    if(now - messageTimestamp > 2000) {
        messageTimestamp = now;

        // creat JSON message for Socket.IO (event)
        DynamicJsonDocument doc(1024);
        JsonArray array = doc.to<JsonArray>();

        // add event name
        // Hint: socket.on('event_name', ....
        array.add("myEvent");

        // add payload (parameters) for the event
        JsonObject param1 = array.createNestedObject();
        param1["now"] = (uint32_t) now;

        // JSON to String (serializion)
        String output;
        serializeJson(doc, output);

        // Send event
        socketIO.sendEVENT(output);

        // Print JSON for debugging
        USE_SERIAL.println(output);
    }
}

Server code (Removed unrelated parts):
from flask import Flask, render_template, Blueprint, current_app, request, session, url_for, render_template
from flask_socketio import SocketIO, emit

from threading import Thread
from queue import Queue
import logging

loggerPath = baseUrl + "logs/appLog.log"
os.makedirs(os.path.dirname(loggerPath), exist_ok=True)
with open(loggerPath, "a") as f:
    logging.basicConfig( level=logging.INFO,
        # format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        format='%(levelname)s - %(message)s',
        filename=loggerPath
    )
bp = Blueprint('audio', __name__, static_folder='static',
            template_folder='templates')
app = Flask(__name__)

async_mode = "threading"

socketio = SocketIO(app, cors_allowed_origins="*", async_mode=async_mode)

@socketio.on('myEvent')
def test_connect(data):
    logging.info("receiving")

def runApp():
    try:
        certificatePath = os.getenv('BASE_URL')+"SSL/"
        key = certificatePath+"localhost.key"
        certificate = certificatePath+"localhost.crt"
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain(certificate, key)
        ip = socket.gethostbyname(socket.gethostname())
        socketio.run(app, host=ip, port=3000,ssl_context=context)
    except Exception as e:
        logging.error("Exception occurred in: "+__file__, exc_info=True)

q = Queue()
t = Thread(target=wrapper, args=(q, runApp), daemon=True)
t.start()

have you examined the ESP32BasicExample sketch?

Above code is from the WebSockets_Generic\examples\esp32\ESP32_WebSocketClientSocketIO\ESP32_WebSocketClientSocketIO.ino

This is version Socketio issue,I have successfully connected .
This installed version
Werkzeug 2.0.0
Flask 2.3.3
Flask-SocketIO 4.3.1
python-engineio 3.13.2
python-socketio 4.6.0


text:
I2S read() is which channel?
The Arduino I2S reference describes the I2S standard and functions available with the standard I2S library, (Bizarrely it doesn't reference the existing read() function which is used in the examples but that is beside the point). There also exists an ArduinoSound library, however I have the same issue with this.
I would like to record audio from WM8731 connected up to Arduino. I am using an SAMD arduino part.
But, I have a tremendous issue with the I2S.read() function. The I2S.read() function only returns a singular value, however the I2S standard is intrinsically stereo.
This is particularly important for my project as I am only interested in the LEFT channel as the RIGHT channel is muted.
I would expect this to either:

return a pair of values (i.e left /right) samples for that particular point in time , OR
return a singular sample with extra information telling me which channel that is was retrieved from.

However it seems this is not the case. (Github)
I also assume that the I2S is buffered making it impossible to simply read the WS pin state, as I will probably be popping a sample from the buffer that was push into the buffer at some point in the past.
So, is it possible to know which channel the sample was returned from the I2S.read() function or does this mean that the library needs to be modified?
I am more interested in using the samd library as other libraries such as AudioLibrary is limited to 16-bit - I need 32-bit resolution.

From my understanding it's just retrieving subsequent samples from the DMA buffer, which means you will alternately get left and right samples from each read. It would be more normal to use the read(buffer, len) variant to read two (or more) samples at once.
int16_t pair[2]; // change to int32_t for 32 bit samples
I2S.read(pair, sizeof(pair));

Thanks. It helps, however using this method would there not still be a possibility that the channels may be swapped? Will this ensure that the first member of the pair is always the LEFT or RIGHT (e.g.)? I find that the Arduino documentation, library and examples are extremely lacking with this regard and to my astonishment does not seem to concern most folk in the community

Your always dealing with an entire dma buffer, so should always be the same.

Thanks, I have tested this however occasionally I am getting all LEFT and sometimes all RIGHT on pair[0]  depending when I start reading. which is my main problem

I think part of the problem is that the whole library's methodology is flawed. You hjave DMA driven ping-pong buffers which receive the data constantly, and you must deal with an entire buffer in less time that it takes to fill the other buffer. You may be better off using the onReceive() callback to run a function at the moment the buffers swap, at which point you must read the entirety of the buffer, otherwise it will stall (by the looks of things).

thanks for the help - you've certainly understood the problem and it is worth recording (no pun intended) for others to know about. For now as my project only requires one channel I can simply put split the one channel into both left and right so that in this case it doesn't matter and I will always read the same channel regardless, however that's just a sticking plaster.


text:
Fubarino (microchip pic32mx), Second timer interrupt is not firing
volatile uint32_t counter_timer = 0;
void __USER_ISR myISR() {
  counter_timer++;
  clearIntFlag(_TIMER_3_IRQ);
}

void __USER_ISR myISR_timer_four() {
  clearIntFlag(_TIMER_4_IRQ);
  TMR4 = 0x16E3600;
  Serial.print("hi\n");
    if(PORTAbits.RA10 != 1){
      LATAbits.LATA10 = 1;
    }
    else{
      LATAbits.LATA10 = 0;
    }
}

void setup{

  T3CONbits.TCS = 0b0; // Timer Clock Source Select bit
  T3CONbits.TCKPS = 0b000; //0b111; // Timer Input Clock Prescale Select bits
  T3CONbits.ON = 0b1; //0;//0b1;
  asm("nop \n");

  T4CONbits.TCS = 0b0;
  T4CONbits.TCKPS = 0b000;
  T4CONbits.T32 = 0b1;
  TMR4 = 0x16E3600; // half of 48mHz.
  T4CONbits.ON = 0b1;

  setIntVector(_TIMER_3_VECTOR, myISR);
  setIntPriority(_TIMER_3_VECTOR, 4, 0);
  clearIntFlag(_TIMER_3_IRQ);
  setIntEnable(_TIMER_3_IRQ);

  setIntVector(_TIMER_4_VECTOR, myISR_timer_four);
  setIntPriority(_TIMER_4_VECTOR, 1, 0);
  clearIntFlag(_TIMER_4_IRQ);
  setIntEnable(_TIMER_4_IRQ);

 TRISAbits.TRISA10 = 0;  // Fubarino onboard yellow led
}

void loop() {
delay(500);
Serial.println(counter_timer);
Serial.println(TMR4, DEC);
}

Hi,
i wanna use multiple interrupts, i got the information from a document i got from: Majenko Technologies.
the interrupt bound to Timer3 works, this was the example code in the pdf.
now i "assembled" a second interrupt bound to timer4, copy, paste and adapt, but that isn't working.
i can print the "content" of the timer4 register and it's running.
have i done something wrong?
search engine didn't yield a answer.

The problem was that you need to combine the even and the next odd timer (see datasheet of the microchip pic you're using) to form a 32 bit timer.


text:
Problem deseralizing some fields in JsonRequest
I'm almost successfully able to GET a json blob and print it to the console. It seems to be failing on some string fields I am guessing because of the length. Any thoughts/ideas/suggestions to make this work?
The requested json blob (I can see this entire string from the console, it is spaced out here for readability). The entire length of the original string happens to be 597 characters.
{
    "expand":"schema,names"
    ,"startAt":0
    ,"maxResults":50
    ,"total":2
    ,"issues":[{
         "expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields"
        ,"id":"94245"
        ,"self":"https://myServer.atlassian.net/rest/api/3/issue/9425"
        ,"key":"BP-4349"
        ,"fields":{
            "summary":"QM: API Timeout Error on Checkout "
        }
    }
    ,{"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields"
        ,"id":"93129"
        ,"self":"https://myServer.atlassian.net/rest/api/3/issue/9319"
        ,"key":"BP-4078"
        ,"fields":{
            "summary":"Search \"term\" options - broken in loader see sproc"
        }
    }]
}

The code I'm using to fetch this json object reduced as much as possible:
JsonRequest request(2048);
//...snip...// (inside JsonRequest object)
WiFiClientSecure *client = new WiFiClientSecure;
HTTPCliernt download_client;
download_client.begin(*client, url);
download_client.collectHeaders(headerKeys, 5);
download_client.setAuthorizationHeader(authValue);
download_client.setUserAgent( HARDWARE_NAME );
int httpCode = download_client.GET();
if(httpCode == HTTP_CODE_OK)
{
    String result = download_client.getString();
    download_client.end();
    client->stop();
    dsError = deserializeJson(*this, (uint8_t*) (result.c_str()) );  //this refers to this object which is the JsonRequest
    if(!dsError)
    {
        ...
        return true;
    .....
(outside JsonRequest object, request is a deseralized `SpiRamJsonDocument` )
//...snip...//

int total = request["total"].as<int>();                         //working: 2
int startAt = request["startAt"].as<int>();                     //working: 0
int maxResults = request["maxResults"].as<int>();               //working: 50
int totalRecords = total + startAt;
for(; startAt < totalRecords && maxResults > 0; startAt++, maxResults--)
{
    log_i("%s: %s - %s"
        ,request["issues"][startAt]["key"].as<String>()                 //working: BP-4349
        ,request["issues"][startAt]["fields"]["summary"].as<String>()   //broken? (garbage string)
        ,request["issues"][startAt]["self"].as<String>()                //broken? (garbage string)
    );

}

I don't know why some strings worked and some did not. I assume that the length of the string is the problem ?
How would you suggest I retrieve the longer strings ?
How do I know when the length dictates the use of .as<String>() vs something else?

Maybe it chokes on the escaped quotes (\") within the last string?

@EdgarBonet thanks for the thought. I tried removing the quotation marks (from the json result) this did not change the result.

Turns out there is a arduino json troubleshooter specifically for this type of issue here: https://arduinojson.org/v6/troubleshooter/  wow awesome. If you are having an similar issue I would start there.
This didn't fix my problem, for myself if I cast the types to const char * meaning
...snip...
const char* x = request["issues"][startAt]["self"].as<const char *>()
log_i("%s", x);
...snip...

this worked every time for every string


text:
Why would a serial device not be sending the correct start code?
I am unable to get any reading from a PMS5003 connected to an ESP32.
In trying to debug this problem, I have a very minimal setup. Only the PMS5003 is connected to the ESP32, and using the following the code.
#include <Arduino.h>
#define PMS_DEBUG
#include <PMSerial.h>

SerialPM pms(PMSx003,Serial2)

void setup() {
  Serial.begin(9600);
  Serial2.begin(9600);
  pms.init();
}

void loop() {
  pms.read();
  Serial.println(pms.pm25);
  Serial.println(pms.status);
}

pms25 always returns 0. When the PMS5003 is properly connected to the ESP32, status always returns "Wrong message start".
Why would the device be sending the wrong start code, and what steps can I take to debug this?
I have tried connecting to different serial pins, including following the ESP32 software serial example provided by the PMSerial library. In all cases, it simply looks as though the PMS5003 sensor is mot transmitting anything - indeed no fans are switching on and there is no sign of life at all from the device. However, I am very much a beginner, and don't know enough to tell whether this is a problem with the device, the library or something I have done.
Very grateful for suggestions how to debug this.
Edit
example serial data
0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x6D, 0x0, 0xE0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x97, 0x0, 0x0, 0x0, 0xF8,

0x0, 0x0, 0x0, 0x0, 0xA, 0x0, 0x0, 0x1, 0x0, 0xB0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0xBB, 0x1, 0x0, 0x5F, 0x0,

Are you sure, that the device ia working at 9600baud?

It would be helpful if you know what library you use. I found this one https://github.com/avaldebe/PMserial. The author provides some examples. Each of these  checking the state of pms with if (pms) after read. and only use the data if this is true. So perhaps the sensor is permanently read, but need some time to generate new data. So you have to check if the data is valid.

It seems the sensor signalizes that the data is valid with sending a 0x42 as a start byte. I've found an Arduino Project, which only uses the seirial connection, no extra driver and they only use the data if this 0x42 is received. Here is the link: https://how2electronics.com/interfacing-pms5003-air-quality-sensor-arduino/

thanks @PeterPaulKiefer! pms is never true because the 0x42 start byte is never received. I've added above an example of the data I'm receiving. I have double checked all my connections. As the start byte is not received, should I assume there is a problem with the sensor? Or are there other possible causes?

thanks @chrisl, the datasheet claims a default baud rate of 9600bps. added some links above

Can you show us how you have it wired to the ESP32?

The bytes you show have many sequences of consecutive bits. Please double check your connections and baudrate. Do you happen to have an oscilloscope? If so, probe the line and check the baudrate.

Sorry for the late answer. I was not notified, perhaps because of the ! behind the Name??   Perhaps (like mentioned in other comments) the baud rate is set to a non default. If you have access to an osci you could check that. Alternatively you could try out some common baud rates. Another good approach is to add a picture of your setup and the schematics. Then you got some reviews, that's also a form of trouble shooting. There are some rules mentioned in the documentation of the sensors. Did you pay attention to those. (e.g. Do not connect RESET if it is not used.)

thanks everyone for these suggestions. apologies for slow reply, things became very busy! I managed to borrow some spare components to test my project. Turns out there was a fault with the cable I was using to attach the PMS5003 sensor. Replaced the cable, everything works. Simple fix, but quite annoyed with myself for not checking this sooner!


text:
Writing file from SD card to ethernet client stops sending after about 2980 characters, STM32f7 board
I am attempting to write a file found on an SD card to a connected Ethernet client. The file opens fine, and we have no problems writing to the client. For testing purposes I also write the lines read from the file to the serial port at the same time as being written to the client. What is happening though, is that the entire file contents are displayed in the serial monitor, but the browser only receives about 2978 characters. the actual file, not including the header, sent separately, is 4426 bytes long. I ran a test sending about 260000 via 8000 "client.print(...)" statements and this worked fine.
I have attached code. Anything not necessary to the basic function of the code has been stripped out to give us the minimum required to debug. I am using the libraries EthernetWebServer_SSL_STM32 & sdFat. My code is derived from the WebServer example.
/****************************************************************************************************************************
  WebServer.ino - Simple Arduino web server sample for ESP8266 AT-command shield
  For STM32F/L/H/G/WB/MP1 with built-in Ethernet LAN8742A (Nucleo-144, DISCOVERY, etc) or W5x00/ENC28J60 shield/module

  EthernetWebServer_SSL_STM32 is a library for STM32 using the Ethernet shields to run WebServer and Client with/without SSL
  Use SSLClient Library code from https://github.com/OPEnSLab-OSU/SSLClient

  Built by Khoi Hoang https://github.com/khoih-prog/EthernetWebServer_SSL_STM32
  Licensed under MIT license
 *****************************************************************************************************************************/
#define REPLY_HEADER    "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n"

    void Process_Client_Request()
    {
        FsFile      file;
        char        line[500];
        char        Received_Character = '\0';
        uint32_t    Character_Index    =   0;
        uint32_t    n;
        uint32_t    File_Length_Bytes;
        uint32_t    File_Length_Lines;

        // listen for incoming clients
        EthernetClient client = server.available();

    //  static  ArduinoOutStream sout(client);
        static  ArduinoOutStream cout(Serial);

        if (client)
        {
            // an http request ends with a blank line
            bool currentLineIsBlank = true;

            while (client.connected())
            {
                if (client.available())
                {
                    char c = client.read();
                    Serial.write(c);
                    // if you've gotten to the end of the line (received a newline
                    // character) and the line is blank, the http request has ended,
                    // so you can send a reply
                    if (c == '\n' && currentLineIsBlank)
                    {
                        Serial.println(F("Sending response:\n"));

                        // send a standard http response header
                        // use \r\n instead of many println statements to speedup data send
                        client.print(REPLY_HEADER);
                        Serial.println(F(REPLY_HEADER));

                        // Open the SD card
                        if (!sd.begin(SD_CONFIG))
                        {
                            sd.initErrorHalt(&Serial);
                        }

                        // Specify the file to read
                        char fileName[] = "404.htm";

                        // Open the file to READ from the SD card
                        if (!file.open(fileName, O_READ))
                        {
                            sd.errorHalt(&Serial, F("open failed"));
                        }

                        File_Length_Bytes = file.fileSize();
                        File_Length_Lines = 0;

                        Serial.print(__DATE__); Serial.print(", "); Serial.println(__TIME__);

                        while ((n = file.fgets(line, sizeof(line))) > 0)
                        {
                            // Write the line to the client
                            client.print(line);

                            // Print the line
                            Serial.print(line);

                            File_Length_Lines++;
                        }
                        file.close();
                        break;
                    }

                    if (c == '\n')
                    {
                        // you're starting a new line
                        currentLineIsBlank = true;
                    }

                    else if (c != '\r')
                    {
                        // you've gotten a character on the current line
                        currentLineIsBlank = false;
                    }
                }
            }
            // give the web browser time to receive the data
            delay(10);

            // close the connection:
            client.stop();
            Serial.println(F("\n\nClient disconnected"));

            Serial.println("\n");
            Serial.print("Total bytes read: "); Serial.println(File_Length_Bytes);
            Serial.print("Total lines read: "); Serial.println(File_Length_Lines);
            Serial.println("");
        }
    }

Any ideas what I am doing wrong?
I tried removing all references to the SD card, and hard-coded a phrase to be sent out via the while() loop - this worked fine. Please see the code below:
#define REPLY_HEADER    "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n"

void Process_Client_Request()
{
    uint32_t    File_Length_Bytes;
    uint32_t    File_Length_Lines;
    uint16_t    c;
    uint32_t    LineCount = 0;

    // listen for incoming clients
    EthernetClient client = server.available();

      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      while (!Serial);

    if (client)
    {
        // an http request ends with a blank line
        bool currentLineIsBlank = true;

        while (client.connected())
        {
            if (client.available())
            {
                char c = client.read();
                Serial.write(c);
                // if you've gotten to the end of the line (received a newline
                // character) and the line is blank, the http request has ended,
                // so you can send a reply
                if (c == '\n' && currentLineIsBlank)
                {
                    Serial.println(F("Sending response:\n"));

                    // send a standard http response header
                    // use \r\n instead of many println statements to speedup data send
                    client.print(REPLY_HEADER);
                    Serial.println(F(REPLY_HEADER));

                    client.print("");
                    Serial.println("");

                    while (LineCount < 8000)
                    {
                        client.print("This is line number: "); client.print(++LineCount); client.print("
\r\n");
                        Serial.print("This is line number: "); Serial.print(LineCount); Serial.print("
\r\n");
                    }

                    client.print("");
                    Serial.println("");
                    break;
                }

                if (c == '\n')
                {
                    // you're starting a new line
                    currentLineIsBlank = true;
                }

                else if (c != '\r')
                {
                    // you've gotten a character on the current line
                    currentLineIsBlank = false;
                }
            }
        }
        // give the web browser time to receive the data
        delay(10);

        // close the connection:
        client.stop();
        Serial.println(F("\n\nClient disconnected"));

        Serial.println("\n");
    }
}

When reading a line of text from the SD card and printing it to the client, transmission to the client terminates after about 1279 characters, give or take. When this happens, the web browser continues to wait for more data.

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Encrypting the code using AES . ESP32
I am trying to figure it out. Why are my encryption and decryption not correct?
The used library for AES:
https://github.com/DanielVukelich/Arduino-AES
This is for testing encrypt and decrypt.
//https://www.hanewin.net/encrypt/aes/aes-test.htm
#include "Rij_Consts.h"
#include "Rijndael.h"

    void setup() {

      Serial.begin(115200);

      //mbedtls_aes_context aes;

      unsigned char iv[16] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};

      //char * key = "abcdefghijklmnop";
      //const unsigned char key[16];
      const unsigned char key[16] = {0xE8,0xE9,0xEA,0xEB,0xED,0xEE,0xEF,0xF0,0xF2,0xF3,0xF4,0xF5,0xF7,0xF8,0xF9,0xFA};
      //unsigned char key[16] = {0xFA,0xF9,0xF8,0xF7,0xF5,0xF4,0xF3,0xF2,0xF0,0xEF,0xEE,0xED,0xEB,0xEA,0xE9,0xE8};//กลับ

      //char *input = "Tech tutorials x";
     const unsigned char input[16] ={0x01,0x4B,0xAF,0x22,0x78,0xA6,0x9D,0x33,0x1D,0x51,0x80,0x10,0x36,0x43,0xE9,0x9A};
      //unsigned char input[16] ={0x9A,0xE9,0x43,0x36,0x10,0x80,0x51,0x1D,0x33,0x9D,0xA6,0x78,0x22,0xAF,0x4B,0x01};//กลับ

      unsigned char output[16]; //6743C3D1519AB4F2CD9A78AB09A511BD ต้องได้ตามนี้

      printf("Testing ECB mode:\n");

      printf("Original Plaintext:\n");
      for(int i = 0; i < 16; i++){
        printf("%2.2X ", input[i]);
      }

      unsigned char keys[176];//for 128

      Schedule_Keys(AES_128, key, 16, keys);
      printf("\n\nKEYs:\n");
      for(int i = 0; i < 16; i++){
        printf("%2.2X ", keys[i]);
      }

      Encrypt(AES_128, input, 16, keys, output);

      printf("\n\nCiphertext:\n");
     for(int i = 0; i < 16; i++){
        char str[16];
        sprintf(str, "%2.2X ", output[i]);
        Serial.print(str);
     }

    Decrypt(AES_128, input, 16, keys, output);
    printf("\n\nCiphertext:\n");
    for(int i = 0; i < 16; i++){
        char str[16];
        sprintf(str, "%2.2X ", output[i]);
        Serial.print(str);
    }
    }

    void loop() {}

My output :

You can see my encryption and decryption not correct.
I tried to reconstruct the full code.
#include "Rij_Consts.h"
#include "Rijndael.h"

//https://www.hanewin.net/encrypt/aes/aes-test.htm   สำหรับเทสเทียบ

void setup() {
   Serial.begin(115200);
    unsigned char iv[16] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
    const unsigned char key[16] = {0xE8,0xE9,0xEA,0xEB,0xED,0xEE,0xEF,0xF0,0xF2,0xF3,0xF4,0xF5,0xF7,0xF8,0xF9,0xFA};
    const unsigned char plainText[16] ={0x01,0x4B,0xAF,0x22,0x78,0xA6,0x9D,0x33,0x1D,0x51,0x80,0x10,0x36,0x43,0xE9,0x9A};
    unsigned char cipherText[16]; //6743C3D1519AB4F2CD9A78AB09A511BD Answer
    printf("Testing ECB mode:\n");

      printf("Original Plaintext:\n");
            for(int i = 0; i < 16; i++){
                  Serial.printf("%2.2X ", plainText[i]);
      }
        unsigned char keys[176];//for 128

        Schedule_Keys(AES_128, key, 16, keys);
            printf("\n\nKEYs:\n");
                for(int i = 0; i < 16; i++){
                    Serial.printf("%2.2X ", keys[i]);
      }

      Encrypt(AES_128, plainText, 16, keys,cipherText );
          Serial.printf("\n\nCiphertext:\n");
              for (int i = 0; i < 16; i++) {
                    Serial.printf("%2.2X ", cipherText[i]);
      }
      unsigned char decryptedText[16];

        Decrypt(AES_128,cipherText , 16, keys, decryptedText);

          Serial.printf("\n\ndecryptedText:\n");
              for (int i = 0; i < 16; i++) {
                    Serial.printf("%2.2X ", decryptedText[i]);
}
}

void loop() {}

Unfortunately I don’t have time to write a complete answer, but it looks like you’re attempting to  “decrypt” the (unencrypted) cleartext, not the ciphertext. The input of Decrypt should be the output of Encrypt.

Could you pls explain a little more about Encrypt and Decrypt? I'm kinda confused. But thanks for the comment

I want to Encrypt the code correctly first. but I don't know what to do. I keep missing and being wrong. My Encrypt is not correct that makes my Decrypt wrong too :<<<.

This is mainly a coding issue and not specific to Arduino. However, see my answer.

Could you pls send me the full code of ur answer to my Gmail? I want to compare to mine what did I do wrong. siripaiboon.J61@rsu.ac.th

With my answer you should be able to reconstruct the full code.

I'm outside, not back home yet. And appreciate you for helping me. You just came in the clutch.

I tried to reconstruct the code today. but My encrypt is still not correct at all. Do I really miss something in my new code. I did change as u said about Input, Output. My new code in the post.

Your reconstructed code as posted in your question runs exactly like it should on an ESP32 and also on an ESP8266. You seem to have renamed "Rijndael_Consts.h" to "Rij_Consts.h" so I had to fix that, but that could not have caused your issue. The output in my case was a correct Ciphertext and Decrypted text. How did you install the library?

Hmm, Interesting. I did not install it by myself. I got this library as WIN.RAR from my friend. I'll try to install it again. I'll let you know. After I install the new library.

I have a question. Why do my Encryption/Decryption not match the website we use to compare ? Even I use the same AES128-ECB :< https://www.hanewin.net/encrypt/aes/aes-test.htm

I don't know. You might try re-downloading and re-installing the library from Github.

Finally, I can encrypt the code correctly. Thanks for the advice. I tried re-installing from the library. It actually worked.

I tried to download the library from Github, but there is a file missing. Could you please provide another link?

@YathribElsiddig There are Rjindael.c, Rjindael.h, Rjindael_Consts. there is no file missing in the library. but you have to read  "README"  carefully first before you use his library with your project and I'm afraid that I don't have that link.  It was like 2 years ago

Maybe you try to redownload it like me. I had problem with download library before. you can see my post up there.

There are some issues with your code.
As mentioned in my comment, Decrypt () expects the Cipher Text as input and generates the Decrypted text as an output. However, in your code you're using the Plain text (which you confusingly named "input") as an input. The correct input should be your Cipher Text (which is the output from the Encrypt () function and which you called "output"). Please read the documentation of the AES library.
I suggest the following changes to your code to get it working:
Replace the part of your code, following Decrypt (...) until the end of setup() with the following code:
unsigned char decryptedText[16];
Decrypt(AES_128, output, 16, keys, decryptedText);

Serial.printf("\n\ndecryptedText:\n");
for (int i = 0; i < 16; i++) {
    Serial.printf("%2.2X ", decryptedText[i]);
}

I would also suggest you name your variables to avoid confusion, for example you could replace input[] with plainText[] and output[] with cipherText[]. Some of your Hex output code is also unnecessarily complex and could do with some restructuring.
I've compiled and run the above changes with your code on an ESP32 and it produces the expected Cipher text and correctly decrypts it. It produces the following output:
00:21:01.583 -> Testing ECB mode:
00:21:01.583 -> Original Plaintext:
00:21:01.630 -> 01 4B AF 22 78 A6 9D 33 1D 51 80 10 36 43 E9 9A
00:21:01.630 ->
00:21:01.630 -> KEYs:
00:21:01.630 -> E8 E9 EA EB ED EE EF F0 F2 F3 F4 F5 F7 F8 F9 FA
00:21:01.630 ->
00:21:01.630 -> Ciphertext:
00:21:01.630 -> 67 43 C3 D1 51 9A B4 F2 CD 9A 78 AB 09 A5 11 BD
00:21:01.630 ->
00:21:01.630 -> decryptedText:
00:21:01.630 -> 01 4B AF 22 78 A6 9D 33 1D 51 80 10 36 43 E9 9A

In your question you mention that the generated Cipher text is not as expected. I can't help you with that, as I can't reproduce it.


text:
Why am I getting Invalid head of packet (0xF0) error when trying to upload code to esp8266?
Solved : In Mac I went back to Tools --> Boards Manager, then removed 3.0 and downgraded to 2.5 and it started working. I found the solution in this thread.

The current connection between uno R3 and esp8266 is
UNO ----- ESP8266
RX — RX
TX — TX
GND — GND
3.3V — VCC (used bread board)
3.3V — CH_PD (used bread board)
GPIO - GND

UNO ----- UNO
Reset -- GND

Then ESP8266 send "OK" when I send AT from the serial monitor. When uploading the red light and blue blinks in esp8266 and rx and tx light blinks at uno r3.
I had to do sudo launchctl stop /dev/cu.usbmodemxxx before running below command.
Since I have GPIO connected to GND, I though that would trigger the programming mode, but for some reason it gives Invalid head of packet. I get same error when trying to upload code from arduino IDE.
I tried below command too from cmd line.
$sudo python esptool.py -t --chip esp8266  --port /dev/cu.usbmodemxxx --before no_reset flash_id
esptool.py v2.8
Serial port /dev/cu.usbmodemxxx
Connecting...TRACE +0.000 command op=0x08 data len=36 wait_response=1 timeout=0.100 data=
    0707122055555555 5555555555555555 | ... UUUUUUUUUUUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    55555555                          | UUUU
TRACE +0.000 Write 46 bytes:
    c000082400000000 0007071220555555 | ...$........ UUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    5555555555555555 5555555555c0     | UUUUUUUUUUUUU.
TRACE +0.000 Read 3 bytes: f8fef0
TRACE +0.000 Read invalid data: f8fef0
TRACE +0.000 Remaining data in serial buffer:
.TRACE +0.056 command op=0x08 data len=36 wait_response=1 timeout=0.100 data=
    0707122055555555 5555555555555555 | ... UUUUUUUUUUUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    55555555                          | UUUU
TRACE +0.000 Write 46 bytes:
    c000082400000000 0007071220555555 | ...$........ UUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    5555555555555555 5555555555c0     | UUUUUUUUUUUUU.
TRACE +0.001 Read 1 bytes: f0
TRACE +0.000 Read invalid data: f0
TRACE +0.000 Remaining data in serial buffer: f0f0
.TRACE +0.056 command op=0x08 data len=36 wait_response=1 timeout=0.100 data=
    0707122055555555 5555555555555555 | ... UUUUUUUUUUUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    55555555                          | UUUU
TRACE +0.000 Write 46 bytes:
    c000082400000000 0007071220555555 | ...$........ UUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU

......

A fatal error occurred: Failed to connect to ESP8266: Invalid head of packet (0xF0)

Below is the image of the arduino IDE with code and board selected as esp8266.

I am following this post https://iot-guider.com/esp8266-nodemcu/how-to-program-esp8266-with-arduino-uno/ and I have exact same hardwares.
UPDATE:
When I tried this connection in Windows it starts uploading code without error. So, my guess is its something to do with MAC.

This reads as if you're omitting some info... what is the role of the UNO? Are you using it to flash the ESP? Also, which GPIO are you pulling to GND? The ESP has many of these. Flashing an ESP also requires pulling three GPIOs up or down. Finally I note that you connect RX to RX and TX to TX -- normally, you need to connect TX (transmit) to RX (receive) on a serial connection.

@orithena I was following this post https://iot-guider.com/esp8266-nodemcu/how-to-program-esp8266-with-arduino-uno/ I have the exact same hardware.

From that article: "Also, connect the RX and TX lines of both." -- this means to connect TX on UNO to RX on ESP and RX on UNO to TX on ESP. I'm repeating that because your question lists those connections wrong. I'm also a bit concerned that those instructions show to connect the 5V TX/RX of the UNO to the 3.3V TX/RX of the ESP...

"Also, connect the RX and TX lines of both." this line does not necessarily say, I say this because the image connects RX of esp8266 to RX of uno and TX esp8266 to TX of uno.  By the way I did tried connect RX-TX and TX-RX get the same error. I also tried connecting with 5 V and I get same error.

The Atmega328 is being held in reset - essentially dormant. This technique borrows the Uno's auxilliary 16U2 chip, the USB <-> TTL converter to program the ESP. The Rx & Tx connections are correct as viewed as between the PC and the ESP, and the '328 plays no part in the communication, in this case. I share your concern about driving the 3.3v ESPs receive pin with a 5v transmitter, however.

I have tried both 3.3v and 5v and again tried 3.3v in a new esp8266 always get same error.

select Port in Tools menu

@Juraj updated the image. The image I had earlier was taken when not connected (I just wanted to show my configuration).

No matter what a tutorial on the internet says, connecting Rx to Rx and Tx to Tx is definitely not correct andin the worst case it can even harm your hardware. you have to connect the transmitting pin of A to the receiveing pin B and vice versa. If it still doesn't work, the error is somewhere else.

@SimSon When the flip the RX and TX connection I get time out error.

The tutorial you linked to can not be trusted! There are mayor mistakes:

They connect a 3.3V device with a 5V devices without taking any measures to convert the logic levels.
Connecting Rx to Rx (or Tx to Tx) is typically not what you do if you want to communicate between devices. A transmitting line must be connected to a receiving line for that. In case the arduino is Serial.print()ing something himself, a bus contention can cause a short circuit and harm the UART pins.
They are plugging the ESP into a breadboard which simply doesn't work! This will short several pins and possibly kill some hardware. At least it can't work like that.

I don't know if the person who did this tutorial just has no idea or is trolling, but you need to find a different tutorial (and - I'm sorry to say - possibly get a new ESP).
If all you want is to use the arduino as a USB to UART bridge, I suggest to remove the atmega chip from its socket on the arduino or make sure that it doesn't run a sketch were it prints something. The UART pins should also be configured as inputs.

Every other tutorial in internet is using ESP with bread board though.

The 5 holes (A,B,C,D,E) of a row are connected together on those breadboards. Can you show me another example where an ESP01 is put onto a breadboard? Maybe they use one of the ESP-based modules, like the nodeMCUs, which can be used on a breadboard. Pin headers with two rows are generally not very suitable for breadboards...

This is another one https://youtu.be/ZJnpgYlelEA?list=LL . Also I was able solve the issue, in my Mac I went back to Tools --> Boards Manager, then removed 3.0 (I had 3.0 version) and downgraded to 2.5 and it started working (meaning started uploading the code and the code in esp8266 was executed as expected). Yes, this is still using ESP01 on bread board. I have edited and mention this in top my question.

@solti in that video, the person uses jumper wires to connect the esp to the breadboard. What I wrote still applies...

you point 2 is not valid. the goal is to use the USB of the Uno, not to connect to ATmega.

@Juraj I see, I will edit my answer. But is it actually okay to do so? What if the ATmega is running code and printing something? In my opinion this should not be done unless there are current limitung line drivers involved... ehich are not on the arduino.

the ATmega should have a sketch without Serial.begin (BareMinimum, Blink) or reset wired to ground


text:
Detect button press in a loop
I am designing simple "Simon Says game" using Arduino. Simon says is a game in which a LED pattern is played and user has to mimic the pattern. There are 10 Rounds. First Round = 1 led, second round = 2 leds and so on. When the first round is played, one led blinks and player has to press the corresponding button. Then if it presses the right button, next round plays in which two LEDs glow and player has to press 2 buttons in sequence. I am having problem in detecting the button press in a loop for more than 1 round. Here is snippet of the code:
void loop() {
  for (int i = 1; i <= ROUNDS; i++)
  {
    digitalWriteGeneric(i);
    bool wait = 1;
    int expected = Sequence[i - 1];
    while (wait)
    {
      int value = digitalReadGeneric();
      if (expected == value)
      {
        Serial.print("Right");
        wait = 0;
        break;
      }
    }
  }
}
int digitalReadGeneric()
{
  for (int i = 0; i < NUM_LIGHTS; i++)
  {
    Readings[i] = digitalRead(buttonPin[i]);
    if (Readings[i] == 1)
    {
      return i;
    }
  }

}

Here, ROUNDS = 10
digitalwritegeneric is working fine, it plays the pattern for corresponding pattern. For round more than one how can i detect button press in sequence?. Kindly tell, what I am doing wrong.

This is a question more suited for stackoverflow actually.

Looking into your for-loop:
for (int i = 1; i <= ROUNDS; i++)
  {

    // Write sequence
    digitalWriteGeneric(i);

    // Read sequence
    bool wait = 1;
    int expected = Sequence[i - 1];
    while (wait)
      {
        int value = digitalReadGeneric();
        if (expected == value)
          {
            Serial.print("Right");
            wait = 0;
            break;

            // Setting vlag to false will exit the while loop
            // break will also exit the while loop
            // so only need to do 1 of the 2
            // but then you won't be able to read anymore, it exited the while-loop
          }
      }
  }

You only check the first button, and if this one is correct you go out of the while loop, ending the reading.
You can change the type of variable wait to an uint8_t (init to 0) and if the value is right, increment wait. The while-loop becomes: while (wait < i) {}. You can use break to stop reading when the player clicked a wrong button.
To see if the player did the sequence correctly:
if (wait == i) {"GOOD";} else {"BAD";}


text:
Adafruit Featherwing Latching Relay lamp switch
I am brand new to Arduino. So I apologize in advance if I have missed the information I am looking for. I have looked for hours and cannot find any help with a Adafruit Featherwing Latching Relay(#2923 on Adafruit). This is the one that has 2 set pins "Set" & "Unset". I would love to use a Wemos d1 mini to trigger this relay. But I cannot find any sketchs or documentation on how to get started.
Ideally the setup would have a push button to toggle between states as well as the basic esp8266 web page to toggle state as well.
I am just trying to turn off/on some LEDs. And want to run the switch via this setup.
Thanks
E
Well I am further along. I was able to get most of this working but now the CSS i am using is causing headaches. The code below errors on "page =
Simple NodeMCU Web Server

    <button class="button">ON</button>         <button>OFF</button>
";
I get the error 'inconsistent user-defined literal suffixes 'LEDOn' and 'button' in string literal'
Any help would most appreciated. This line is the only one failing in my sketch

Please ask a new question for a new question rather than globbing it onto an existing one, particularly when it regards a completely separate topic. If you're having code issues including the code would be... helpful.

I will add the final code here. It took me weeks to find a starting place and many hours of trial and error to sort it all out. With help I was able to get a stable working switch.
This code was written for a Wemos D1 Mini coupled to a Adafruit Featherwing Latching relay. Since it has Set and Unset pins coding this was struggle for me. The Set/Unset pins only require a pulse to trigger them then they stay 'Latched' in state. even if power is lost. I found the base code here and it took a bit of tweaking to get it to work.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

// Replace with your network credentials
const char* ssid = "SSID";
const char* password = "PASSWORD";

ESP8266WebServer server(80);   //instantiate server at port 80 (http port)

String page = "";
int LEDUnsetPin = D1;
int LEDSetPin = D2;
void setup(void){
 //the HTML of the web page
 //don’t forget you need estapes (") around the quotes
 page = "
Kitchen LEDs

    <button class=\"button\">ON</button>         <button>OFF</button>
";
 //make the LED pins output and initially turned off
 pinMode(LEDUnsetPin, OUTPUT);
 digitalWrite(LEDUnsetPin, LOW);
 pinMode(LEDSetPin, OUTPUT);
 digitalWrite(LEDSetPin, LOW);

 delay(1000);
 Serial.begin(115200);
 WiFi.begin(ssid, password); //begin WiFi connection
 Serial.println("");

 // Wait for connection
 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
 }
 Serial.println("");
 Serial.print("Connected to ");
 Serial.println(ssid);
 Serial.print("IP address: ");
 Serial.println(WiFi.localIP());

 server.on("/", [](){
   server.send(200, "text/html", page);
 });

 //turn on the on pin and turn off the off pin
 server.on("/LEDOn", [](){
   server.send(200, "text/html", page);
   digitalWrite(LEDSetPin, HIGH);
   delay(10);
   digitalWrite(LEDSetPin, LOW);
   delay(10);
 });

 //turn off the on pin and turn on the off pin
 server.on("/LEDOff", [](){
   server.send(200, "text/html", page);
   digitalWrite(LEDUnsetPin, HIGH);
   delay(10);
   digitalWrite(LEDUnsetPin, LOW);
   delay(10);
 });
 server.begin();
 Serial.println("Web server started!");
}

void loop(void){
 server.handleClient();
}

That board is specifically designed for the Feather ecosystem, so you'd need to provide the relevant connections, looks like 3.3V and GND, and the two input signals (also 3.3V, I assume). Nutshell: you can ignore almost every single connector on the board except for 3.3V, GND, SET, and UNSET.
Any D1 (or Arduino in general) tutorial that discusses how to set an output pin value is fine--you'd need them to be LOW by default and bring the relevant one HIGH for 10ms (delay is fine here) to set the new state.
Any switch input tutorial should be fine for learning how to read a switch, and there are multiple tutorials regarding setting up a simple web app that interacts with 8266 IO. Note that you'll want to keep track of the current state, though, and probably update the web app with the current state if it's changed via the button.
All this said: "just trying to turn off/on some LEDs" is broad. A relay may not be necessary; is there an explicit need for a latching relay?

Dave - This pretty much what I am after. There is no explicit need really just a learning exercise. Really finding an answer to a question no one asked ;o) - If anyone wants to provide code.... that would be awesome but I'm not greedy and can dig it up myself. Thanks


text:
Send/Stream BLE (Bluetooth Low Energy) data with high data rate with Arduino
My project is to transfer an image wirelessly via BLE from my Sparkfun EDGE board using the Arduino IDE to another laptop. In the following, for simplicity, I have reduced the program to transmit integers via BLE. This already works but it takes a long time (~0.5 seconds) to transfer a few bytes. However, from the BLE specifications, much more should be possible.
This is the stripped down code for the Board using Arduino:

#include <ArduinoBLE.h>
#include "utility/HCI.h"    // needed for sendcommand
#include <string>

const char BLE_PERIPHERAL_NAME[] = "Peripheral Hello World BLE";
BLEService Test("83436682-10c6-4dad-acb1-133927f3f080");
BLEStringCharacteristic HelloWorlds("83436682-10c6-4dad-acb1-133927f3f080", BLERead | BLENotify, 512);

#define SERIAL_PORT Serial
#define BAUD_RATE   115200 //(originally, 460800)

void setup() {

  // Start up serial monitor
  SERIAL_PORT.begin(BAUD_RATE);

#ifdef BLE_Debug
  BLE.debug(SERIAL_PORT);         // enable display HCI commands
#endif
  BLE.setLocalName(BLE_PERIPHERAL_NAME);
  BLE.begin();

  BLE.setAdvertisedService(Test);

  Test.addCharacteristic(HelloWorlds);

  BLE.addService(Test);
  BLE.advertise();
//BLE part end
  }

void loop(){
    int period=3000; //minimum time [ms] to be spent in each loop. This is to give the BLE enought time to transmit. To be adjusted depending on the test.
    unsigned long timing=millis();

    BLE.poll();

    int v1;
    v1 = rand() % 100;

    //Generate 8 integer to be transmitted
    String sixteen=String(v1);
    for (uint32_t ccc=0; ccc < 8; ccc=ccc+1){

      v1 = rand() % 100;
      sixteen = sixteen + " " +String(v1);
    }
  HelloWorlds.writeValue(sixteen);
  SERIAL_PORT.print(sixteen);
  SERIAL_PORT.print("   ");

   while(millis() < timing + period){
   }

  }

The code compiles, runs on the EDGE board and I receive the random bytes on my phone (NRF app) as well as on the other laptop.
On the other laptop, I use gatttool in the Ubuntu terminal to receive the packets:
gatttool -I
connect C0:4B:39:C9:B1:04
char-read-hnd c

(I obtain the handle "c" through inspecting the characteristics before).
Then, I do receive the String, but it takes the some hundreds of milliseconds until the integers are displayed. I also automated this in a Python script using pexpect and then print the timestamps after the sendline and expect command and it shows the time difference of ~hundreds of milliseconds.
The data rate that I target should be at least hundreds of bytes per second.
Thank you kind community.

Why you are using a deprecated tool for this? Do it with Bleak then update the question with the time you record via your script please.


text:
How to multiplex multiple displays?
I want to use 2 "displays" with 4 digits. The displays are common cathodes with cathode transistors connected to the digits, as the figure:

The segments of both displays are connected together on the digital pins.
The problem is that I tried to use some libraries for 7 segment displays and they worked with only one 4 digit display, but when I connected the second display, did not display the numbers correctly. The numbers that will be written are integers and I'm using mega 2560 R3.
Here are my attempts:
#include "SevSeg.h"
byte digitPins_1[] = {29, 30, 31, 33};//Digits pins
byte digitPins_2[] = {25, 26, 27, 28};
byte segmentPins[] = {38, 39, 40, 41, 42, 43, 44, 46}; //segment pins
SevSeg disp1;
SevSeg disp2;

void setup() {
disp1.begin(P_TRANSISTORS, 4, digitPins_1, segmentPins);
disp2.begin(P_TRANSISTORS, 4, digitPins_2, segmentPins);
disp1.setBrightness(20);
disp2.setBrightness(20);
}

void loop() {
disp1.setNumber(8888, 0);
disp1.refreshDisplay();
disp2.setNumber(1111, 0);
disp2.refreshDisplay();
}

or using another lib:
#include <SevenSeg.h>
SevenSeg disp1(38,39,40,41,42,43,44);//segment pins
SevenSeg disp2(38,39,40,41,42,43,44);
int digitPins1[4]={29,30,31,33};//digitpins
int digitPins2[4]={25,26,27,28};

void setup() {
disp1.setDigitPins(4,digitPins1);
disp2.setDigitPins(4,digitPins2);
disp1.setDigitDelay(1600);//time delay
disp2.setDigitDelay(1600);
disp2.setActivePinState(HIGH,HIGH);//seg active HIGH, digit active HIGH
disp1.setActivePinState(HIGH,HIGH);
}

void loop() {
disp1.write(8888);
disp1.clearDisp();
disp2.write(1111);
disp2.clearDisp();
}

Check the library code for what would happen if you use the same segments pins. Also add a short delay between write-clearDisp.

How are your segment lines driven?  If driven directly by ATmega pins instead of through a transistor, 8 segments at about 8 mA each is way too much; 4 at 8 mA might have worked ok, without 8 such working

Why are you making two instances of the class when one instance  "Supports arbitrary number of digits and multiple displays"? See: Arduino
SevenSeg v1.2

Because on every 4-digit display I would like to write a different variable at different times in my program.
The segment lines are connected directly to the Arduino, only with a 220 ohm resistor, I'm going to change that.

The code instantiates two instances of the SevSeg class.  This may or may not work.  Really depends on if the class uses any resources are not meant to be shared between multiple instances of that class.  For instance, it is unlikely that one hardware timer can be used for more than one purpose at a time.
But the code continues on to use the same (anode) pin resources for both instances of the class. This is likely not going to work.
Apologies for being vague using qualifier like "unlikely" instead of simply stating that it will not work.  Truth is, one might be able to write a class that can deal with multiple instances of its self.  But it would be very difficult and a far more complex programming task than to simply use one instance for all 8 digits.
In case there is a question as to the maximum number of digits supported for one instance of the SevSeg class, this line is in the one of the SevSeg header files:
#define MAXNUMDIGITS 8 // Can be increased, but the max number is 2^31

As the answers suggested, it is better to make a single display with 8 digits. But if anyone needs 2, here is my solution:
As suggested, I checked if the library supported, and the solution was to only increase the delay on each digit.
#include <SevenSeg.h>
SevenSeg disp1(38,39,40,41,42,43,44);//segment pins
SevenSeg disp2(38,39,40,41,42,43,44);
int digitPins1[4]={29,30,31,33};//digitpins
int digitPins2[4]={25,26,27,28};

void setup() {
disp1.setDigitPins(4,digitPins1);
disp2.setDigitPins(4,digitPins2);
disp1.setDigitDelay(4000);//time delay
disp2.setDigitDelay(4000);
disp1.setDutyCycle(10);//decrease the duty cycle
disp2.setDutyCycle(10);
disp2.setActivePinState(HIGH,HIGH);//seg active HIGH, digit active HIGH
disp1.setActivePinState(HIGH,HIGH);
}

void loop() {
disp1.write(8888);
disp1.clearDisp();
delay(1);// don't need
disp2.write(1111);
disp2.clearDisp();
}

Why do you feel you need to multiplex two displays? What is wrong with just having one display of 8 digits? They don't have to be physically together, and it's entirely up to you what you display on each character of the display.

I think it would not make any difference for me to use an 8-digit display, initially it just seemed easier to use 2 different ones.

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


text:
Micromod nrf52840 sniffer
Can I use the Micromod nrf52840 processor module, Micromod ATP carrier, with Nano 33 type bootloader and modify the ArduinoBLE library or modify the MBED OS abstraction layer and make a promiscuous BLE sniffer that will output something, preferably a Wireshark compatible capture file to the main serial COM port and save the output from arduino IDE?

maybe you can, maybe you cannot, we do not know what skill you have