text:
How to send and receive multiple integer values through serial comm for Arduino Micro and HC05 bluetooth?
I need to send gyroscope values and a voice command flag and counter with a start and end marker through serial in the format <2,4,5,6> through Arduino Software serial using the HC05 Bluetooth module between Arduino Micro boards. I can send values in the struct format. But it seems that the order of the struct gets changed after a few seconds of receiving on the other side. How can I send these values in the mentioned format? I am new to this. Please help me out. It would also help if I could get suggestions on how to receive and parse this data of this format in the correct order/way.

why do you use SoftwareSerial? Micro has Serial1 for RX/TX pin

@Juraj , I need to monitor the values since the transmission is so fast and needs the least latency possible. Besides, I could never get my bluetooth modules to work on hardware serial. Please provide me with a demo code or some link. Are there two hardware serial on Arduino Micro? I'm not sure. Please enlighten me.

there is USB named Serial and UART named Serial1. pins RX/TX are Serial1

@Juraj , I have been trying wireless communication using Serial but not Serial1. Is that the reason I am unable to send? Also, the question still remains how I can send, receive and parse the data to be sent in the format <2,3,4,5>

where are you sending the serial data?

@jsotola , arduino micro to arduino micro. Sending the values of gyroscope sensor and voice command flag. I wanna move the mouse cursor using that data.

Try Google Protobuf it's really awsome. I use it every time when I connect C# app to STM but it can be used in this case as well. U use Protobuf to encode your message and COBS do remove zeros from message so you can slap it on the end to know when the packet ends

Google Protobuf does work on AVR Arduino?


text:
How to extract the binary from STM32 MCU
I have an already programmed STM32MCU. But I don't have the source code. I understand it is difficult to get the source code from the IC. I have heard some people can get the binary file from the IC which I can flash to another Arduino. Any guide or material will be helpful. I tried my luck with google. but didn't find any good resources on this matter.

you can probably get the hex file from the mcu you are using, and use a decompiler to get the functions. Tirdad is right, that the code likely wont work on different architectures directly, but once you have the hex file you can start porting functions.

you can download the flash content using a ST-Link probe and STM32CubeProg tool. you can't flash it to just "any" arduino board; it must be the exact same chip or same family MCU, if the IOs and peripherals used are the same.

There's also the command-line tool, STM32_Programmer_CLI, which can be used. I describe installing it here: https://arduino.stackexchange.com/a/77432/7727. Check the help menu, UM2237, or help menu at the command-line (STM32_Programmer_CLI -h), for more command info on which commands to use.

source: Stack Exchange

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

sort: votes


text:
Issue with different ways of powering
I have a project to make where I have to read tags out of 5 RFID Readers and when every tag is in correct reader to open a relay. The schematic is the same with Annaane's with the difference I have 5 Readers, so I didn't make one.
I also have made the board that i have attached so I can connect all the common pins together (MISO, MOSI, SCK, RESET, 3.3V and GND)
The SDA SS pins are connected directly to pins 3-7 of Arduino.
My code works just fine when powering arduino through my Laptop's USB port but since it have to be installed somewhere I tried the following ways to power it:

USB coming from a Xiaomi 5v Phone Charger to Arduino's USB port
USB coming from this to Arduino's USB Port. It is being powered from a 12v 1amp power supply from and old router.
The 12v 1amp power supply from and old router.
L7805CV and it's suggested circuit from the datasheet

My problem is that none of these ways seem to work properly. What I mean is that I cant get readings from the Readers as it should do. I have an LED which lights up when it read a tag but at these cases it only lights up only on some of the readers. The strange part is that when I am charging my laptop and powering arduino through its usb port it doesnt work either.
Any help please?

On your board I see much of what seems to be flux residuals from soldering. Maybe you should clean that up. Depending on the flux, you might get unwanted connections there. I personally use the lighter fluid of my zippo.

This flux is there because I used to have a 5V regulator (L7805CV) but I desoldered it because id didnt seem to work properly. I dont think that this is the issue.

I am suspecting noise. Can you test once with a Power bank if you have access?

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


text:
Possible noise from the motors
I'm trying to control a self-balancing car, but it seems that the MPU6050 get dirty once my motors operate a full velocity.
I'm controlling my motors with the module L298N and with the PWM signal (pin 5, 6, 9 and 10 from the arduino).
I have read about decoupling it, with capacitors, but I don't know exactly how should I do it.
This is my code. It's a little messy (sorry for that, it just I'm still figuring out what is going on) and also an image of my project:
#include <PID_v1.h>
#include <LMotorController.h>
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

#define MIN_ABS_SPEED 20

MPU6050 mpu;

#define DEBUG
//#define OFFSET_1

//#define STOP

// MPU control/status vars
bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q; // [w, x, y, z] quaternion container
VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi]    Euler angle container

//PID
//double originalSetpoint = 175.8;
#ifdef OFFSET_1
      double originalSetpoint = 225;
#else
      double originalSetpoint = 184;
#endif

double setpoint = originalSetpoint;
double movingAngleOffset = 0.1;
double input, output, output_left, output_right, error;
int moveState=0; //0 = balance; 1 = back; 2 = forth
double Kp = 40;
double Kd = 0.05;
double Ki = 5;
PID pid(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT);

double motorSpeedFactorLeft = 1;
double motorSpeedFactorRight = 1;
double motorSpeedFactorForward = 1;
double motorSpeedFactorBackward = 1;

//MOTOR CONTROLLER
int ENA = 5;
int IN1 = 6;
int IN2 = 7;
int IN3 = 8;
int IN4 = 9;
int ENB = 10;
//LMotorController motorController(ENA, IN1, IN2, ENB, IN3, IN4, motorSpeedFactorLeft, motorSpeedFactorRight);

//timers
long time1Hz = 0;
long time5Hz = 0;

volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady()
{
  mpuInterrupt = true;
}

void setup()
{

  // join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000);  // Set the SCL clock speed to 400kHz
  //Wire.setClock(200000);  // Set the SCL clock speed to 400kHz
  //TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
  //Fastwire::setup(200, true);
#endif

  Serial.begin(115200);
  mpu.initialize();

  devStatus = mpu.dmpInitialize();

  // supply your own gyro offsets here, scaled for min sensitivity

  #ifdef OFFSET_1
      mpu.setXGyroOffset(0);
      mpu.setYGyroOffset(0);
      mpu.setZGyroOffset(0);
      mpu.setZAccelOffset(16372);
      mpu.setYAccelOffset(5);
      mpu.setXAccelOffset(2);
    #else
      mpu.setXGyroOffset(-52);
      mpu.setYGyroOffset(-12);
      mpu.setZGyroOffset(53);
      mpu.setZAccelOffset(2420);
      mpu.setYAccelOffset(2881);
      mpu.setXAccelOffset(-784);
    #endif

  // make sure it worked (returns 0 if so)
  if (devStatus == 0)
  {

    //mpu.CalibrateAccel(6);
    //mpu.CalibrateGyro(6);
    // turn on the DMP, now that it's ready
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    attachInterrupt(0, dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    dmpReady = true;

    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();

    pid.SetMode(AUTOMATIC);
    pid.SetSampleTime(10);
    pid.SetOutputLimits(-255, 255);
  }
  else
  {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }

  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);

  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);

  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

}
void loop()
{
  #ifdef STOP
      return;
  #endif

  // if programming failed, don't try to do anything
  if (!dmpReady) return;

  // wait for MPU interrupt or extra packet(s) available
  while (!mpuInterrupt && fifoCount < packetSize)
  {
    pid.Compute();

    output = 255;
    output_left = output * motorSpeedFactorLeft;
    output_right = output * motorSpeedFactorRight;
    if(input > (setpoint))
    {
      output_left = output_left*motorSpeedFactorForward ;
      output_right = output_right* motorSpeedFactorForward;

      Move_Forward();
    }
    else if(input < (setpoint))
    {
      output_left = output_left*motorSpeedFactorBackward ;
      output_right = output_right* motorSpeedFactorBackward;
      Move_Backward();
    }
    else
    {
      Stop();
    }
  }
  // reset interrupt flag and get INT_STATUS byte
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();

  // get current FIFO count
  fifoCount = mpu.getFIFOCount();

  // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus & 0x10) || fifoCount == 1024)
  {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
  }
  else if (mpuIntStatus & 0x02)
  {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);

    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;

    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(euler, &q, &gravity);
    input = (euler[1] * 180 / M_PI + 180);
    error = input - setpoint;
//    Serial.print("\tOutput: ");
//    Serial.print(output);
    Serial.print("\tError: ");
    Serial.println(error);

  }
}

void Move_Forward() //Code to rotate the wheel forward
{

  //******RIGHT******//
      analogWrite(5, -1*output_right);
      analogWrite(6, 0);

  //******LEFT******//
      analogWrite(9, -1*output_left);
      analogWrite(10, 0);

      digitalWrite(11, HIGH);
      digitalWrite(12, LOW);
}

void Move_Backward() //Code to rotate the wheel forward
{
  //******RIGHT******//
      analogWrite(5, LOW);
      analogWrite(6, 1*output_right);

  //******LEFT******//
      analogWrite(9, 0);
      analogWrite(10, 1*output_left);

      digitalWrite(11, LOW);
      digitalWrite(12, HIGH);
}

void Stop() //Code to rotate the wheel forward
{
      analogWrite(11, LOW);
      analogWrite(12, LOW);
      analogWrite(5, LOW);
      analogWrite(6, LOW);

      digitalWrite(9, LOW);
      digitalWrite(10, LOW);
}

Keep reading about decoupling.  Learn what a capacitor does.  You’re on the right track you just need to keep looking at that.

this is the typical arrangement.

@Majenko: Are the cap leads insulated? If not, it intended that the motor case may be shorted to power leads?

No, the leads are not insulated. Two of the capacitors are soldered to the motor case. That's part of the arrangement.

Where'd you get the kit? Can you post a link? Looks pretty cool. Would be a fun project.

@Seamus The part of the motor case where the (blue) bodies of the capacitors are is plastic. A capacitor is not a short-circuit for DC: the solder joints (on the right in the photo) to the case are intentional.

Well, I have to said that at the beginning I didn't think that the arrangement that @Majenko mentioned will work.
First I tried connecting the capacitor with cables, but it still give me noise. Once I soldered it directly to the motors the noise decrease a lot.
Thanks to all. This is the image of the arrangement that I made:


text:
Run function concurrent to server.available()
I have a Arduino UNO WiFi Rev2 board that runs WiFiServer serving as a web server. The server listens and accepts clients using server.available(). I also want a loop that controls a servo in concurrent of the server.
I looked at ArduinoThread and tried to implement my web server with it.
class WebServer : public Thread
{
private:
    // Some method definition omitted
    WiFiServer server;
    void accept_and_process();

public:
    void run() override;
}

void WebServer::accept_and_process()
{
    Serial.println("Waiting for client");
    // listen for incoming clients
    WiFiClient client = server.available();
    // Process client
}

void WebServer::run()
{
    this->accept_and_process();
    this->runned();
}

But the code does not run in parallel with code in void loop() it only ran code inside loop function and does not accept client as expected
This is the code I ran the server with
void setup()
{
    Serial.begin(9600);
    WebServer webserver = WebServer();;

    webserver.setInterval(100);
    webserver.run();
}

void loop()
{
    Serial.println("Hello");
    delay(1000);
}

How would I run the server concurrent to another function.

There is no “parallel” on a single core arduino.  All you need to do is program both things in a non blocking fashion.  Don’t use delay or while loops waiting on things and you can do both things so fast it seems like they are parallel.  There are tons of tutorials on non blocking code.  Or post some actual compilable code here and maybe someone can help you see how.

@Delta_G thanks for the suggestion, I moved server.available() into void loop() to unblock the execution. I'm still experimenting with it but now everything should work as expected.

I never expected server.available() to be non-blocking because I assume it's basically socket.accept() in other languages which for most of the time, is blocking.

No.  server.available doesn’t wait for anything.  It just immediately returns whether or not there is a connection available.  If there’s not then it returns false and moves on.  Don’t assume.  There’s a great adage about what happens when you assume things.  Look it up if you don’t know it.

@Delta_G hey do you mind posting your comments as answer so I can accept it?

There is no “parallel” on a single core arduino. All you need to do is program both things in a non blocking fashion. Don’t use delay or while loops waiting on things and you can do both things so fast it seems like they are parallel. Put a call to server.available() in loop and then if it returns an invalid client object then the rest of the loop runs.  If it returns a valid client object then you can quickly do what you need with the server and then get back to everything else.
As noted in the comments, server.available is not blocking.  It doesn't wait for anything to come, it simply returns whether there is a connection available or not.


text:
Can you power the ESP8266E-12 with any of the 3.3V pins?
If I want to operate the NodeMCU on the 3.3V input with 2.5V to 3.6V; can I use any of the 3.3V pins to do so?

The 3.3V pins have this name for a reason. You need to provide 3.3V. 2.5V is a bit too low

On the nodeMCU board all the 3.3v pins have continuity. That means they all do the same thing. And yes, you can apply ~3.3v to them. I have trouble with voltages under ~2.8 though, 2.5v is likely not going to work.
Use a buck+boost to keep it 3.3v if needed. For cheap dc/dc converters, I strongly prefer ones with XL semi chips; clean enough to please the ESPs.


text:
Nextion Display won't show data
I'm prototyping my Weather Station on Wemos D1 mini pro (ESP8266) with BME280 sensor and Nextion Display. The problem is that my display doesn't show data from the sensor and from the internet (openweathermap.org), it's only showing the static numbers which I assigned in Nextion Editor.
Here's my code (I hid the ssid, password, apikey and CityID):
#include "Wire.h"
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include "SparkFunBME280.h"
BME280 mySensor;
float hums;
float temps;
float pres;

float tempitod;
float humitod;
float pressitod;
String data;
String result;

char ssid[] = "";
char pass[] = "";
String APIKEY = "";
String CityID = "";

WiFiClient client;
char servername[] = "api.openweathermap.org";

void setup() {
  Serial.begin(9600);
  Serial.print("restart");
  Wire.begin();
  Wire.setClock(400000);
  mySensor.setI2CAddress(0x76);
  mySensor.beginI2C();
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

void loop() {
  hums = mySensor.readFloatHumidity();
  temps = mySensor.readTempC();
  pres = mySensor.readFloatPressure();
  getWeatherData();
  NextionData();
  Serial.print("Humidity: ");
  Serial.print(hums, 2);
  Serial.print(" Temp: ");
  Serial.print(temps, 2);
  Serial.print(" Pressure: ");
  Serial.print(pres, 2);
  Serial.println();
  delay(3000);
  }

void getWeatherData()
{
  if (client.connect(servername, 80)) {
    client.println("GET /data/2.5/weather?id=" + CityID + "&units=metric&APPID=" + APIKEY);
    client.println("Host: api.openweathermap.org");
    client.println("User-Agent: ArduinoWiFi/1.1");
    client.println("Connection: close");
    client.println();
  }
  while (client.connected() && !client.available()) delay(1);
  while (client.connected() || client.available()) {
    char c = client.read();
    result = result + c;
  }
  client.stop();
  result.replace('[', ' ');
  result.replace(']', ' ');
  char jsonArray [result.length() + 1];
  result.toCharArray(jsonArray, sizeof(jsonArray));
  jsonArray[result.length() + 1] = '\0';
  StaticJsonBuffer<1024> json_buf;
  JsonObject &root = json_buf.parseObject(jsonArray);
  String location = root["name"];
  String country = root["sys"]["country"];
  float temperature = root["main"]["temp"];
  float humidity = root["main"]["humidity"];
  String weather = root["weather"]["main"];
  String description = root["weather"]["description"];
  float pressure = root["main"]["pressure"];
  Serial.println(temperature);
  Serial.println(humidity);
  Serial.println(pressure);

  tempitod = temperature;
  humitod = humidity;
  pressitod = pressure;
}

void NextionData() {
  data = "tempitod.txt=\"" + String(tempitod, 1) + "\"";
  Serial.print(data);
  Serial.write(0xff);
  Serial.write(0xff);
  Serial.write(0xff);
  delay(500);
  data = "humitod.txt=\"" + String(humitod, 1) + "\"";
  Serial.print(data);
  Serial.write(0xff);
  Serial.write(0xff);
  Serial.write(0xff);
  delay(500);
  data = "pressitod.txt=\"" + String(pressitod, 1) + "\"";
  Serial.print(data);
  Serial.write(0xff);
  Serial.write(0xff);
  Serial.write(0xff);
  delay(500);
  data = "temps.txt=\"" + String(temps, 1) + "\"";
  Serial.print(data);
  Serial.write(0xff);
  Serial.write(0xff);
  Serial.write(0xff);
  delay(500);
  data = "hums.txt=\"" + String(hums, 1) + "\"";
  Serial.print(data);
  Serial.write(0xff);
  Serial.write(0xff);
  Serial.write(0xff);
  delay(500);
  data = "pres.txt=\"" + String(pres, 1) + "\"";
  Serial.print(data);
  Serial.write(0xff);
  Serial.write(0xff);
  Serial.write(0xff);
  delay(500);
}

The screen seems to be working fine, but it but doesn't gather data from the Wemos (and BME280). Could the problem be with bauds? I set the bauds in my code for 9600 but I don't know whether it changes anything. The strangest part is that, the debugger in Nextion Editor shows correct measurements.
Nxtion display looks like this right now (it doesn't gather data)

And the view from debugger looks like this (it gathers data correctly from the internet and BME280 sensor):

I don't know why Nextion doesn't display measurements.
Here's also photo from connecting Nextion to Wemos D1 mini. Maybe something is bad connected?:

I connected D7 pin from Wemos to RX on Nextion, and D4 pin from Wemos to TX on Nextion.

In NextionData() you appear to be writing Nextion commands using Serial. How is that possibly going to work?

@romkey It's a modified code from GreatScott: https://www.youtube.com/watch?v=daS2CE-zFNo&t=478s
He uses exactly the same Wemos and Nextion. I thought it would work as good as he did. What should be there instead of "Serial"?

Why do you think Serial will communicate with the Nextion when you've connected the Nextion on D7 and D4, which are not the serial port lines?


text:
SPI transactions in Arduino
I have a task where I should do SPI transactions in interrupt mode. Means I have to handle data in IRQ handler (both for tx and rx bytes). How should I approach?
I have a arduino board (2560) and a CAN shield (seeed studio) with SPI interface.
Edit:
From the website: https://www.arduino.cc/en/reference/SPI

With most SPI devices, after SPI.beginTransaction(), you will write
the slave select pin LOW, call SPI.transfer() any number of times to
transfer data, then write the SS pin HIGH, and finally call
SPI.endTransaction()

My question is - the function SPI.transfer() is handled in what way?
Are the bytes transfered/received in interrupt handler or by polling?

Which Arduino board?  That could make a difference.

There are a lot of libraries. Your question is very broad. There are even multiple SPI and I2C libraries. You need to narrow your question down. What library are you concerned about? What do you mean do a transaction "in interrupt mode"? Do you mean, during an interrupt? Or that the transaction should use interrupts?

Your question is so broad I suggest you read How to ask a good question for Arduino Stack Exchange. The answer to "are these libraries interrupt based or polling based" is, briefly, "it depends". So you need to narrow down the question to get a useful answer.

@Delta_G added in the question

@NickGammon yes. I know there are lot of libraries. That is the problem. I have edited the question. And yes "the transaction should use interrupts". Tell me if I have to narrow it more.

I have a lengthy reference question about SPI which may help you.
To transfer outwards you do not need to use an interrupt. Nor is it polled. The data is simply placed in the SPI register and the hardware clocks the data out at the defined SPI rate.
To transfer inwards you are just reading the register. However to know when you need to read it, you would probably put the reading inside an interrupt routine.
I suggest you read the link above, and then if you want, you might expand your question more.
The source for the SPI transfer which I think applies to the Atmega2560 is as follows:
// Write to the SPI bus (MOSI pin) and also receive (MISO pin)
  inline static uint8_t transfer(uint8_t data) {
    SPDR = data;
    /*
     * The following NOP introduces a small delay that can prevent the wait
     * loop form iterating when running at the maximum speed. This gives
     * about 10% more speed, even if it seems counter-intuitive. At lower
     * speeds it is unnoticed.
     */
    asm volatile("nop");
    while (!(SPSR & _BV(SPIF))) ; // wait
    return SPDR;
  }

You can see that there is brief polling (the "while" line) for the register which the processor maintains to show whether the transmission has ended. Then the register is read and returned. So yes, there is polling there.
Now if you use an interrupt (see link above) then you will know that the flag has been set, and therefore there will be no delay (in the polling).


text:
How can I copy and compare a string?
I have the following code (I realise String isn't very efficient, but this sketch doesn't have to be)
debugOutput gets called every loop, but I only want to spam the serial bus (to debug) if the status changes.
However, it runs once, despite changes to the pins being made.
String prevState = "";
void debugOutput() {
  String s = "";
  //s = s + digitalRead(6) ? "1" : "0";
  //s = s + digitalRead(5) ? "1" : "0";
  s = s + digitalRead(4) ? "1" : "0";
  s = s + digitalRead(3) ? "1" : "0";
  s = s + digitalRead(2) ? "1" : "0";
  if(!prevState.equals(s)) {
    Serial.println("State Change: "+s);
    //strcpy(s, prevState);
    prevState = s;
  }
}

My suspicion is it was because of the pointers being the same, but I declare a new string every time this function runs. Just in case, I tried to swap this to strcpy, which isn't valid since I'm using String instead of character arrays.
What can I do, I'm really confused.
This is the Serial output, btw
State Change: 1 So it's clear to me that my string appending isn't even working as expected.

Why are you using a String for this?  Just save the pin states and compare them and if any have changed send a message.  Take out the intermediate step of creating a String from that data and compare the data directly.

Why using a String? Anyway making a copy si as simple as prevState = s; And check for inequality is simply prevState != s.

This was intended to be quick and dirty debug code that wouldn't be in the final thing, I was attempting to do what I thought was easy and quick for me at the time, but when you need to start debugging your debugging code, you start to get frustrated.

I've added an edit as I realized I missed including what my serial output was.

Yeah, operator priority is kinda need to know (or you have to use paretheses). Even  +=  operator would let you avoid stuff like adding result of digital with s and then use it as bool value for ?:  :D

Operator Priority? God damn it, I assumed that the types disambiguate it (coming from Java, C#) would prevent that from happening, now I feel really foolish.

The string class can handle  String+int, and obviously it can be also implicitly casted to the bool value (which is really surprising and quite dangerous operator in this case)

There is this thing called "operator precedence" that defines the hierarchy of operators.
The ?: will be calculated after the +. That's why
s = s + digitalRead(2) ? "1" : "0";

actually means
s = (s + digitalRead(2)) ? "1" : "0";

But you want
s = s + (digitalRead(2) ? "1" : "0");

To make this a more useful answer, you should really mention how the types are ignored / coerced. I've awarded you the answer regardless though. I was aware of operator precedence, but not how it interacted with the types under C.

I'm not sure why string appending using + was failing, but changing it from
s = s + digitalRead(2) ? "1" : "0";
to
s += digitalRead(2) ? "1" : "0";
fixed my issue.

I won't be accepting this as the answer, even though that it is AN answer, in order to award the answer points to someone that explains what was wrong.

first of all you shouldn't use String for this. you can store numbers, compare numbers, print numbers. digitalRead returns a number


text:
Connect one SD card to two devices
I have a system where an Arduino controls a DSLR camera for environmental monitoring. The Arduino can power on/off the camera and control the shutter (through the standard plug for a external shutter). The Arduino record and transmit the status of the system (battery voltaje, time of the last shot, etc.).
I want the Arduino to be able to access the camera's SD card while the camera is powered off. In order to check if the pictures were actually taken and check available memory (I don't need to write to the card).
So my questions are:

If I create a contraption to connect a single card to the camera and the arduino. The fact that the card is connected to one device (although not been used) will interfere in the operation of the other?
Should I consider the use of a multiplexer or something alike to completely disconnect the data lines from one device while the other is using the card?

An SD card has two interfaces: The SPI interface is what is used by the Arduino (it is rather slow). The second one is a parallel interface, which is capable of way bigger transmission speed. It is most likely, that the camera uses that interface, since it has to transmit rather big data packets in a short time. But as I remember some pins are used for both interfaces.
We cannot know, what happens inside the camera. But providing voltage to a digital pin of a microcontroller, while it is not powered, (as it would happen, when you drive the SD card while the camera is off) can be harmful. We must assume, that this would also happen with your camera, or you risk damaging it.
Using multiplexers (or - if you find no fitting one - some simple transistors) to disconnect the camera, when you want to connect with the Arduino, seems a good idea to me. Disconnect all lines, including the supply voltage. The ground line has to stay together, though you should check with a multimeter, if the SD slot ground is the same as the shutter connector ground (if they are not, you don't want to connect these grounds). Is most likely is, but you should check it to be sure.


text:
Is WiFi traffic encrypted on ESP32?
I am using the ESP32 in soft access point mode. In other words I specify my wifi username and password on the ESP32 and I am able to connect to it from my phone.
So I am not using any router or internet connection. Only my phone and the esp32.
If my phone is the only device on the network created by the esp32 do I have to worry about HTTPS? People say HTTP is not secure and I also know how easy it is to see http traffic with Wireshark. But if no one else has access to the network I guess http is secure correct? If no one knows the wifi password will my http requests be encrypted? Moreover, if I connect from my computer instead than my phone via wifi to the ESP32 and send UDP packets will those be encrypted?

the quality of the encryption depends solely on the quality of the wifi password.

WiFi with WPA2 (which is what you get when you specify a password) is encrypted.
As long as your HTTP requests only go over that connection and nowhere else then yes, they are encrypted and as secure as WPA2 (which isn't unbreakable, but not easy to break).
HTTPS adds encryption for use over the internet which in general is not encrypted.

If you provide a password for you network, it will be encrypted. Thats the point of the password. When you look at the function description in the WifiAP.cpp file of the Wifi class for the ESP32, the description suggests, that it will be encrypted with WPA2, which is currently the standard in Wifi encryption. (Though that can depend on the actual library, that you are using)

do I have to worry about HTTPS?

That depends on your needs. In IT security is a scale, not a binary. Using HTTP on a WPA2 protected network can be considered safe on the one side and unsafe on the other. You need to thing about, if your project needs that additional layer of encryption through HTTPS.
For example: If you control your Smart Home with that ESP32, which may be able to open your windows or even the door, I would consider that critical. Then I would take every bit of security, that I can get, as there are ways to break into a WPA2 protected wifi network.
An example in the other direction: I'm currently building a game, which gets configured on a smartphone via the Wifi network of an ESP32. The network is encrypted to prevent casual attackers from messing with my current game run, but the project has so low security needs, that I will not bother with HTTPS. It's just a game, that will not that often being used, and the possibility of an attack on it is very low.
So it's about risk assessment (as with all security in IT).

if I connect from my computer instead than my phone via wifi to the ESP32 and send UDP packets will those be encrypted

The mentioned types of encryption (WPA2 and HTTPS) happen on two different layers of the network communication. With WPA2 your complete wifi data of that network is encrypted. So the UDP packet is also encrypted, but only in that wifi network, and it can be read by any authenticated user of the network. HTTPS works in a layer above that, so that your packet would be encrypted, even if it would move out of that Wifi network. For learning more about network layers, refer to the OSI model.

Apart from the security perspective: When you use HTTPS you also need to think about the certificate, that you are using. If you use a self-signed one, your browser will present you a warning about that, everytime you open that site. To prevent that, you either need to trust that certificate on all your devices, or you need to use an officially signed certificate (which might be a problem for a pure local project).


text:
Erasing 1 byte of external Flash memory (winbond)
i'm trying to use an external flash memory Winbond 25q64jvsiq for my Arduino Nano based project for audio recording purposes, to have extra memory for recording 1 byte audio samples, since Arduino nano SRAM memory is too small (8kb), to store at least 1 second of 8 kHz 8 bit samples audio. I'm trying to understand the basics of  bytes storing in my external memory. I'm using SPIMemory library for that, and i can't find a function to erase 1 byte, there is only sectorErase() function. So i wonder is it even possible to erase a single byte of external memory?
Here is a part of code where i try to rewrite (erase one byte and write a new one) a next byte when the button pressed, but when it erase a sector it erases not the one byte but all bytes behind it, and i want to manipulate it more accurate, and erase only one byte:
if(!digitalRead(5)){      //button pressed
     if(e<3){
      e++;
      flash.eraseSector(count);    //erasing a byte
      flash.writeByte(count,e,NOERRCHK); // write a new value
      }  else {
        e=0;
        flash.eraseSector(count);
        flash.writeByte(count,e,NOERRCHK);
        }
     }

For a flash chip, no it's not possible to erase a single byte.
The closest you can do is to read an entire sector into memory, erase that sector, modify your in-memory copy, then write the sector back.
You would be better using an SPI SRAM or PSRAM chip instead of a flash chip.


text:
Why do my Hall sensor readings change when I write them to the serial port?
I have a small project where I connected a Hall sensor (see picture) to an Arduino Mega. The blue wire is connected to pin 45, the red wire to +5V, and the black wire to GND.

At the beginning I initialize the pin used to read the sensor as follows.
#define HALL_PIN 45

void setup()
{
  pinMode(HALL_PIN, INPUT);
}

I have written a function to read out the sensor. While there is no magnet nearby, the sensor returns HIGH. If a magnet approaches in the correct orientation, the sensor returns LOW. The function should return true if a magnet is nearby, i.e. if the read value is LOW.
I have noticed that my program logic sometimes does not work reliably after seemingly irrelevant changes to the code. After commenting out more and more code to narrow down the problem, I came across the following discovery.
Implementation 1:
In the first implementation, I initially read out the value of the Hall sensor. Next, I send the value to the serial port. The serial monitor in the Arduino IDE outputs the number 1 (HIGH). This is the expected behavior as during testing there is no magnet nearby. Based on the subsequent program behavior I can confirm that the function returns false. I can let the Arduino run for minutes and the behavior remains stable.
bool readHallSensor()
{
  int s = digitalRead(HALL_PIN);

  Serial.println(s); // The serial monitor outputs 1 (HIGH)

  return s == LOW; // Returns false
}

Implementation 2:
With the second implementation I do not write the read value to the serial port. As expected, the serial monitor in the Arduino IDE remains empty. The function, however, now returns true. Apart from commenting out the marked line and flashing the sketch to the Arduino, I did not make any changes (again no magnet nearby). Also in this case I can let the Arduino run for minutes and the behavior is stable.
bool readHallSensor()
{
  int s = digitalRead(HALL_PIN);

  // Serial.println(s); // No output to the serial monitor

  return s == LOW; // Returns true
}

My first suspicion was that the delay caused by writing to the serial port is what makes the difference. I asked an electrical engineer whether Hall sensors might need short breaks between successive readings. He denied my assumption, and indeed, if I simply insert a delay(300); after reading the value (without writing to the serial port) the behavior does not change and is identical to implementation 2.
I can switch back and forth between the two implementations and flash them to the Arduino as many times as I like. The behavior is always as described above for both cases. I cannot make any sense of this, as the behavior seems to lack any (programming) logic. Has anyone ever made similar observations and can give me a hint what might cause this? Thank you in advance.

I haven't found the problem yet, but I have come a step closer. The issue has reappeared in a similar project on the same Arduino. I use a new Hall sensor with pull-up, which is read out wrong again under certain circumstances (always read out as LOW, no matter if a magnet is nearby). The problem seems to occur only when I use a certain pin. The pin in question on my Arduino Mega this time is pin 37. If I connect the Hall sensor to another pin (I have tested 34 and 36), it works fine. If I connect a previously working Hall sensor to pin 37, it will not work anymore (always evaluated as LOW). The only explanations that make sense to me at the moment are that either the Arduino Mega is damaged or that there are side effects, maybe caused by external libraries using certain pins without my knowledge and incorrectly initializing them.

what happens if you use Serial.println('x');?

Do you have a pull up connected between 5 V and the digital output pin? Please check. is it the same with other digital pins too?

@goodarduinocode.com Good observation, but it looks like one may be present on the sensor board.

The problem could be in another part of the code.  When you run into situations where a seemingly unrelated change completely changes the behavior of the program then you are often times up against some issue causing undefined behavior like a buffer overrun or a memory issue or a bad pointer or something.  It can be in a completely unrelated part of the program.  But if memory is getting clobbered somewhere then there is no way to predict what the consequences will be.  Post a complete and compilable example that illustrates the problem.

Writing a string constant to the serial port (instead of the read value) results in the same behavior as in implementation 2 (no writing to the serial port at all). I added a pull-up since the output voltage was a bit low. However, this did not change the behavior. It seems that the sensor worked fine before and that the problem is software-related. Unfortunately, I still could not find the cause of the problem. I will make sure to update this thread if I should find out what it is. Thank you all for your suggestions!

The 3144 requires a pull-up resistor. It only sinks when a magnet is present. It doesn't source, so the pin is floating if no magnet is present.
You can use the internal pull-up resistor by using pinMode(HALL_PIN, INPUT_PULLUP);

The Hall sensor came already pre-mounted on a circuit board with a resistor (see picture in my first post). My assumption was that the pull-up was already there. But when we measured the voltage of the output signal, we found that it is only 3.8V (with 4.8V as input voltage). Adding a pull-up has increased the output voltage to the full 4.8V. However, this did not change the behavior of the Arduino so it does not seem to be a hardware problem. Nevertheless your advice is absolutely justified and it is certainly better to add a pull-up. So thank you for that.

I think that resistor is for the LED, not a pull-up. Though the net effect is that it will pull-up output pin to 5V minus the forward voltage of the led. The forward voltage of a red led is around 1V so that would give you the voltages you've measured.

Thank you for the clarification. My understanding of electrical engineering is still quite limited and I really appreciate your help.


text:
help explain pulseIn function with arduino and Ultrasonic sensor
dears Engineers.. i got stuck with this issue couldn't understand.. please help with explanations.
first i was upset of my ultrasonic sensor reading deviations, that is i examine my sensor indoor and at quite environment,, so what makes this noisy output readings??!!!
so i tried to dig into the pulseIn function and tracking the timing of each instruction in the code..
after reading the library.., i decided to use pulseInLong function.
following is a result of some iterations timing in microseconds:
Ultrasonic Sensor HC-SR04 Test
with Arduino UNO R3
Start ~ trig LOW  ~ 10us delay ~ trig High ~ 10us delay~ trig High ~   pulseIn    ~   Duration
0           8           12          8           12          4           7352            137976
4           4           12          8           12          8           7336            137960
4           8           12          8           12          8           7352            137976
4           8           12          8           12          8           7356            137980
4           8           12          8           12          8           7352            137976
4           8           12          8           12          8           7356            137980
4           8           12          8           12          8           7360            137984
4           8           12          8           12          8           7364            137996
0           8           12          8           12          8           7364            137992
4           8           12          8           12          8           7372            137996
4           8           12          4           12          8           7380            138004
0           4           12          8           12          8           7372            137996
0           4           12          8           12          8           7348            137968
4           8           12          4           12          8           7372            137996
4           8           12          8           12          4           7376            138004
4           8           12          8           12          8           7380            138008
0           8           12          8           8           8           7352            137980
4           8           12          4           12          8           7352            137976
4           8           12          4           12          8           7368            137992
4           8           12          8           12          8           7340            137964
4           8           12          4           12          8           7352            137980
4           8           12          4           12          8           7360            137984
12          8           12          8           12          8           7368            137996
4           8           12          8           12          8           7348            137972
4           8           12          8           12          12          7360            137984
0           8           12          8           12          8           7344            137968
4           8           12          8           12          8           7352            137976
4           8           12          8           12          8           7364            137988
4           8           12          4           12          8           7360            137984
4           8           12          8           12          4           7372            138000

first i wondered why there are different execution time for the same instruction??!
for example digitalWrite(trig_pin,LOW or High) varies in range 4 ~ 12 microseconds!!????
more strange when i found elapsed time after delay 10us, micros() function shows only 8 us??!!!
all these in range of 16 us,, so i expected maybe due to some instruction cycles or unprecise clock...etc.
but the BigBang i shocked when read this huuuuuge difference in pulseIn timing measurment;
i reset the timer befor the function and just after it, so i got an elapsed time in range of 7350 us. in the same time the resultant measured time from the function in range of the  138000 us?????!!!!!!
put in mind that pulseInLong is a blocking function..as you will see below, it loops in a while loop until timeout (so return 0) or pulse generated and measured before timeout then return pulse elapsed time.
first i suspected in this number maybe not microseconds. inspected the function deeply, ??!!!
i found it using the exact micros() function such i do in the code?
 * this function relies on micros() so cannot be used in noInterrupt() context
 */
unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout)
{
    // cache the port and bit of the pin in order to speed up the
    // pulse width measuring loop and achieve finer resolution.  calling
    // digitalRead() instead yields much coarser resolution.
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    uint8_t stateMask = (state ? bit : 0);

    unsigned long startMicros = micros();

    // wait for any previous pulse to end
    while ((*portInputRegister(port) & bit) == stateMask) {
        if (micros() - startMicros > timeout)
            return 0;
    }

    // wait for the pulse to start
    while ((*portInputRegister(port) & bit) != stateMask) {
        if (micros() - startMicros > timeout)
            return 0;
    }

    unsigned long start = micros();
    // wait for the pulse to stop
    while ((*portInputRegister(port) & bit) == stateMask) {
        if (micros() - startMicros > timeout)
            return 0;
    }
    return micros() - start;
}

anyway..i dont want to make this story long..
can someone explain what is going on to me please?!
thanx
here is arduino code i used
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04

// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

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

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed

  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
  Serial.println("with Arduino UNO R3");
  Serial.println("Start ~ trig LOW   ~   10us delay   ~   trig High   ~   10us delay   ~   trig High    ~    pulseIn    ~   Duration");

}

void loop() {
  // put your main code here, to run repeatedly:
  // Clears the trigPin condition
  int indx = 0;
  int arr[7] = {0};
  double last = micros();

  arr[indx] = micros() - last;
  indx++;
  last = micros();

  digitalWrite(trigPin, LOW);

  arr[indx] = micros() - last;
  indx++;
  last = micros();

  delayMicroseconds(10);

  arr[indx] = micros() - last;
  indx++;
  last = micros();
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds

  digitalWrite(trigPin, HIGH);
  arr[indx] = micros() - last;
  indx++;
  last = micros();

  delayMicroseconds(10);
  arr[indx] = micros() - last;
  indx++;
  last = micros();

  digitalWrite(trigPin, LOW);
  arr[indx] = micros() - last;
  indx++;
  last = micros();

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseInLong(echoPin, HIGH);
  arr[indx] = micros() - last;

  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor

  for (int i = 0; i <= indx; i++)
  {
    Serial.print(arr[i]);
    Serial.print("     \t    ");
  }
  Serial.print(duration);
  Serial.println();

}

Look at the source code, you have it.  digitalWrite is a function that has several lines in it.  There are interrupts running on the chip.  If one of those interrupts fires during the execution of the digitalWrite function then it will take longer to execute that time.

This method of reading an ultrasonic sensor is a great way to introduce someone to how those types of sensors work, because it is really easy to follow code, but there are much better ways to handle reading an ultrasonic sensor in a much more accurate manner.

thanx Delta_G for responding here,
but unfortunately, i still can't get the point!!!
first: why sometimes i measure an elapsed time 8us, while i used a delay of 10us?!
second: why do i receive big difference in time measurement between elapsed time while execution the pulseInLong function and its return duration measurement!?

Go read the documentation on delayMicroseconds.  It clearly states that the resolution of that function is 4us.

Just to add my two cents. Perhaps the digitalWriteFast library might come handy for this time-critical application. I normally use it instead of the default function and it certainly saves a bit of time

I see at least three reasons for the behavior you notice:

micros() has a resolution of 4 µs. If you could call it at a
period fixed to exactly 10 µs, you would see the time deltas
alternate between 8 and 12 µs. But then micros() takes some
time to execute, so if you use it to time a function that takes
10 µs to execute, you will read 12 µs more often than 8.
There is a timer interrupt firing every 1024 µs. Any process
that gets interrupted will show an execution time longer than normal.
This is the likely cause of digitalWrite() taking occasionally a
lot longer than usual.
pulseIn() waits for the start of the pulse before it starts to
measure its duration. Its execution time can then be significantly
longer than the pulse duration it reports.

i expected maybe due to some instruction cycles or unprecise clock.

The same clock is used for sequencing the CPU instructions and for
timing them. So the clock precision has no effect on the timings you
measure.
Edit: There is an extra issue here, which is the overflow of
arr[6]. The execution time of pulseInLong() may be something like
138,424 µs. Since an int on the Uno is 16 bits, this value wraps
modulo 216 to 7,352, which is the value shown in the first
line of the output.

Dear @Edger Bonet and other Engineeries
please concentrate with me little bit..

@absi: What do you mean?

#3) The point number 3: regarding pulseInLong returned time and execution time:
the time returned by the function is what i listed in the timing table under duration, where the execution time is listed under pulseIn at the timing table.
as you can see the execution time is much less than the returned measured time for the pulse, and that is very strange??!!
so please someone try to explain

@absi: Oh, I missed that. See amended answer.

Why do I receive the big difference in time measurement between
elapsed time while execution the pulseInLong function and its return
duration measurement?

The answer lies in the choice of the way it is implemented.
The delay function itself is helpful but the accuracy is not great when precision is needed. Here is the official note from the site:

This function works very accurately in the range of 3 microseconds
and up. We cannot assure that delayMicroseconds will perform
precisely for smaller delay-times.
As of Arduino 0018, delayMicroseconds() no longer disables
interrupts

If you want to really be precise, I recommend to use hardware timers. I believe it will suffice. to know more about using hardware timers you can refer to
https://learn.adafruit.com/multi-tasking-the-arduino-part-2/timers
https://maker.pro/arduino/projects/timer-interrupts-improve-your-arduino-programming-skills


text:
Where are the Arduino Function Unit Tests kept? I want to submit a fix for a faulty Arduino function
I have coded a fix for a major problem with the Arduino map function (in Arduino.h & arduino/avr/cores/arduino/WMath.cpp).
I submitted it as a comment to map function causes huge errors when mapping to small intervals due to integer truncation #10382 but heard nothing so far.
I thought it might be handled quicker if I can submit it as a Pull Request with Unit Tests to A) expose how and why map is faulty and B) show how my solution fixes the problem.

You should be submitting requests about the API to the API repository, not the core repository: https://github.com/arduino/ArduinoCore-API

I am not aware of any unit tests within the Arduino core. I suggest you commit the code change with no tests, add a small test sketch (mostly Serial.println()) within the “cover letter” of the pull request, and state the results you get with and without the patch applied.

@Majenko note that the API is fine. It's the code in the core that does not implement the API properly (assuming that arduino/avr/cores/arduino/WMath.cpp is in the core)


text:
Is it possible to detach an interrupt for a certain ammount of time
Hardware: Arduino Uno
Software Version: 1.8.13
My sketch has an interrupt service routine that triggers with the rising edge of digital pin 2.
What I want to do now is detaching the interrupt as soon as it has been triggered once and reattaching it as soon as a certain amount of time (>1s) has passed.
However despite of trying I haven't found a possibility to do this.
I have tried detaching it in the ISR itself and reattaching it in the main loop with a delay after manually clearing the interrupt flag. However with this approach the time the interrupt is detached for depends on the point of time the interrupt is triggered, which is undesirable.
Is there a better solution for this? Thank you in advance for every answer

The standard way to do this is just as you described (but with the non-blocking coding style like in the BlinkWithoutDelay example): Detach in the ISR and setting a flag and a timestamp. Then in the main code check the flag and the time since the timestamp was took. In code that looks somewhat like this (Note, that I left out some arguments of the attaching/detachting functions):
volatile byte flag = 0;
volatile unsigned long timestamp = 0;
#define REACTIVATE_INTERVAL  1000

void ISR_function(){
    detachInterrupt(...);
    flag = 1;
    timestamp = millis();
}

void setup(){
    attachInterrupt(..., ISR_function, ...);
}

void loop(){
    if(flag && millis() - timestamp > REACTIVATE_INTERVAL){
        flag = 0;
        attachInterrupt(..., ISR_function, ...);
    }
    // Rest of your main code from here on
}

For this to work correct, you must of course use a non-blocking coding style in your main code, meaning no delay()s (except for really small ones) and no blocking while loops. If you have those in your main code, you should rewrite it to be non-blocking. Not only for this feature, but for any further extension of your project. A non-blocking coding style is an important principle to embrace, especially microcontrollers.

Without a non-blocking coding style, you would need to use a timer interrupt, to reattach the pin interrupt. While that is totally possible, it does not make much sense to configure extra peripherals of the Arduino just for this.

That's exactly what I was looking for. I was irritated by the fact that the interrupt causes the timer to stop incrementing but now it makes sense. Thank you :)

You mean, that millis() will stop counting while inside the ISR? Thats correct. But it doesn't matter here, since we just get the current value and them leave the ISR very quickly


text:
What NRF24L01 module is this?
I received my NRF24L01 Module today but I'm having a hard time finding any resources about this particular combination of modules!
https://i.stack.imgur.com/Tiwyj.jpg
I tried searching up the v200 1812A but no results...You would think the seller would have some documentation on his page but nothing.
Does anyone know what I'm dealing with here?
Thank you!

What numbers are on the chips?

@Majenko Both the modules display the same V200 1812A, the only slight variation is that one says WSCOM and the other WSUSB

I asked what is on the CHIPS not on the MODULE.

Excuse me, the WSCOM module has a chip with the markings (ST MICROELECTRONICS) 78754 32F03DF4O6 PHL B17 A

That sounds like an STM32F0 ARM M0 chip?

I highly doubt it. You can see the sheer difference in size and pins on the chip

The actual number is not what you read (it can be hard to distinguish some letters / numbers), but is 32F030F406.

They are transparent bridge modules that are designed specifically to work together. It's intended to be kind of like a wireless UART.
This AliExpress Seller details how to use them.
You need one UART and one USB module. You plug the UART module into the USB module and plug the USB module into your computer. After about 10 seconds the modules are paired together.
You then separate them, and you can connect the UART module to your Arduino or other board.
Now you have a wireless UART between your computer and your Arduino.
Alternatively, since they have an STM32F0 chip controlling them you could hack them to do other things using stm32duino.

Ah thanks! Is an Arduino library available to work with it? That's all whats left what's keeping me to work on it!

To use it as is there's nothing to "use". You just plug it in (once it's paired) like you would an FT232 cable.

So wait, I can't connect this to my arduino? I thought that I would've been able to communicate between my pc and my arduino... Even that seller page never mentioned the usage of an Arduino

Once paired you connect the UART portion to the Arduno. Like you'd connect the TTL UART side of an FT232 cable to the Arduino.

Alright, 1 last question. Since the breakout of the UART module differs alot from the "standard" NRF24l01 module, how should I connect the RXD and TXD part of the WSCOM module to my arduino? I dont suppose I can just hook it up to my Arduino Micro's RX and TX?

If you're not using them for the USB interface then yes, you can. Or to any other pins and use SoftwareSerial. It's. Just. Serial.


text:
ESP32 nodemcu serialbt sending data
I'm currently trying to send data from esp32 to my android app that I made. The sensor readings are showing in the serial monitor, however, what's showing on my app are either @ or &. Please help and thank you. I'm new to bluetooth coding.
Here's the code:
#include "BluetoothSerial.h"
int sensorPin = 35;
int sensorreading;

BluetoothSerial SerialBT;

void  setup ()
{
    Serial.begin(115200);
    SerialBT.begin("ESP32_ABO");
    pinMode (sensorPin, INPUT);
}
void  loop ()
{
   sensorreading = analogRead(sensorPin);
   String toSend = String (sensorreading);
   sendData(toSend);}

void sendData(String textToSend){

   Serial.print(sensorreading);
   SerialBT.write(textToSend[sensorreading]);
}
delay(1000);}

You see very different output via bluetooth and Serial Monitor, because you are sending completely different things. On the Serial Monitor you see the sensor reading, since that is exactly, what you send:
Serial.print(sensorreading);

The print() function will convert the integer variable sensorreading into human readable text (meaning ASCII encoded text) and send this over Serial.
But then you do this:
SerialBT.write(textToSend[sensorreading]);

textToSend is a String object here. So with the parentheses [ ] you are taking one character of that string. You try to use the sensorreadingth character. Since sensorreading comes from an analogRead(), it is most likely, that is value is rather big, meaning bigger than the length of the string. So you are basically reading some random memory, that happens to lie behind your string variable. The write() function will then send that random data out over your bluetooth serial interface, without any conversion.
I guess you want to transmit the data over bluetooth also in human readable form. So just use the same code as with the Serial interface (for the Serial Monitor).
And remove all that manual conversion of the measured analog value to a String. That is not needed. If you want to also display some text, you can just use multiple print() commands, like this:
Serial.print("Value: ")
Serial.print(sensorreading);
Serial.print(" units");

Note, that it is rather bad to use the String object at all. The String class uses dynamic memory allocation, which leads to memory fragmentation, which can eat up your available memory. This is not as important on chips with rather big memory (as the ESP32) than on chips with smaller memory (like the Atmega328p, which is used in Arduino Uno and Nano), but you should still keep that in mind. Instead of the String class you would work with char arrays, aka C-strings.

thank you sir. i tried a different approach using serialbt.write(sensorreading); instead of SerialBT.write(textToSend[sensorreading]); i get values that displays ranges from 2300 to 2400 on my serial monitor. When I try to connect it to another app, serial terminal bluetooth app which i downloaded on playstore. in the app it just displays random letters this time.

this is my current code:
#include "BluetoothSerial.h"
int sensorPin = 35;
int sensorreading = 0;
BluetoothSerial SerialBT;
void  setup ()
{
Serial.begin(115200);
SerialBT.begin("ESP32_ABO");
pinMode (sensorPin, INPUT);
}
void  loop ()
{
sensorreading = analogRead(sensorPin);
Serial.print(sensorreading);
Serial.println("mV");
SerialBT.write(sensorreading);
delay(1000);}
sorry i'm really new to arduino

thank you so much for your help sir! what is was lacking was a serialBT.print(sensorreading); to display it to the device app thnk you very much for your help

Thats great. As mentioned in the answer, SoftwareSerial.write() will send out the data untouched, meaning, that you send that data as binary (just the binary representation of the number). SoftwareSerial.print() instead creates an ASCII encoded representation of the number, which is human readable text. The app on your phone just receives the data from serial and interprets it as ASCII encoded text. So you get some random characters, when sending binary data.

If that answered your question, you can accept my answer as correct


text:
Change arduino output from input
I'm trying to change values such that the arduino uno outputs comes from what is input, with the code,
int PinOutput = 11;
int PinInput = A0;
int inph;
int inpl;
int input;

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(PinInput, INPUT);
pinMode(PinOutput, OUTPUT);
delay(100);
}

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

  {

    input = Serial.read();

  }

 else
{

    input = 255;

}
    inpl = analogRead(PinInput)/4;
    Serial.println(inpl);
    analogWrite(PinOutput,input);
    delay(10);
    inph = analogRead(PinInput)/4;
    Serial.println(inph);
    analogWrite(PinOutput,input/2);
    delay(10);

}

Where pin 11 is connected with an RC circuit to pin A0. Will this code take a value through pin 11 and output it to pin A0? I'm checking if this should work right, so I can then check the python code that goes with it. As of now it mostly stalls, but maybe it's a problem with the python code. I'm trying to make it sustain the number put in. Python code I've tried with is,
import serial
import time

ser = serial.Serial('COM3', baudrate = 9600, timeout = 1)
time.sleep(1)

while 1:

    userInput = input('Get data point? ')

    ser.write(userInput.encode())

    for i in range(5):
        arduinooutput = float(str(ser.readline().decode().split('\r\n')[0].strip('\x00')))
        print(arduinooutput)
        time.sleep(0.01)

The numbers printed out are somewhat random, around 100, it seems, no matter the value put in.

pin 13 is not a PWM pin on Uno. https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

@Juraj ok I switched it to 11

PWM is fast switching between 0 V and HIGH. so analogRead will read only 0 or 1023.

You will need a filter between the PWM output and he analog input. Use your favorite web search engine and look for "R/C filter". Since you are waiting for a second already, a long time constant will be fine, without calculating you might like to start with 100 kOhm and 1000 µFarad.

@the busybee ok I can make an rc circuit. So is there no way to send a signal through one pin and receive it through another with a range of values (with just a wire connection)? Only 0 V or HIGH?

Correct. The AVR in the Arduino does not have a DAC (digital analog converter). If you want some, you will need to add another IC.

Well, it's a pity, but the name of analogWrite() is kind of misleading. :-} If you connect the PWM to anything observable by humans like an LED, it will look like being analog.

@the busybee yes I guess an LED and a photodiode could work to transmit an analog signal also.

@user14094230: an LED and a photodiode may be too fast for that. An LDR, on the other hand, may be slow enough to provide the required low-pass filtering.

Ok, I added an RC circuit that outputs DC, the question now is whether the code should work.


text:
Connecting ESP8266 to website
I would like to control a relay using Wemos D! R1 via a website from anywhere. I managed to control it using local web server and now would like to step it up further.
I'm using the following code which connects to this website and retrieve data as JSON perfectly.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

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

void setup () {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
    }
}

void loop() {
    if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
        Serial.println("");
        HTTPClient http;  //Declare an object of class HTTPClient
        http.begin("http://jsonplaceholder.typicode.com/users/1");  //Specify request destination
        int httpCode = http.GET();                                                                  //Send the request

        if (httpCode > 0) { //Check the returning code
            String payload = http.getString();   //Get the request response payload
            Serial.println("");                  // Empty Line
            Serial.println(payload);             //Print the response payload
            //////////////// Json code
              StaticJsonDocument<2000> doc;
              DeserializationError error = deserializeJson(doc, payload);
              if (error) {
                Serial.print(F("deserializeJson() failed: "));
                Serial.println(error.c_str());
                return;
              }
              const char* sensor = doc["name"];
              const char* username = doc["username"];
              const char* email = doc["email"];
              const char* address = doc["address"];
              Serial.println(sensor);
              Serial.println(username);
              Serial.println(email);
              Serial.println(address);
            //////////////// End of Json Code
              http.end();   //Close connection
              while ( 0 < 1 ){ delay(10000); }  // to break the loop
            }
    }
    delay(10);    //Send a request every 30 seconds
}

I made a web page that makes AJAX call to a PHP file to retrieve data from MYSQL DB, but when I run it, the monitor keeps printing empty lines forever although connected successfully to my WIFI.
$(document).ready(function(){
$.ajax({
        url: "test.php",
        type: 'GET',
        dataType: 'json', // added data type
    data: ({mobile: 'hi'}),
        success: function(res) {
            console.log(res);
        }
    });
});

The result I'm getting from AJAX is (which you can check visiting this link:
    {"status":"ON"}

I'm using the following code on php file:
<?php
header('Content-type: application/json');
require 'functions.php';
header("Access-Control-Allow-Origin: *");
    $catrecord = mysqli_query($link,"SELECT * FROM `ard`");
        while($catinfo = mysqli_fetch_array($catrecord, MYSQLI_ASSOC)){ $Cat = $catinfo['status']; }
    $responseArray = array('status' => $Cat );

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);
    header('Content-Type: application/json');
    echo $encoded;
} else {
    echo $responseArray['status'];
}
?>

check the returning code. 200 is OK. all others are an error. negative return values are a local error. positive are a HTTP error

What is the exact question? You don't know how to modified the Arduino code to receive json payload of {"status":"on"}?

you can use port forwarding or websockets to control from the WAN. or hammer the php site from the wemos, but that's not as good as talking to the esp server directly or having always-on streaming.

@dandavis "talking to the esp server directly or having always-on streaming." would you please elaborate more or share a link about this methodology. Thx

You should do what @Juraj suggested. The way it's written now, your code won't correctly report errors which would hide the cause of the problem you're seeing.


text:
Neo 6M + ESP32 unable to take a fix on battery but works fine with laptop USB
I am using Neo 6M GPS module with ESP32 and 2 X 3.5V(7 v in series) 18650 lithium ion battery stepped down to 5V using LM2596 buck converter.
Problem which I am facing is when I power ESP32 using 5V output of LM2596 by connecting Vin pin and powering Neo6M using 5V output of buck converter or 3.3 V of ESP32 then my Neo 6M is unable to fix on satellite, however when removing battery and LM2596 and powering ESP32 using laptop usb cable and Neo 6M using 3V pin of ESP32 then its able to take a fix in 1 minute.
Any idea what mistake I could be doing.
Note - When using battery ESP32 is working as normal and able to connect to wifi and submit Tiny GPS++ output everysecond.
Please let me know in case more information required.

With full battery charge to 3.7V this issue was resolved also using 10uf capacitor between vcc and ground help to improve

You have several problems. You are telling me it is power related as the ESP runs fine but the Neo 6M failed. Reason the Neo 6M does not tolerate as wide a voltage range as the ESP32. Using a Buck converter is a mistook, you should use a SEPIC (bicl/boost in one), this will maintain the voltage to your project as the battery voltage changes with its charge etc. With the correct SEPIC converter you can parallel the batteries giving you more instantaneous current. The buck converter needs head room, that is so much voltage above the output to work properly. I doubt it is less than 2v. Using small wires will esterbate your problems. The 10uF was a good idea but you also want to add something for high frequency. This should get you going.


text:
Measuring car speed between two points: What sensor to use and how to cover the distance?
PROBLEM
Cars regularly exceed the speed limit in our street
SOLUTION
Measure each car's speed and clearly display the speed to the driver
EXECUTION

Measure the time the car takes to cover a set distance (e.g. 25 meters) to calculate the speed
For this I'd set up two sensors and calculate the difference between the timestamps recorded between the car passing the first and second sensors -> then convert into km/h
Display the result on an LED screen

CHALLENGES & QUESTIONS
A. What sensors should I use here? Photoresistor with laser diode, digital or analog IR sensor, ...
B. How can I best cover the distance between the sensors and connect them to the Arduino? Long wire, wireless, connect two Arduinos, ...
Thanks!

radar is used to measure speed of cars. google found https://www.sierzega.com/en-us/about-us/our-products-services/speed-displays

Thanks @Juraj. I posted a question regarding a 150$ project on an Arduino forum so you send me a link to buy 2000$ ready-made systems... Sorry, not very helpful at all. The point is to build stuff! :-)

@Uralan your post says nothing about a price limit

Okay  that's true.

https://www.eevblog.com/forum/projects/playing-with-cheap-hb100-doppler-radar-module-for-car-speed/

Doppler radar is often used, but may be overkill? Perhaps the best-known DIY radar project is MIT's open courseware. There's a separate paper devoted to the antenna if you want a deep dive.

Why 25meters? If you place the two sensors 1 meter apart, you only need 1ms accuracy to get km/h (assuming a 50km/h speed limit). The Arduino can handle 1ms resolution with ease.
I'd probably go with 3-5 meters, so you don't need your setup to be that precise (i.e. distance and alignment of the two sensors). Lowering the distance also makes it less likely for two cars, from both directions, to simultaneously be inside your sensor area.
For the sensors, the biggest problem is the legal one. Having objects on/near the road could cause some liability issues. The laser solution is probably the least likely to cause this issue. Though I'm unsure about having a display next to the road.
You could go with laser and photo-transistor on one side of the road. And a reflector/mirror on the other side. I'd probably go with an IR laser, so it's invisible. You'd have to shield the photo-transistor as much as possible from ambient light, so a sudden cloud won't trigger it. You probably still need to do some filtering in software.
There are radar modules available, but I think they are pretty expensive.
Another option is a Laser range sensor, like this one from sparkfun

Thanks! Good points! I will probably go for IR laser curious to see how well it'll all work...

You need 3 ir/laser emitters, mirrors and phototransistor sensors to get  the car's direction and some reliability. Good luck with the legal issues.

You can also modulate the laser, similar to how tv remotes modulate the signal, so other IR light sources don't interfere. You could maybe even use IR receivers, instead of phototransistors.I don't have a great solution on how to align the system, so the laserbeam hits the sensor. Maybe some crappy phone camera that doesn't have an IR filter, so you can see where it's pointing.

The alignment issue would be solved by using a corner reflector instead of a mirror. See also Retroreflector.


text:
Reading a json file from SPIFFS and displaying the info it contains on an embedded web page
I am working on a smart IR receiver that reads an IR signal, decodes it and saves that decoded info in a json file stored on the NodeMCU's SPIFFS. This info is then displayed on the embedded web server in a table.
Now my problem is that even though I correctly save the signal's info in the json file (and when I try to print it in console it looks perfect), the son file is not correctly passed to my web server and the table remains empty. I am using jQuery to read the file and make the changes in the HTML. All the web server files (HTML, css & JavaScript) were tested first on my local machine with an example Json file of the same structure I am using on my SPIFFS so I know for sure the problem is not in there.
It is worth noting that I faced this problem when developing on my local machine, where the table would remain empty even though the json file is not, but it was fixed when I used the Live Server extension on VSCode. However, I don't understand if this is the problem how is it that there is no server to pass the json file on when all my web interface files are correctly passed and loaded from the SPIFFS.
I will include a portion of my code, and of course all help is appreciated.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>
#include<FS.h>   // Include the SPIFFS library
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ArduinoJson.h>

ESP8266WiFiMulti wifiMulti;     // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'

ESP8266WebServer server(80);    // Create a webserver object that listens for HTTP request on port 80

String getContentType(String filename); // convert the file extension to the MIME type
bool handleFileRead(String path);       // send the right file to the client (if it exists)

// Declaring a variable to hold JSON object size
//const size_t capacity = JSON_OBJECT_SIZE(10);

// Creating a JSON document to hold signal entry
//DynamicJsonDocument doc(capacity);

// Declaring array size
const size_t array_capacity = JSON_ARRAY_SIZE(16) + JSON_OBJECT_SIZE(1) + 16*JSON_OBJECT_SIZE(9);

// Creating a JSON document to hold all signal entries in a nested array
DynamicJsonDocument array_doc(array_capacity);

// Creating a nested JSON array to hold all signal entries
JsonArray signals = array_doc.createNestedArray("signals");

// Declaring a JSON object to hold single signal entry
JsonObject signal_entry;

// Declaring method that save JSON object to JSON file stored on SPIFFS
void saveJSON();

// Declaring method that prints JSON file stored on SPIFFS
void printJSON();

void setup(void){
  Serial.begin(115200);         // Start the Serial communication to send messages to the computer
  delay(10);
  Serial.println('\n');

  Serial.println("Connecting ...");
  int i = 0;
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }

SPIFFS.begin();                           // Start the SPI Flash Files System

  server.begin();                           // Actually start the server
  Serial.println("HTTP server started");

  server.onNotFound([]() {                              // If the client requests any URI
    if (!handleFileRead(server.uri()))                  // send it if it exists
      server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error
  });

void loop(void){
  server.handleClient();                    // Listen for HTTP requests from clients

//Creating a JSON object from the JSON document
    signal_entry = signals.createNestedObject();

    //Assigning correct values to keys in JSON object
    signal_entry["date"] = currentDate;
    signal_entry["protocol_type"] = protocol_type;
    signal_entry["bitNr_device"] = bitNr_device;
    signal_entry["bitNr_op"] = bitNr_op;
    signal_entry["codeDec_device"] = codeDec_device;
    signal_entry["codeDec_op"] = codeDec_op;
    signal_entry["codeHex_device"] = codeHex_device;
    signal_entry["codeHex_op"] = codeHex_op;
    signal_entry["codeBin_device"] = codeBin_device;
    signal_entry["codeBin_op"] = codeBin_op;

    serializeJsonPretty(signal_entry, Serial);
    Serial.println("");

    saveJSON();
   }
}

String getContentType(String filename) { // convert the file extension to the MIME type
  if (filename.endsWith(".html")) return "text/html";
  else if (filename.endsWith(".css")) return "text/css";
  else if (filename.endsWith(".js")) return "application/javascript";
  else if (filename.endsWith(".ico")) return "image/x-icon";
  return "text/plain";
}

bool handleFileRead(String path) { // send the right file to the client (if it exists)
  Serial.println("handleFileRead: " + path);
  if (path.endsWith("/")) path += "index.html";         // If a folder is requested, send the index file
  String contentType = getContentType(path);            // Get the MIME type
  if (SPIFFS.exists(path)) {                            // If the file exists
    File file = SPIFFS.open(path, "r");                 // Open it
    size_t sent = server.streamFile(file, contentType); // And send it to the client
    file.close();                                       // Then close the file again
    return true;
  }
  Serial.println("\tFile Not Found");
  return false;                                         // If the file doesn't exist, return false
}

void saveJSON(){
  File jsonFile = SPIFFS.open("signals.json", "w");
  if (serializeJsonPretty(array_doc, jsonFile) == 0) {
    Serial.println("Failed to write to file");
  }
  jsonFile.close();
}

void printJSON(){
  uint8_t* pBuffer;
  File testFile = SPIFFS.open("signals.json", "r");
  if(testFile){
    unsigned int fileSize = testFile.size();
    pBuffer = (uint8_t*)malloc(fileSize + 1);
    testFile.read(pBuffer, fileSize);
    pBuffer[fileSize] = '\0';
    Serial.println((char*)pBuffer);                // Print the file to the serial monitor.
    testFile.close();
  }
  else{
    Serial.println("Failed to read to file");
  }
  free(pBuffer);
}

I think you messed your copying and pasting up. Your loop() function seems to be in the middle of your setup() function.

It sound like you are running the webpage on you PC, but getting the json from the ESP. Browsers don't like that, as it's some form of cross-site scripting. It can work if the ESP also sends the correct permission headers. Access-Control-Allow-Origin: * to be specific. You also might want to open the developer console in your browser to see if any errors pop up. Also check the network tab to see if the json gets requested.

@Gerben I am not quite sure I understand what you mean, my web page is hosted on the ESP and I access it via the IP address, however, in the JS file linked to my HTML (Both stored on SPIFFS btw) I look for the json file in the same folder as my web page, is this the problem?   And I checked the dev tools, yes the json file is requested and the request has a status 200 OK.

Never mind. The VSCode extension part threw me of, but apparently that's not the issue here.

Besides the somewhat strange problem of loop() being nested inside setup() (which I will put down to a copy-and-paste error) I think your main problem is that of a lack of content-type.
The function getContentType() is supposed to guess the content type by the filename extension. However there is nothing there to handle a .json file. So it will just default to text/plain - which won't be interpreted as JSON data.
You need to add a bit in there to look for JSON files and set the content-type accordingly:
...
} else if (filename.endsWith(".json")) {
    return "application/json";
}

I tried it, but sadly this was not it. In the browser dev tools, the json file is requested and the request is accepted, however, the table remains empty even though the json file is not.

Then there is something wrong with your website code.

try coping the response and manually parsing it with JSON.parse().


text:
HC-05 will NOT pair in Master mode (AT+ROLE=1). Same module will pair in slave mode (AT+ROLE=0)
I have a HC-05 Bluetooth module Version (+VERSION:2.0-20100601).
I am using Linux Mint Rosa on an Acer laptop
Section 1 - How it's wired
Wiring
HC-05       Arduino
VCC         5V
GND         GND
TX          pin 1
RX          GND via voltage divider (GND to 2k resistor{2k to HC-05 RX and a 1k resistor} 1k to pin 0)

Section 2 - Sequence to get into AT command state
The sequence I use to get the BT module in AT command state

Unplug the Arduino Uno
Unplug both the RX and TX
Press the button on the HC-05
Plug in the Arduino
HC-05 LED flashes 1 time every 2 seconds
Initialize com ports via Linux terminal - sudo chmod 0777 /dev/ttyACM*
Upload an empty sketch
Plug in the HC-05 RX to Arduino pin 0, and TX to pin 1
Open the Serial monitor
Set Both NL & CR  and 38400 baud

Section 3 - AT commands issued
I use the following AT commands with the noted results.
AT                                  > OK
AT+ORGL                             > OK
AT+RMAAD                            > OK
AT+VERSION  +VERSION:2.0-20100601   > OK
AT+ADDR     +ADDR:98d3:b1:fd85b0    > OK
AT+NAME=Master1                     > OK
AT+UART  +UART:38400,0,0            > OK
AT+ROLE  +ROLE:0                    > OK

NOTE:HC-05 is set to slave and it will pair (see Section 4 below)
THE PROBLEM IS AFTER PAIRING, I RETURN TO AT COMMAND MODE (Section 2) and SET ROLE=1 (Section 5) BUT IT WILL NOT PAIR IN MASTER MODE.
Section 4 - Pairing
I do the following to pair the HC-05 to my phone

Unplug the Arduino
Plug the Arduino back in
HC-05 LED flashes quickly blink/blink/blink
Android phone>settings>connections>Bluetooth>Scan
1 device found > Master1 > pair 1234
Android app > Serial BT terminal>device>Master1>connected
Once Android app connects:
HC-05 LED flashes blink/blink 2 seconds then blink/blink
Remove the RX and TX cables from Arduino and put a jumper to connect HC-05 TX to RX (loopback)
Serial BT terminal>hello>send
Output both green and blue - which means the data was sent via RX and returned via TX.

Section 5 - change ROLE=0 (slave) to ROLE=1 (Master)
I then follow the same sequence that I used previously in Section 2 to return to AT command state.
Issue the following AT commands
AT                      > OK
AT+ROLE  +ROLE:0        > OK
AT+ROLE=1               > OK

Since I changed the configuration I unpair the device on my phone.
I then follow the same sequence that I previously used in Section 4 to pair the HC-05 to my phone

HC-05 LED flashes quickly blink/blink/blink
Android phone>settings>connections>Bluetooth>Scan - CAN'T FIND THE DEVICE.

If I return to AT Command mode and change AT+ROLE=0 it will Pair.
In Master mode:

I tried to swap the TX and RX pins - won't pair.
I tried to pair with the TX and RX removed from the Arduino - won't pair.
I tried NOT UNpairing the device on the phone but it won't communicate with it via the android app once I change it to Master (Section 5).
As I mentioned above if I return to AT Command mode and change AT+ROLE=0 it will Pair.

Lastly I have 2 other HC-05 modules and they all fail to pair when set to Master mode, so I'm thinking I'm missing something but can't figure out what it is.
I would appreciate hearing from anyone with the same problem and anyone who can determine what I'm doing incorrectly.

You might have already solved your problem, but I just wanted to say that a HC-05 Blueooth module will only connect to a phone when it is in slave mode. The phone acts like a master, and therefore, it can't connect to another master.

I observed that these device do very well in slave more, however, in Master mode, they only connect to themselves ( I mean other HC-05).
I have sevceral slave devices ( gamepads, GPS modules, ...)  that never get connected, thoug the HC-05 sees them through the INQ  command, & accurately returns their address, class, signal force, and their name even.
Though, I never succeeded to pair them !!
As if they were designed to be used together and never tested with other slave devices !!?

Not an answer...


text:
How to use LCD display HD44780 with arduino without using any library
My professor wants me to implement a display to an old project prototype we had laying around on the lab.
But he wants me NOT to use LiquidCrystal.h library or any other to achieve that.
I read HD44780 datasheet and tried lots of tweaking and hacking stuff to finally write my name "AUGUSTO" on the screen. The problem is: "lots of tweaking and hacking stuff" which turns my code into trash and kind of impossible to implement it on other project. Eg: when I accidentally short circuit arduino, display "freezes" emtpty and does not work anymore so I have to upload a generic LiquidCrystal.h example code in order to "reset" the whole thing.
My code:
/*
 * Driving LCD Display without library
 * Augusto
 */

//PINS(RS to D7): (2,3,4,6,7,8,9,10,11,12,13);

// WRITE HITACHI (datasheet)

/*
 *     RS RW D7 D6 D5 D4 D3 D2 D1 D0
 * 2.  0  0  0  0  1  1  0  0  *  * -> Function set
 * 3.  0  0  0  0  0  0  1  1  1  0 -> Display ON/OFF control
 * 4.  0  0  0  0  0  0  0  1  1  0 -> Entry Mode set (INCREMENT)
 * 5.  1  0  0  1  0  0  1  0  0  0 -> H
 * 6.  1  0  0  1  0  0  1  0  0  1 -> I
 * 7.  ...
 * 8.  1  0  0  1  0  0  1  0  0  1 -> I (HITACHI)
 * 9.  0  0  0  0  0  0  0  1  1  1 -> Entry Mode set (INCREMENT) - Display Shift
 * 10. 1  0  0  0  1  0  0  0  0  0 -> Escreve um espaco
 *
 */

/*  0000 0000 01 LIMPA
    0000 0000 1— RETORNA HOME
    0000 0 0 0 1 I/D S ENTRY MODE SET
    000 0 0 0 1 DCB SETS ENTIRE DISPLAY ON/OFF
*/

/*
 *  Instruction RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 Description fOSC is 270 kHz)
                1  0                                   Write data Writes data into DDRAM or

                1  1                                   Read data Reads data from DDRAM or

    I/D = 1: Increment
    I/D = 0: Decrement
    S = 1: Accompanies display shift
    S/C = 1: Display shift
    S/C = 0: Cursor move
    R/L = 1: Shift to the right
    R/L = 0: Shift to the left
    DL = 1: 8 bits, DL = 0: 4 bits
    N = 1: 2 lines, N = 0: 1 line
    F = 1: 5 × 10 dots, F = 0: 5 × 8 dots
    BF = 1: Internally operating
    BF = 0: Instructions acceptable

*/

#define RS 2
#define RW 3
#define E 4
#define DB0 6
#define DB1 7
#define DB2 8
#define DB3 9
#define DB4 10
#define DB5 11
#define DB6 12
#define DB7 13

void setup() {

    for (int i = 2; i <= 4; i++) {
        pinMode(i, OUTPUT);
    }

    for (int i = 6; i <= 13; i++) {
        pinMode(i, OUTPUT);
    }

    digitalWrite(E, 0);
    returnHome();
    delay(100);
    limpa();
    delay(100);
}

void loop() {

    functionSet();
    displayOnOff();
    entryModeSet(HIGH, LOW);
    //A
    escreve(1, 0, 0, 1, 0, 0, 0, 0, 0, 1); //Writes A
    //piscaE();
    //U
    escreve(1, 0, 0, 1, 0, 1, 0, 1, 0, 1); //Writes U and so on...
    //G
    escreve(1, 0, 0, 1, 0, 0, 0, 1, 1, 1);
    //U
    escreve(1, 0, 0, 1, 0, 1, 0, 1, 0, 1);
    //S
    escreve(1, 0, 0, 1, 0, 1, 0, 0, 1, 1);
    //T
    escreve(1, 0, 0, 1, 0, 1, 0, 1, 0, 0);
    //O
    escreve(1, 0, 0, 1, 0, 0, 1, 1, 1, 1);
    piscaE();

    entryModeSet(HIGH, HIGH);

    //escreveEspaco();

    while(1) {} //infinite loop to "stop" void loop()

}

void escreve(int rs, int rw, int db7, int db6, int db5, int db4, int db3, int db2, int db1, int db0) { // Function to WRITE something on the display

    piscaE();
    digitalWrite(RS, rs);
    digitalWrite(RW, rw);
    digitalWrite(DB7, db7);
    digitalWrite(DB6, db6);
    digitalWrite(DB5, db5);
    digitalWrite(DB4, db4);
    digitalWrite(DB3, db3);
    digitalWrite(DB2, db2);
    digitalWrite(DB1, db1);
    digitalWrite(DB0, db0);
    //piscaE();
    delay(10);

}

void escreve(int db7, int db6, int db5, int db4, int db3, int db2, int db1, int db0) {
    digitalWrite(RS, HIGH);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, db7);
    digitalWrite(DB6, db6);
    digitalWrite(DB5, db5);
    digitalWrite(DB4, db4);
    digitalWrite(DB3, db3);
    digitalWrite(DB2, db2);
    digitalWrite(DB1, db1);
    digitalWrite(DB0, db0);
}

void piscaE() { //Function to blink ENABLE pin

    // NOT shure how enable pin works
    digitalWrite(E, 1);
    delay(11);
    digitalWrite(E, 0);
}

void limpa() { //Function to clear display
    piscaE();
    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);
    digitalWrite(DB1, LOW);
    digitalWrite(DB0, HIGH);
    returnHome();
}

void entryModeSet(int id, int s) {

    //0 0 0 0 0 0 0 1 I/D S   -   ENTRY MODE SET

    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, HIGH);
    digitalWrite(DB1, id);
    digitalWrite(DB0, s);
}

void functionSet() {
    // 0  0  0  0  1  1  0  0  *  * -> Function set

    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, HIGH);
    digitalWrite(DB4, HIGH);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);

}

void displayOnOff() {
    //0  0  0  0  0  0  1  1  1  0 -> Display ON/OFF control

    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, HIGH);
    digitalWrite(DB2, HIGH);
    digitalWrite(DB1, HIGH);
    digitalWrite(DB0, LOW);
}

void escreveEspaco() { //Function to write a space
    //1  0  0  0  1  0  0  0  0  0 -> Writes a space
    piscaE();
    digitalWrite(RS, HIGH);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, HIGH);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);
    digitalWrite(DB1, LOW);
    digitalWrite(DB0, LOW);
    piscaE();
}

void escreveEspaco(int quant) { //Function to write a specific number of spaces
    //1  0  0  0  1  0  0  0  0  0 -> Writes a space

    for (int i = 1; i <= quant; i++) {
        piscaE();
        digitalWrite(RS, HIGH);
        digitalWrite(RW, LOW);
        digitalWrite(DB7, LOW);
        digitalWrite(DB6, LOW);
        digitalWrite(DB5, HIGH);
        digitalWrite(DB4, LOW);
        digitalWrite(DB3, LOW);
        digitalWrite(DB2, LOW);
        digitalWrite(DB1, LOW);
        digitalWrite(DB0, LOW);
        //piscaE();
    }
    piscaE();
}

void returnHome() { //Function to return cursor to adress 0 according to datasheet
    piscaE();
    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);
    digitalWrite(DB1, HIGH);
    digitalWrite(DB0, LOW);
    piscaE();
}

why would you habe to upload LiquidCrystal.h example code? ... LED blink code should also work, if the arduino code gets corrupted

you are not thinking clearly ... you use a function escreve() and you call it like escreve(1, 0, 0, 1, 0, 0, 0, 0, 0, 1);, which is the proper way to reuse code .... but then you go on to define pointless functions such as returnHome() and escreveEspaco(), which do the same thing as escreve()

I'm not used to work with bytes or pointers and that's why I said this code is totally messed up because of "lots of tweaking and hacking stuff" like writing a function to write something and another function to write a SPACE instead of creating a variable to then split it or so.

start by reducing the code ... for instance, escreveEspaco() is same as escreve(1, 0, 0, 0, 1, 0, 0, 0, 0, 0); ... work with bytes is no different than work with integers... a byte is just a number ... it is like saying not used to working with numbers that are less than 256


text:
pin numbering for non-standard chips
so i replaced the mainboard in (what was) an anet a8 3d printer with a proper RAMPS setup. there was nothing wrong with it, (or at least it wasnt damaged, there are a number of severe design flaws) so i thought it might be a good start point for a remote controlled crawler/bot thing. it already has four a4988 drivers on board, plus a few mosfets and other bits which will be great for accessories (planning headlights, horn, maybe light sensor). its built around the atmega1284p, which is something of an oddball inbetween the 328 on the uno and the 2560 on the mega, but is the same product line. ive already worked out the libraries/drivers for the ch340 or whatever it is that is needed to flash code to the board,it already has already been added to the arduino ide, i have successfully flashed sketches to it before, but not my own. what im wondering is how to declare pins when im writing my own code. the bottom right of this schematic lists connections to the main chip, is it reasonably safe to assume that the digital pin numbers listed there can be used like the normally labeled headers on a standard board? how exactly are those numbers determined?

Does this answer your question? Adding a custom board to the Arduino IDE

example https://github.com/jandrassy/my_boards

Each chip uses the normal register names (like PORTB or DDRA) with the bits representing a pin. The pin numbers, that you know from other Arduinos are just referencing to them. The numbers are defined in the core for the used chip. So when you are installing the core for the used chip inside the Arduino IDE, that core also defines the pin numbers.

@Juraj a custom board file has already been made by someone, it sounds like i need to dig through those core files to find where things get enumerated or whatever the word is

not much digging. it is the variants folder. in my_boards I have a custom 1284p too

Look for a file named pins_arduino.h.

ok so what ive found is that pins are declared in a file, pins_arduino.h. for each board/chip/variant another file is added(or created, if writing your own) to the arduino hardware files. in my specific case the numbers in the graphic are consistent with those listed in the hardware file, so im good