text:
Arduino bluetooth HC-05 servo control
I am using HC-05 Bluetooth module to control two servos. I use Bluetooth terminal in my android phone to control them.
Problem is that myServo1 is moving like I want but I can't control myServo2. Code is reading the variable a but it can't read variable b.
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myServo1;
Servo myServo2;
int servo;
SoftwareSerial BT(2, 3);
void setup()
{
myServo1.attach(11);
myServo2.attach(10);
servo = 90;

Serial.begin(9600);
BT.begin(9600);
}
char a;
char b;
void loop()
{
 if (BT.available())
{
a=(BT.read());
b = (BT.read());
if (a=='1')
{
  myServo1.write(180);
  delay(50);

}
if (a=='2')
{
  myServo1.write(-180);
  delay(50);

 }
  if (b=='3')
{
  myServo2.write(90);
  delay(50);

}
  if (b=='4')
{
  myServo2.write(-90);
  delay(50);

}
}
}

Where is the problem?

your sketch has no debugging code .... why are you not printing the values of a and b to the serial monitor?

When using
if(BT.available())

that's doing the same as
if(BT.available() > 0)

But then you are reading 2 bytes, though you cannot be sure, that there are 2 bytes to read. The data is transmitted serially, so even when you send it on your phone in one bunch, it does not get transmitted as bunch.
Try to use
if(BT.available() >= 2)

Also makes sure, that nothing else gets send over serial besides the numbers (often there is a line ending send implicitly depending on the used app).

If I use the " if(BT.available() >= 2) " it will mix the whole system

What do you mean by that? @engineerstudent

It does not work properly. If I put "1", "2", "3" or "4" it turns one servo randomly. In some cases it doesn't work at all

Then you also have another problem. Have you confirmed, that the comminication with the HC-05 works correctly? You can do this by using a testsketch, where you forward the received data from bluetooth to the serial monitor. If everything is transmitted correctly, we can rule out that part

I don't think that there is problem in the connection because if I use "BT.available()>0" and I type "1" or "2" then it work properly and turns the myServo1 between 180 and -180.

My proposed solution should not result in the observed errating behavior. It just waits for 2 bytes to be actually available, before you read them. Thus I think, that there is something else wrong. Do you really don't send any line ending? That would explain the behavior

When it send the value then I press enter. Would that cause the error? If so how I fix that.

Let us continue this discussion in chat.


text:
Sending MIDI CC to multiple midi Channel
Hi so i would like to send CC messages to different MIDI Channel (volume control). The CC messages are coming from one knob.
The solution i found kind of work but i'm pretty sure is not ideal and seems to introduce drift or lag: the volume isn't getting the same value from one channel to another.
My question is: is there a better way to do it than what i have done.
I use and tweak the following exemple provided in the Teensy Exemple library "USB MIDI AnalogControlChange Example"
The exemple was using this line of code to send CC (controlChange) to a specific channel:
MIDI.sendControlChange(controlNumber, controlValue, channel);
As i wanted to have multiple target channels for the third parameter i tried things like this:
MIDI.sendControlChange(controlNumber, controlValue, 1-2-3);
or
MIDI.sendControlChange(controlNumber, controlValue, (1,2,3));
or
MIDI.sendControlChange(controlNumber, controlValue, 1+2+3);
But it didn't worked. I didn't find in the documentation if this parameter could accept more than one number.
What worked is to multiply analog read of the same knob and multiply the sent message. It's not elegant (i'm new to programing of course) but also i noticed i strange latency or drift if you will: the volume of the channel did went from 0 to full volume but the one on channel 2 didn't go to zero, so the purpose failed. The idea here is to have all the midi channels (1 to 8) but the 11 to be affected by the volume knob.
Hope you can help, in advance, thanks
    /* USB MIDI AnalogControlChange Example

   You must select MIDI from the "Tools > USB Type" menu
   http://www.pjrc.com/teensy/td_midi.html

   This example code is in the public domain.
*/

#include <Bounce.h>

// the MIDI channel number to send messages
const int channel = 11;

// the MIDI continuous controller for each analog input
const int controllerA9 = 1; // param 1
const int controllerA8 = 2; // param 2
const int controllerA7 = 3; // cutoff
const int controllerA6 = 4; // reso
const int controllerA5 = 16; // volume (for channel 11)
const int controllerA4 = 16; // volume (for other channels exept 11

void setup() {

}

// store previously sent values, to detect changes
int previousA9 = -1;
int previousA8 = -1;
int previousA7 = -1;
int previousA6 = -1;
int previousA5 = -1;
int previousA4 = -1;

elapsedMillis msec = 0;

void loop() {
  // only check the analog inputs 50 times per second,
  // to prevent a flood of MIDI messages
  if (msec >= 20) {
    msec = 0;
    int n0 = analogRead(A9) / 8;
    int n1 = analogRead(A8) / 8;
    int n2 = analogRead(A7) / 8;
    int n3 = analogRead(A6) / 8;
    int n4 = analogRead(A5) / 8;
    int n5 = analogRead(A4) / 8;
    int n6 = analogRead(A4) / 8; //i duplicated this to be able to have a different channel target
    // only transmit MIDI messages if analog input changed
    if (n0 != previousA9) {
      usbMIDI.sendControlChange(controllerA9, n0, channel);
      previousA9 = n0;
    }
    if (n1 != previousA8) {
      usbMIDI.sendControlChange(controllerA8, n1, channel);
      previousA8 = n1;
    }
    if (n2 != previousA7) {
      usbMIDI.sendControlChange(controllerA7, n2, channel);
      previousA7 = n2;
    }
    if (n3 != previousA6) {
      usbMIDI.sendControlChange(controllerA6, n3, channel);
      previousA6 = n3;
    }
    if (n4 != previousA5) {
      usbMIDI.sendControlChange(controllerA5, n4, channel);
      previousA5 = n4;
    }

    if (n5 != previousA4) {
      usbMIDI.sendControlChange(controllerA4, n5, 1);
      previousA4 = n5;
    } // 1 here is the channel who's different from the int channel = 11

     if (n6 != previousA4) {
      usbMIDI.sendControlChange(controllerA4, n6, 2);
      previousA4 = n6;
    } // 2 here is the channel who's different from the int channel = 11

  }

  // MIDI Controllers should discard incoming MIDI messages.
  // http://forum.pjrc.com/threads/24179-Teensy-3-Ableton-Analog-CC-causes-midi-crash
  while (usbMIDI.read()) {
    // ignore incoming messages
  }
}

A single CC message applies to a single channel. If you want to affect multiple channels, you have to send multiple messages:
usbMIDI.sendControlChange(controllerAx, nx, 0);
usbMIDI.sendControlChange(controllerAx, nx, 1);
usbMIDI.sendControlChange(controllerAx, nx, 2);
usbMIDI.sendControlChange(controllerAx, nx, 3);
...

And this should of course be done in a loop:
for (int c = 0; c < 16; c++)
    if (c != 10)
        usbMIDI.sendControlChange(controllerAx, nx, c);

Thanks a lot for your answer.
I'll try both of your solution.
On your loop exemple C is getting all the channel between 0 to 16 except the channel 10 right ?

Thanks again, it behave as expected like that:
  `if (n5 != previousA4) {
          for (int c = 1; c < 8; c++){
              usbMIDI.sendControlChange(controllerA4, n5, c);
            }
          previousA4 = n5;
        }`

source: Stack Exchange

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

sort: votes


text:
ESP8266, I am trying to establish a SoftAP and I cant seem to get the WiFilocalIP function to give me my IP
I am just trying to establish a server and it seems that I can't get the serial monitor to read the local IP of my device and my Client can't establish a connection to update the sensor value. when I run the monitor I get this:
IP Address: (IP unset)
here is my code:
    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>

    /// Config parameters for Access Point
    char * ssid_ap = "This Little Buddy";
    char * password_ap = "guessing";
    IPAddress local_ip(192,168,4,4);
    IPAddress gateway(192,168,4,1);
    IPAddress subnet(255,255,255,0);

    //Setup Server Object
    ESP8266WebServer server;

    //Sensors and what not here
    float sensor_value = 0.0;

    void setup() {
        //identify and start WiFi
      WiFi.mode(WIFI_AP);
      WiFi.softAPConfig(local_ip, gateway, subnet);
      WiFi.softAP(ssid_ap, password_ap);
      //sanity check
      Serial.begin(115200);
      Serial.println();
      Serial.print("IP Address: "); Serial.println(WiFi.localIP());
      //Configure the server's routes
      server.on("/", handleIndex); //using top root path for last sensor value
      server.on("/update", handleUpdate); //use this to update sensor value
      server.begin();
    }

    void loop() {
      // put your main code here, to run repeatedly:
    server.handleClient();
    }

    void handleIndex(){
      server.send(200, "text/plain", String(sensor_value));//need to refresh page to get information
    }

    void handleUpdate(){
      //value is passed by an URL argument
      sensor_value = server.arg("value").toFloat();
      Serial.println(sensor_value);
      server.send(200,"text/plain", "Updated");
    }

You should be using WiFi.softAPIP(); to get the AP IP address.

Ya I know this but I am still not getting a reponse from my client. this line isnt becoming true on the client.
Serial.println("Response: ");
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);

Have you tried just running the WiFiAccessPoint example?

Comment // WiFi.mode(WIFI_AP); You dont need it with softAP

The WiFi.localIP() is a function of the STA. To print the IP address of the SoftAP, use WiFi.softAPIP().

this is the answer to the question, code and output in the question. if you want to ask why the client can't connect, ask with the code and output of the client

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


text:
ESP-01 Programming
I have had so many problems with this board.  I have a detailed list of everything I've tried at the link below, but for simplicity I will just summarize where I am now:
https://forum.arduino.cc/index.php?topic=673618.new
What I am trying to do
I want to connect my Arduino Nano to the internet using an ESP8266 ESP-01.  Links to board references below:
Arduino Nano:
https://128217-368301-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2017/06/NSE-1004-2_7.jpg
ESP01:

My Arduino is a clone.  Here is the exact model:
https://www.amazon.com/Longruner-ATmega328P-Controller-Module-Arduino/dp/B01MSYWE6B/ref=sr_1_7?dchild=1&keywords=arduinonano&qid=1585358071&sr=8-7
I have a server running on my network that will take two types of requests from these Arduinos.  One Arduino/ESP pair will send data from sensors to the server, another pair will take that data from the server.  These are dedicated processes.  The sender will never receive and the receiver will never send.
Circuit
Three devices are at play: Arduino Nano (AN), ESP, and External Power Supply (EXPWS)
ESP:
VCC   -> 3.3v EXPWS
GND   -> GND  EXPWS
CH_PD -> 3.3v EXPWS
RX -> RX AN*
TX -> TX AN*
GPIO0 -> 3.3v EXPWS*
RESET -> 3.3v EXPWS*
Arduino
GND -> GND EXPWS
GND -> Reset AN*

I have tested various configurations of these.  GPIO0 to ground, Reset of ESP to nothing, inverting RX and TX depending on what I am doing, etc.  GND to Reset on the Arduino is when I try to upload to the ESP using the Arduino as a USB TTL converter.  More on that later.

Where I am
I have been able to communicate with the ESP using the Arduino IDE via AT commands in the Serial monitor.  I have connected the ESP to my WiFi network, can ping it from my Mac, and have set the default baud rate to 9600.
Things I cannot do
I cannot access AT commands when this sketch is uploaded to the Arduino:
void setup() {
  Serial.begin(9600);

}

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

}

But I can access AT commands with the following two:
void setup() {
  // put your setup code here, to run once:

}

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

}

and
void setup() {
  int i = 0;

}

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

}

This tells me that trying to use Serial commands is causing a problem.  I considered trying to work the ESP by sending AT commands via Serial communications, but, as per my description above, I received no responses from the ESP.
I also cannot use libraries intended for the ESP, namely WiFiEsp.  I receive the error:
[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] No tag found
WiFi shield not present

When I run any example sketches provided by the library (even when I change parameters such as baud rate and adding delay statements to the library code).  Here is a link to that library, you can find the examples there: https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClientRepeating/WebClientRepeating.ino
I also cannot upload sketches directly to the ESP using the Arduino as a USB TTL converter.  I have tried grounding the Arduino reset pin while uploading, grounding it during compiling then pulling that connection when it starts to upload, and doing nothing to the Arduino reset pin.  I have tried different combinations with the GPIO0 pin (ground, vcc, nothing), as well as the other pins.
Conclusion
I am really open to some suggestions here.  The root of the problem seems to be Serial communications - it is the common thread between basic sketches on the Arduino and uploading to the ESP itself.  I have four of these modules and all of them behave the same way.  If I can't get a solution here, I'm going to have to give them back to Satan.

From your connections I guess, you try to use the USB to Serial chip on the Nano to communicate with the ESP directly through the serial monitor. Then it is no wonder, that you cannot communicate that way, when you initialize Serial on the Nano. Keep in mind, that you have 3 devices connected to the same UART interface. That's not good. You may want to try using a SoftwareSerial interface for the ESP and forward data from Serial to SoftwareSerial. Then you can still use Serial for debug messages

Have you tried the WiFiESP library while still having Arduino RX to ESP RX and Arduino TX to ESP TX?

Do yourself a favour and get a 2$ USB TTL converter, flash the esp01 with Arduino software instead of wasting ttime with crutch solutions based on the espressif AT firmware (probably outdated and buggy) Development for this stopped end 2018, Arduino is still active - current 2.6.3. The esp01 is compared to the nano superioir (CPU, flash, connectivity) So in most use cases you can drop the nano

upvote for spending time on your question

First, when you use your Serial for Serial Monitor, you will need another port for communicating with ESP-01, in the case of Nano, since it has only one Serial port, so you will need SoftwareSerial. Secondly, I've been through what you (and many of others) experienced before and have tried WiFiESP, it doesn't work for me and the developer seems stop maintaining the library long ago. I use a library that I fork and fixed some minor bug and modified it  that you can find in my github. It is very stable and use only 11-bytes SRAM.

Wow this was complicated to figure out.  I am able to upload code to the esp, though it doesn't run yet.
Thanks to all who commented, the suggestions did not solve the problem, but they pointed me in the right direction.  Rather than using my Arduino to interface with the ESP01, I switched to a Raspberry Pi so that I could connect it directly to the pins of the computer doing the flashing.  Beyond that, it is still a complicated process, which I will go through here:
Wiring
Format: ESP -> Raspberry Pi
VCC -> 3.3v (I used a breadboard to allow multiple connections)
CH_EN -> 3.3v
GND -> GND
GPIO0 -> GND
TX -> RXD (GPIO 15)
RX -> TXD (GPIO 14)
GPIO0 needs to be connected to GND before you connect VCC to 3.3v.  The purpose of this is so that the chip boots in programming mode.
Uploading
My methodology may be less useful for some, but there is probably something useful here for others.
My Raspberry Pi is headless so I needed to interface with the ESP via command line.  Arduino does not have up to date resources for this, so I tried a couple of my own.

First, I tried Arduino-cli - a package that can be downloaded from GitHub to compile and upload.  I followed the tutorial provided by the video on the page posted below, but Arduino-cli requires you to include the FQBN of the device you are uploading to.  I could not find this for the ESP and my Raspberry Pi did not recognize it on its own, so this was ultimately a dead end for me.

https://www.hackster.io/jithinsanal1610/arduino-cli-c26e6e

esptool.py requires python and can be installed using pip.  I created a virtual environment for the package to keep it separate from the rest of my system.  The tool had trouble compiling sketches, so I used the Arduino Ide on my Mac, exported a compiled binary, and then transferred that to the Raspberry Pi via a smb drive.  Using the command below, I was able to flash the compiled file to my ESP01.
esptool.py --port /dev/ttyS0 write_flash 0x1000 SketchFolder/Sketch.ino.generic.bin

Now here is the important part.  Restart the ESP01 after each flash attempt.  Unplug it from VCC, plug it back in, then upload.  If you upload successfully, then run the exact same command again, it will not upload!  I suspect this may be the same problem I was running into when I was originally using the Arduino Ide. I haven't tested this, but I received a similar message when uploads failed on the Arduino and esptool.py:
Connecting: ----....----....----
Failed to connect

and
Invalid head of packet

These are not copy/pasted error messages, but they should be enough for anyone googling the error.
It is also worth noting that I used an AT command previously to change the default baud rate to 9600.  I specified in the esptool.py command -b 9600.  This did not allow me to upload.  Leave the command alone - the default is 115200 but you don't need to specify it even if you changed the ESP baud rate (though it may be the case that I reset this somehow.  I really don't know enough about the board to say).
Conclusion
There are a lot of bad resources out there for this board.  Frankly, I would have bought a different one had I known.  But it taunted me, and I don't play games.  Good luck to anyone else who tries to work with this board!  I am going to post a new question for my current problem, but for now I would say this one deserves to be marked as solved.


text:
How to split a *char and pass to a function needing uint8_t?
I have a requirement where an event has char *newvalue.
void event(char *newValue) {
//Code here
}

newValue is 2 digits. If it's 1-9 it is " 1" " 2" and 10+ is "10" "11" etc. It also can contain alpha characters as well not just numbers.
I am passing this to a function void function(uint8_t ascii) to display on a single digit display. If I pass newValue it doesn't register less than 10 as it picks up the space.
So what I am trying to achieve is if it's a single character, strip the space somehow into a uint8_t and if it's 2 digits strip just the right digit as a uint_8 and have a bool where I will turn on the decimal point.
I've googled like crazy and can't seem to get something workable. If somebody can help it would be appreciated. If the above is not clear please let me know what more info you need.
The code below, 'value here' is where I want to put the rightmost value from *newvalue.
void onUfcComm2DisplayChange(char *newValue) {
  comdisp.setBrightness(9);
  comdisp.writeDigitAscii(0, 'valuehere');
  comdisp.writeDisplay();
}

void Adafruit_AlphaNum4::writeDigitAscii(uint8_t n, uint8_t a,  boolean d, boolean w) {
  uint16_t font;
  if (w == false) {
    font = pgm_read_word(alphafonttable + a);
  } else {
    font = pgm_read_word(alphafonttableWD + a);
  }
  displaybuffer[n] = font;
  if (d) displaybuffer[n] |= (1 << 14);
}

Please show us the sketch you're using.

C++ function strtok() can be used for spliting a str into a token, as long as there is a delimiter in the str. https://www.cplusplus.com/reference/cstring/strtok/.

Thats where I have been unstuck. there is no delimiter.

I amended the basic code in original post

I'm not real clear on exactly what you want to have there, but here are a few ideas that may help:
If you know what character you want, then just get it.  Like if you always want the second character (I think this is what you need):
void someFunc(char *p)
{
  char secondChar = p[1];
  Serial.print(secondChar);
}

If you just want the last character in the string no matter how long, get the length of it and then pull that character:
void someFunc(char *p)
{
  int len = strlen(p);
  char lastChar = p[len-1];
  Serial.print(lastChar);
}

If you want the last digit in the string no matter how long and no matter how many random characters that aren't digits after it:
void someFunc(char *p)
{
  int len = strlen(p);
  char lastDigitChar = 0;
  // Cycle backwards til we get the first digit
  for(int i=len-1; i>=0; i--){
    if(isDigit(p[i]){
      lastDigitChar = p[i];
      break;
    }
  }
  Serial.print(lastDigitChar);
}

Thanks that is exactly what I was after..... I think I was just trying to overengineer the whole thing and that is just so simple it works perfectly thankyou!


text:
Problem sending GPS coordinates with SMS when requested
I have made a project that sends GPS coordinate but the problem is, when GPRS sends coordinates as 00.0000,00.000. So, I want to know if my code is wrong.
Thank you for your answer.
#include <SoftwareSerial.h>
#include <TinyGPS++.h>

double latitude, longtitude;
char Received_SMS; //Here we store the full received SMS (with phone sending number and date/time) as char
short MSG_OK = -1; //Used later it shows if there's the word "DHT"/"MLX" within the received SMS "-1" means they are not found
String Data_SMS; //Here's the SMS that we gonna send to the phone number, it may contain DHT data or MLX data

TinyGPSPlus gps;
SoftwareSerial mySerial(2, 3); //gps
SoftwareSerial ss2(9, 10); //gprs

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600); //Begin all the communications needed Arduino with PC serial and Arduino with all devices (SIM800L+DHT+MLX)
  ss2.begin(9600);
  Serial.println("GPS Tracking");
  delay(1000);
  Serial.println("Starting ...");
  delay(3000); //Delay to let the module connect to network, can be removed
  ReceiveMode(); //Calling the function that puts the SIM800L moduleon receiving SMS mode
}

void loop() {
  mySerial.listen();
  while (mySerial.available()) {
    gps.encode(mySerial.read());
  }
  if (gps.location.isUpdated()) {
    latitude = gps.location.lat();
    longtitude = gps.location.lng();
  }
  String RSMS;
  ss2.listen();
  while (ss2.available() > 0) { //When SIM800L sends something to the Arduino... problably the SMS received... if something else it's not a problem
    Received_SMS = ss2.read(); //"char Received_SMS" is now containing the full SMS received
    Serial.print(Received_SMS); //Show it on the serial monitor (optional)
    RSMS.concat(Received_SMS); //concatenate "char received_SMS" to RSMS which is "empty"
    MSG_OK = RSMS.indexOf("GET-GPS"); //And this is why we changed from char to String, it's to be able to use this function "indexOf"
  }
  if (MSG_OK != -1) { //If "DHT" word is found within the SMS, it means that DHT_OK have other value than -1 so we can proceed
    Serial.println("found MSG"); //Shows on the serial monitor "found DHT" (optional)
    Data_SMS = ("http://www.google.com/maps/place/" + String(latitude, 6) + "," + String(longtitude, 6));
    Send_Data(); //This function set the sending SMS mode, prepare the phone number to which we gonna send, and send "Data_SMS" String
    ReceiveMode(); //Come back to Receving SMS mode and wait for other SMS
    MSG_OK = -1; //If the DHT is found the variable should be reset to -1 otherwise it will be kept as !=-1 and will send SMS over and over
  }
}

void Serialcom() { //This is used with ReceiveMode function, it's okay to use for tests with Serial monitor
  delay(500);
  while (Serial.available()) {
    ss2.write(Serial.read()); //Forward what Serial received to Software Serial Port
  }
  while (ss2.available()) {
    Serial.write(ss2.read()); //Forward what Software Serial received to Serial Port
  }
}

void ReceiveMode() { //Set the SIM800L Receive mode
  ss2.println("AT"); //If everything is Okay it will show "OK" on the serial monitor
  Serialcom();
  ss2.println("AT+CMGF=1"); // Configuring TEXT mode
  Serialcom();
  ss2.println("AT+CNMI=2,2,0,0,0"); //Configure the SIM800L on how to manage the Received SMS... Check the SIM800L AT commands manual
  Serialcom();
}

void Send_Data() {
  Serial.println("Sending Data..."); //Displays on the serial monitor...Optional
  ss2.print("AT+CMGF=1\r"); //Set the module to SMS mode
  delay(100);
  ss2.print("AT+CMGS=\"+66xxxxxxxxx\"\r"); //Your phone number don't forget to include your country code example +212xxxxxxxxx"
  delay(500);
  ss2.print(" You are here "); //This string is sent as SMS
  delay(500);
  ss2.print(Data_SMS); //This string is sent as SMS
  delay(500);
  ss2.print((char)26);//Required to tell the module that it can send the SMS
  delay(500);
  ss2.println();
  Serial.println("Data Sent.");
  delay(500);
}

if you want an answer, then perhaps you should ask a question

what coordinates is GPS providing?


text:
Serial.println() not working in ISR
Please refer my below code,
const int led_pin = PB5;
const uint16_t t1_load = 0;
const uint16_t t1_comp = 43750;
int blinkcount;

void setup() {
  // put your setup code here, to run once:
  DDRB |= (1<< led_pin);
  TCCR1A = 0;
  //TCCR1B = 0X03;
 TCCR1B |= (1 << CS12);
 TCCR1B &= ~(1 << CS11);
 TCCR1B &= ~(1 << CS10);

  TCNT1 = t1_load;
  OCR1A = t1_comp;

  TIMSK1 = (1 << OCIE1A);
  Serial.begin(9600);
  sei();

}

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

}

ISR(TIMER1_COMPA_vect) {
  TCNT1 = t1_load;
  PORTB ^= (1 << led_pin);
  blinkcount = blinkcount + 1;
  Serial.println(blinkcount);
}

the Serial.println(blinkcount); not working or the serial window does not show up.
Apologies if it sound stupid as I'm new to programming.

please format your code .... you don't print inside ISR .... increment variable and set a second flag variable instead ... check for flag in loop() and print if the flag is set

thank you for support

@jsotola can you please review the changed code and share your suggestion?

ISR are simply not intended for this abuse.
If you want to use Arduino level functions, you must have good reasons why you need to mix them with direct arv-gcc hardware-accessing code (or vice versa).
If you're new to programming and to Arduino, simply ignore that level (for now).
DDRB |= BV(PB5);
is easier understandable if you write
pinMode(13,OUTPUT); ( or even use LED_BUILTIN instead of 13 )

const uint16_t t1_load = 0;
const uint16_t t1_comp = 43750;
int blinkcount;
int flag, flag_1, a, i;

void setup() {
  // put your setup code here, to run once:
  DDRB |= (1<< led_pin);
  TCCR1A = 0;
  //TCCR1B = 0X03;
 TCCR1B |= (1 << CS12);  //for 256 prescalar
 TCCR1B &= ~(1 << CS11);
 TCCR1B &= ~(1 << CS10);

/* TCCR1B &= ~ (1 << CS12);
 TCCR1B |= (1 << CS11);
 TCCR1B &= ~(1 << CS10);*/

  TCNT1 = t1_load;
  OCR1A = t1_comp;

  TIMSK1 = (1 << OCIE1A);
  Serial.begin(9600);
  sei();

}

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

/*  blinkcount = blinkcount + 1;
  if(blinkcount++)
  {
    flag = 1;
  }
  if(flag == 1)
  {
    Serial.println("ok");
  }*/

}

void loop_1()
{
  i = blinkcount;
  //for(i=0; i<=blinkcount; i++);
  //{
  i = i + 1;
  //if(i++)
  // {
    flag = 1;
    flag_1 = flag;
   //}
  if(flag_1 == 1)
  {
    Serial.println(flag_1);
  }
//  }
}

ISR(TIMER1_COMPA_vect) {
  TCNT1 = t1_load;
  PORTB ^= (1 << led_pin);
  //blinkcount = blinkcount + 1;
  //Serial.println(blinkcount);
  loop_1();

}```

I've changed the code according to your suggestion, the tx led on arduino blinks but serial monitor does not pop up

loop_1 is (logically) still part of the ISR. Serial.println() not working in ISR is a fact, not a question.  Don't use ISRs if you don't need OR understand it. In your case both conditions apply. Sorry.


text:
How can I add PWM to my BLDC code using port manipulation?
I have the following code, which currently uses 6 output pins (pins 8 - 13) from the Arduino to my inverter circuit, which controls a BLDC motor. The code is fine and it works, however I want to add PWM using port manipulation and not analogWrite, as this is not fast enough for this application.
I know for example I could write OCR1B = 200, which sets the duty cycle of pin 10 to 200 and replaces the analogWrite function, but I do not know where to put this in my code. Also, do I need 3 PWM pins as the commutation of a BLDC motor is done in 6 steps in order to do 1 full revolution, or do I only need 1 PWM pin?
void setup() {
  pinMode(A0, INPUT); // sensor inputs
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
  DDRB  |= B00111111; // Sets D8, D9, D10, D11, D12 and D13 as OUTPUT
  PORTB &= B11000000; // D8 to D13 LOW
}

void loop() {
  switch (PINC) {
    case 3:
      PORTB |= _BV(PB3); // set pin 11 high
      PORTB |= _BV(PB5); // set pin 13 high
      PORTB &= ~_BV(PB0); //set low
      PORTB &= ~_BV(PB1); //set low
      PORTB &= ~_BV(PB4); //set low
      PORTB &= ~_BV(PB2); //set low
      break;
    case 2:
      PORTB |= _BV(PB3); // set pin 11 high
      PORTB |= _BV(PB4); // set pin 12 high
      PORTB &= ~_BV(PB5); //set low
      PORTB &= ~_BV(PB2); //set low
      PORTB &= ~_BV(PB1); //set low
      PORTB &= ~_BV(PB0); //set low
      break;
    case 6:
      PORTB |= _BV(PB2); // set pin 10 high
      PORTB |= _BV(PB4); // set pin 12 high
      PORTB &= ~_BV(PB0); //set low
      PORTB &= ~_BV(PB1); //set low
      PORTB &= ~_BV(PB3); //set low
      PORTB &= ~_BV(PB5); //set low
      break;
    case 4:
      PORTB |= _BV(PB2); // set pin 10 high
      PORTB |= _BV(PB0); // set pin 8 high
      PORTB &= ~_BV(PB1); //set low
      PORTB &= ~_BV(PB5); //set low
      PORTB &= ~_BV(PD3); //set low
      PORTB &= ~_BV(PD4); //set low
      break;
    case 5:
      PORTB |= _BV(PB1); // set pin 9 high
      PORTB |= _BV(PB0); // set pin 8 high
      PORTB &= ~_BV(PB2); //set low
      PORTB &= ~_BV(PB4); //set low
      PORTB &= ~_BV(PB5); //set low
      PORTB &= ~_BV(PD4); //set low
      break;
    case 1:
      PORTB |= _BV(PB1); // set pin 9 high
      PORTB |= _BV(PB5); // set pin 13 high
      PORTB &= ~_BV(PB0); //set low
      PORTB &= ~_BV(PB4); //set low
      PORTB &= ~_BV(PB3); //set low
      PORTB &= ~_BV(PB2); //set low
      break;
  }
}

Did you manage to solve it?


text:
A problem in l led or arduino nano
When I am working on arduino nano and i uploaded a file that will blink led at 13th pin but rather than at 13th pin l-led is blinking. I even tried resetting it and uploading an empty file and again uploading the 13th pin blinking code but still l-led is blinking. What is the problem?

13th pin is pin12 ... the numbering starts at zero ... the LED is on the 14th pin

The L LED and pin 13 are one and the same thing. That LED is connected directly to pin 13. If you blink pin 13 then that LED will blink.

but the problem is the led that i connected to 13th pin is also not glowing

Did you connect it the right way around? Did you include the required resistor?

yeah i did that and now even the blank code is not uploading


text:
Arduino bluetooth HC-05 data reading problem
I have a problem with bluetooth module HC-05 and servos. If I type in bluetooth terminal 4,1 I want that servo1 turns 60 degrees 3 times. Briefly servo1 turns 60 degrees and then servo2 goes 180 and turns back and again servo1 turns 60 degrees and so on.
The bluetooth mixes the numbers. If I type "1" it gives me "49" and that's why the system is not working properly. How do I fix this data problem?
#include <Servo.h>
#include <SoftwareSerial.h>

Servo myservo1;
Servo myservo2;
long players, cards;
int pos1 = 0;
int pos2 = 0;
int servo;
int pos = 0;
int deal = 0;

SoftwareSerial BT(2,3);

void setup() {
  Serial.begin(9600);
  BT.begin(9600);
  myservo1.attach(10);
  myservo2.attach(11);
  servo = 90;

}

void loop() {
  if(BT.available()>0) {
    players = BT.read();
    cards = BT.read();

    Serial.println(players);
    Serial.print(cards);

    pos = 180/(players-1);
    for(deal = 0; deal < cards; deal++) {
      for (pos1 = 0; pos1 <= 180 ; pos1 += pos ) {
          delay(20);
          myservo1.write(pos1);

          for (pos2=0; pos2<=180 ; pos2 +=1){
            myservo2.write(pos2);
            delay(10);
          }

          for (pos2=180; pos2>=0 ; pos2 -=1){
            myservo2.write(pos2);
            delay(15);
          }

    }
      for (pos1 <= 180; pos1 >= 0; pos1 -=1 ) {
          pos2=0;
          myservo1.write(pos1);
          delay(10);
      }
    }

  }
}

You are mixing ASCII characters and integer values.
The serial data is a pure binary stream, a series of bytes. It is up to the programs on both sides to interpret, how these bytes are meant. When you type 1 into your bluetooth serial app, it already does this. It complies to the ASCII standard, which gives a meaning to every binary value between 0 and 127. Google "ASCII" to get a table of the mapping. Each character (alpha numeric and some special characters and control characters) has a binary value associated with it. That way we can interpret a binary data stream as text.
The ASCII character 1 corresponds to the decimal value 49. You are saving the read byte from the bluetooth serials as long, which is a big integer. So, when you are printing it, you will see the decimal value, which is 49.
What to do now? The easiest way is to subtract the ASCII value of '1' from the received byte:
players = BT.read() - '0';

'0' is the C/C++ representation of a single ASCII encoded character. It's the same as subtracting the decimal value 48, but it's a bit clearer to see, what happens here. We are shifting the numbers row (0 to 9) from position 48 to position 0. That way the ASCII '0' is transformed to a decimal 0, the ASCII '1' to a decimal 1, and so on up to 9.
Note: You might want to make sure, that only numbers are used for these variables, as the principle will result in garbled data, when the user inputs some other characters. You would need to read the binary data into a temporary variable (here called c) and then check, if they are numeric. Either by hand:
if(c >= '0' && c <= '9')

or by a convinient function
if(isDigit(c))


text:
why this unexpected behaviour shows when i use the following code to send the data from the ultrasonic distance sensor to firebase
I am using nodeMCU esp8266 wifi module to send the data received by the ultrasonic distance sensor to the firebase.
here is my code:
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>

//Firebase settings
#define FIREBASE_HOST "dis3333333333333333aseio.com"
#define FIREBASE_AUTH "Lb21333333333333333333v6HzPatg1HA"

//Wi-Fi settings
#define WIFI_SSID "hello"
#define WIFI_PASSWORD "123456789"

//Define trigger and echo digital pins
const int trigPin = 5;
const int echoPin = 4;

// The amount of time the ultrassonic wave will be travelling for
long duration = 0;
// Define the distance variable
double distance = 0;
double cm=0;
double statusTemp=0;
int temp=0;
unsigned long time_now=0 ;
unsigned long time_prev=0 ;
String stringOne="consump/day";
String stringTwo;

void setup()
{

    Serial.begin(9600);
    // Connect to Wi-Fi
    Serial.print("Wi-Fi...");
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print("Connecting...");
    while (WiFi.status() != WL_CONNECTED)
    {
        Serial.print(".");
        delay(500);
    }
    Serial.println();
    Serial.print("Connected to: ");
    Serial.println(WiFi.localIP());

    Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

    // Ultrasonic sensor, set echo as Input and trigger as Output

}

void loop()
{

    getDistance();
    time_now = millis();

    Serial.print("Distance: ");
    Serial.println(distance);

    delay(500);
}

void getDistance()
{
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    pinMode(echoPin, INPUT);
    Serial.print("Time: ");
    Serial.println(time_now);
    if(statusTemp==0){
      time_prev=time_now;
      statusTemp=1;
      Serial.println("Hello");
    }
    if(statusTemp==1)
    {
      if((time_now - time_prev)> 10000){
        statusTemp=0;
        stringTwo=stringOne+temp;
        Serial.print(stringTwo);
        Firebase.setFloat(stringTwo, distance);
        temp++;
        Serial.print(temp);
      }
        duration = pulseIn(echoPin, HIGH);

        distance = duration * 0.034 / 2;
        Firebase.setFloat("distance", distance);
        if (Firebase.failed()) {
        Serial.print("setting /number failed:");
        Serial.println(Firebase.error());
        return;
    }
 }
}
long microsecondsToCentimeters(long microseconds) {
   return microseconds / 29 / 2;
}

It works totally fine but after some time the below thing appears

Is the following thing happening due to my code or something else is causing this.

Looks like some memory issue (from the descriptions of similar errors found through google). You are using String, which is not good. Read Majenko's blog entry about the Evils of Arduino Strings. Try to use char arrays instead (also called C-Strings). If that works, I will write a full answer.

have you tried the exception decoder? it should tell you the line of code that crashes.


text:
What are the applicable processor for the ATmega32u4? And what are higher versions of ATmega32u4?
Can arduino uno smd r3 version handle a Keyboard.h library?  it is not applicable for that arduino?

It is unclear, what you are asking.  The Arduino Uno cannot use the Keyboard library (unless you are hacking the USB to Serial chip). The Atmega32u4 has a native USB interface, thus it can use the Keyboard library, but the Uno only uses this chip as Serial to USB chip. The main chip is the Atmega328p, which doesn't have native USB

The ATMega32U4 is the ATMega32U4. There are no "higher versions" of it. What are you really asking?

Okay sir. But can arduino mega2560 use the keyboard library?

I am just clarifying if arduino uno can use keyboard library but now I know that it is not so, what type of arduino can you recommend on me sir for me to use the keyboard library?

The Arduino Uno cannot use the Keyboard library. The microcontroller needs to have a native USB interface. The Uno uses the Atmega328p, which does not have one.
You can use the Arduino Micro or Arduino Leonardo for this.

For more experienced hackers: If you need to use the Uno, but still want to use extended USB capabilities (more than USB to Serial), it is possible to reprogram the Atmega32U4 on the Uno, which is only used as USB to Serial adapter chip, but of course has native USB capabilities and could create a HID/Keyboard input on the USB interface. Since that is not a task for beginners, it is not applicable for this question, but should be mentioned for future readers.


text:
Bluetooth module HC05 does not react to bluetooth signal from smartphone
I try to switch off two leds with a hc05 module by sending the signal from my phone.
I know there are a lot of examples on the internet and I tried some of them, but they dont work either. I use a Elegoo Uno R3 and the "Serial Bluetooth Terminal" on my phone. When I try to send a 1 to the HC05 (slave) from my phone it just gives the 1 back, but does not seem to save it in the variable state.
I dont know if the two software serials can be a problem? But when I delete the the Software Serial it still does not work.
Here is my code:
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

SoftwareSerial Bluetooth(8,9); // RX, TX
SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;

void printDetail(uint8_t type, int value);
char state;
void setup()
{
  pinMode(7,OUTPUT);  //LED1
  pinMode(6,OUTPUT);  //LED2
  Bluetooth.begin(9600);
  mySoftwareSerial.begin(9600);
  Serial.begin(9600);

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true){
      delay(0); // Code to compatible with ESP8266 watch dog.
    }
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(30);  //Set volume value. From 0 to 30
}
void loop()
{
  digitalWrite(7,HIGH);
  digitalWrite(6,HIGH);
  static unsigned long timer = millis();
  static unsigned long zeit = 0;

mySoftwareSerial.listen();
  if (millis() - timer > 900000) {
    timer = millis();
    myDFPlayer.next();  //Play next mp3 every 10 minutes
    zeit = millis();
    while(millis()-zeit < 10000){
      digitalWrite(7, !digitalRead(7));  // toggle state
      delay(50);
      digitalWrite(6, !digitalRead(6));
      delay (100);
    }
  }
Bluetooth.listen();
state = Bluetooth.read();
if (state == '1'){
   digitalWrite(6,LOW);
   delay(5000);
  }
}

Your help would be much appreciated.
Best wishes,
CR

You tried to read bluetooth byte right after Bluetooth.listen(), which is probably why you don't receive anything. Instead wait for byte to be available using "while (Bluetooth.available() == 0);"

Thanks for your answer, Fahad, but it still does not work. It appears that the condition Bluetooth.available() == 0 is always right...so it does not get a signal? I can, however, send something from the HC-05 to the phone.

Let's work with a simple example and just test the Bluetooth. Get rid of everything, except Bluetooth SoftwareSerial. If there is one SoftwareSerial you won't even need listen(). In the loop() just check if Bluetooth.available() is greater than zero or not. If is greater, read() and print().

Also listen() clears the SoftwareSerial buffer. Both of your SfotwareSerial uses the same buffer. So if you received anything before calling listen(), it is gone now.

I did that, but the available() is never greater than zero.

When I do: if(Bluetooth.available() ==0) {Bluetooth.write("something")}, it works, but not for read(). SO there is some kind of connection, but the available returns 0. Btw, (I dont know if this means anything) if I write something in the bluetooth terminal on my phone, the same thing comes back (from the hc05?). Like, if I write 1, it returns a 1.

Can you post your new code? Also, provide the link for bluetooth terminal. I have one HC-05. I can test on my end.

#include "Arduino.h"
#include "SoftwareSerial.h"
SoftwareSerial Bluetooth(8,9); // RX, TX
char state;
void setup()
{
pinMode(3,OUTPUT);  //LED
Serial.begin(9600);
Bluetooth.begin(9600);
}
void loop(){
digitalWrite(3,HIGH);
if(Bluetooth.available()){
state = Bluetooth.read();
Serial.println(state);
if (state == '1'){
digitalWrite(3,LOW);
delay(5000);
}
}
}

https://play.google.com/store/apps/details?id=de.kai_morich.serial_bluetooth_terminal&hl=de

It worked as expected. So you might have different issues. If you can, edit your question, and add a connection, how did you connected your module with Arduino. Also, provide a link of the exact module you are using.

I dont know why, but it works now. Fahad, thank you very much for your effort :)


text:
How to subtract micros()?
I am attempting to calculate the time between pulses by comparing the micros() timestamp. I understand that you cannot just simply subtract unsigned longs, but I cannot understand what the alternative for it is.
Below is a simplified version of code. On pin 6 I receive 2ms long pulses every 2ms comparing the times returns "-19728". I'm planning to make the pulses much shorter once I figure out this math problem.
Site note: I'm using pulses to make two Arduinos send simple data via digital pins.
Thanks you.
int pinReceiver = 6;
int val = 0;
int isReceiving = 0;
int pauseLength = 0;
unsigned long timeStart = 0;

void setup() {
  Serial.begin(9600);
  pinMode(pinReceiver,INPUT);
}

void loop() {
  noInterrupts();
  val = digitalRead(pinReceiver);

  if(val==HIGH){
    if(isReceiving==0){ //Pulse begins
      isReceiving = 1;
      pauseLength = micros() - timeStart;
      Serial.println(pauseLength);
    }

  } else {
    if(isReceiving==1){ //Pulse ends
      isReceiving = 0;
      timeStart = micros();
    }
  }
  interrupts();
}

The calculation seems correct. Please try to also use unsigned long for pauseLength. That might be your problem

That definitely solved the problem. I assumed that since the difference would be such a short number it could be int. Thank you. I don't know how to mark this as solving answer.

I think its more about that you mixed unsigned and signed types. Tomorrow I will write an answer, that you can accept

what happens if you cast long to int ? ... pauseLength = (int)(micros() - timeStart);

Long to Integer conversion will overflow the value and you'll get values in negative numbers.
Define the pauseLength as unsigned long to make it work.


text:
Convert JSON into string for MQTT
I am trying to publish json object into string with following snippet
JSONVar data;
data["chipid"] = chipId;
data["co2_equivalent"] = co2_equivalent.c_str();
data["tvoc"] = tvoc.c_str();
data["h2_signal"] = h2_signal;
data["ethanol_signal"] = ethanol_signal;
data["humidity"] = humidity;
data["temperature"] = temperature;
data["absolute_hum"] = v.absolute_hum;
data["co2_equivalent_baseline"] = co2_equivalent_baseline;
data["tvoc_baseline"] = tvoc_baseline;

String data_json = JSON.stringify(data);
Serial.print(data_json);
Serial.println();
client.publish("/devices/data", data_json);

This give me following error during compilation.
  /Users/ubuntu/Desktop/Arduino/data_collection/esp32-svm30-mqtt.ino/esp32-svm30-mqtt.ino.ino: In function 'void loop()':
  esp32-svm30-mqtt.ino:271:46: error: no matching function for call to 'PubSubClient::publish(const char [14], String&)'
       client.publish("/devices/data", data_json);
                                                ^
  In file included from /Users/ubuntu/Desktop/Arduino/data_collection/esp32-svm30-mqtt.ino/esp32-svm30-mqtt.ino.ino:2:0:
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:141:12: note: candidate: boolean PubSubClient::publish(const char*, const char*)
      boolean publish(const char* topic, const char* payload);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:141:12: note:   no known conversion for argument 2 from 'String' to 'const char*'
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:142:12: note: candidate: boolean PubSubClient::publish(const char*, const char*, boolean)
      boolean publish(const char* topic, const char* payload, boolean retained);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:142:12: note:   candidate expects 3 arguments, 2 provided
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:143:12: note: candidate: boolean PubSubClient::publish(const char*, const uint8_t*, unsigned int)
      boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:143:12: note:   candidate expects 3 arguments, 2 provided
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:144:12: note: candidate: boolean PubSubClient::publish(const char*, const uint8_t*, unsigned int, boolean)
      boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:144:12: note:   candidate expects 4 arguments, 2 provided
  Multiple libraries were found for "PubSubClient.h"
   Used: /Users/ubuntu/Documents/Arduino/libraries/PubSubClient
  Multiple libraries were found for "Arduino_JSON.h"
   Used: /Users/ubuntu/Documents/Arduino/libraries/Arduino_JSON
  Multiple libraries were found for "svm30.h"
   Used: /Users/ubuntu/Documents/Arduino/libraries/svm30
  Multiple libraries were found for "Wire.h"
   Used: /Users/ubuntu/Library/Arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/Wire
  Multiple libraries were found for "WiFi.h"
   Used: /Users/ubuntu/Library/Arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/WiFi
   Not used: /Applications/Arduino.app/Contents/Java/libraries/WiFi
  exit status 1
  no matching function for call to 'PubSubClient::publish(const char [14], String&)'

Line Serial.print(data_json) does print it in serial monitor.
Update :
If I doclient.publish("/devices/data", data_json.c_str());, it gets compiled, but data doesn't appear in mqtt.
Serial.print(data_json.length()); prints 236
Is my json to string conversion correct ?

Please note: the question originally had no mention of trying to use c_str() - so I'm not a retard

Point 1 JSON actually is a string
Point 2 your data_json varibale is a String
Point 3 client.publish doesn't work take String as the payload argument, it takes either const char * or const uint8_t *
So, what you can simply do is use Strings c_str method to pas a const char * as the payload
i.e.
client.publish("/devices/data", data_json.c_str());

Point 4 - if you read the pubsubclient documentation, you'll see that

The maximum message size, including header, is 128 bytes by default. This is configurable via MQTT_MAX_PACKET_SIZE in PubSubClient.h. Longer messages can also be sent with the publish_P() method.

so what you may be experiencing now is a message size too big for pubsubclient to handle - set a larger packet size before including the PubSubClientHeader.h
#define MQTT_MAX_PACKET_SIZE 1024
#include <pubsubclient.h>

If that also doesn't work, try
client.publish_P("/devices/data", data_json.c_str());

I tried data_json.c_str() but still data doesn't appear in mqtt.

@roy - but it compiles now?

Yes its getting compiled, but data not getting to mqtt.

@roy - updated the answer with another possible problem - which you have confirmed with your latest update that the payload is over 128 length ... meaning the whole message is WELL over 128

I tried adding #define MQTT_MAX_PACKET_SIZE 1024, still no data appearing in mqtt.

@roy - what if you set a fixed payload? I can't recall if you tried that since you keep editing the question - you did add that define BEFORE you included the header file?

If i just publish fixed data it works like this client.publish("/devices/data", "1234567890");

and now that you've increased the packet size, it still doesn't work? it's odd, because if Serial.print(data_json); prints a string, and the string is far less than 1024, this should've worked - can you Serial.print(MQTT_MAX_PACKET_SIZE); just to be sure

try using client.publish_P("/devices/data", data_json.c_str());

You have almost tried everything and @Jaromanda has given an answer that should possibly work. Can you please try the following things const char *buffer = NULL; //declaring const char * buffer = strdup(data_json.c_str()); //duplicating the string client.publish("/devices/data", buffer); //publish it MQTT


text:
Digital LED clock - matrix circuit question
i'm making a digital clock.
Right now the plan is to matrix them on a atmega328 using transistors.
I figured i need a transistor on both sides or the current would be sinked/sourced by the atmega, which is not what i want.
I'd rather use the MAX7219 but i'm not sure if it's possible to use transistors, because i don't think the MAX7219 can handle the current.
I found the circuits here, i smushed them together, is this correct? Idk.

This is the led segment i'm using, there's four of them. So four 337 transistors, one for each digit. And seven 327 transistors, one for each segment.
I will scan through the four digits and turn on the apropriate segment.

So yea, please let me know if this is totally wacky or something else.
Edit :
I guess this would be 1 digit. Sorry it's confusing to draw the whole matrix. I hope this clears it up. It's just a normal matrixing situation but with more leds.

So normally it goes something like this :
The cathodes of the leds are controlled directly by the atmega, but results in the atmega supplying the current. So my reasoning would be to put a row of transistors there instead, would that be correct?

why are you using two transistors?

Your schematic has two Q1's, which is confusing. Your schematic is not complete or it does not match your description. Please correct it so they match. The BC327 will be connected to the 7 segments and the BC337's to the (common) cathode of each digit, right?

That's my question. Do i need two for each segment? Like i said in my OP, if i would use 1 transistor, the current would be sourced/sinked by the arduino. I need to leds to be powered seperatly.
One of those should then be Q2, forgot to edit that. I can't match it to my description because i'm not sure if it's correct.
It's a led matrix, but instead of individual leds, i need to turn on sets of 2 and 3 leds. The cathodes are controlled by the BC337, the anodes by the BC327.

I think this will work. Why don’t you test this on a breadboard? The value for R1 should be chosen such that the LEDs light up evenly. I would advise you to use different values for the clusters with two and three LEDs, or use one resistor per LED. You should take the (small) voltage drop from the transistors into account and calculate resistors accordingly.

Since each LED is individual, I'm afraid that you can not put them in parallel. They will lit differently due to their own forward voltage. You might like to put them in series.

Since you're using a matrix of anodes and cathodes you need to connect/disconnect both ends of each LED.
You will probably multiplex these LEDs and only light one at a time. Are the LEDs high enough current that you can't either source or sink enough current for a single LED directly from Arduino pins? Most LEDs run on ≤ 20 mA, which an atmega328 can handle.
If you are trying to drive LEDs that need > 20mA then your plan to switch both the +5 and the ground with transistors should work. As StarCat said, you should consider the "on resistance" of your transistors as part of your calculation for the value needed for the current limiting resistors of your LEDs.

Or just use the MAX7219, specifically designed for 7-segment displays.  It has an operating current spec of 330 mA, good for all segments and the decimal point on at the same time.  A four-digit 7-segment display with a total of 32 LEDs allows 10 mA per LED assuming you have everything on at once.
Am I missing something?
Frank


text:
Analog Comparator works on Nano, but not working on Pro Mini 3.3v
I've coded an analog comparator to work on Nano, but the same code does not work on a brand new Pro Mini 3.3v 8MHz. The serial monitor just outputs the triggered interrupt continuously. Lines orange and yellow have the potentiometer.

The code is:
#define INDICATOR_PIN 8

volatile boolean triggered;
volatile boolean rising;
volatile byte acsr_value;

ISR (ANALOG_COMP_vect) {
  if (triggered) return;           // For testing purposes, ignore the interrupt if we haven't reported the last one yet.
                                   // This also effects some crude debouncing.
  cli();
  acsr_value = ACSR;
  rising = (acsr_value & bit(ACO)) > 0;
  triggered = true;
  sei();
}

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

  pinMode(INDICATOR_PIN, OUTPUT);
  digitalWrite(INDICATOR_PIN, LOW);

  ADCSRB = ADCSRB & ! bit(ACME);   // disable Analog Comparator Multiplexer Enable
  ACSR =  bit(ACI)                 // clear Analog Comparator Interrupt Flag
        | bit(ACIE)                // set Analog Comparator Interrupt Enable
        | bit(ACIS1) | bit(ACIS0)  // select rising edge: ACIS1/ACIS0 Analog Comparator Interrupt Mode Select
        ;
}

void loop() {
  if (triggered) show_what_happened();
}

// just give an indication via Serial and LED that we handled an interrupt...
void show_what_happened() {
  digitalWrite(INDICATOR_PIN, HIGH);

  Serial.print ("Triggered! ACSR=");
  Serial.print (acsr_value, BIN);
  if (rising)
    Serial.println (" RISING EDGE (as expected)");
  else
    Serial.println (" FALLING EDGE .. wtf, didn't ask for this, but every so often one slips thru. Maybe a sync issue reading ACSR.");

  triggered = false;

  delay(100);
  digitalWrite(INDICATOR_PIN, LOW);
}

Why does it work well on Nano? I've read all the related sections in the datasheet and tested several ACSR configurations.
I'm seeing the voltage levels changes on a DSO, and it works as expected in the Nano.
I'd like to add that when loading the code to the board, it either prints nothing, or prints continuously RISING FALLING edge. Sometimes, when a connect the serial monitor, it just stops flashing the led. It is definitely an erratic behavior.
What am I doing wrong?

Could you tell us the exact board models/ microcontrollers?

Yes. It's an Arduino Pro Mini 3.3v 8Mhz board. Atmega328p.

Ok, just in case (ISR names and such). Are you using this circuit? Because it sets AIN1 to a reference of 2.5V. Just thnking out loud, but internally in a 3.3v board, that might be too high.

I edited the question with the schematics. I assure you that at first, the level of AIN0 is fewer that AIN1, and then when I move the potentiometer, the level surpass AIN1, moment when I expect it to trigger the interruption, but this does not happen. I'm starting to think that there must be some kind of limitation in the Arduino Pro Mini board.

There's no limitation - the signals go straight from the header pins to the TQFP pins on both boards.  The only difference is AREF - 5V on the Nano, 3.3V on the Promini you are using. What level signal are you sending in, and comparing against?

The level signals will be the same proportion for any AREF. The relevant thing is that I move the potentiometer and AIN0 surpass AIN1, which is happening, I see it in the DSO.

No, that's not what @CrossRoads meant. AIN0 can surpass AIN1, but if the level isn't within 3.3V range, this won't work. Analog comparator works based on the AREF voltage. Nano's AREF is 5v. Pro Mini 3.3v 8Mhz 's AREF is 3.3V. So check the voltage level of AINs.

The FTDI is set to work with 3.3v and is feeding the Pro Mini with this voltage.

Do you have a proper schematic? I can't tell from the image you posted what values of resistors you used.

The circuit next to the FT232 (set to 3.3v) is a voltage devider with a 2 * 10K in series and 3 * 470K in parallel. Midpoint is the reference to D7. The variable reference is a voltage devider between a 10K and a potentiometer that goes from 23K to 150K. The schematic a posted is made with the autoroute of Fritzing, so don't take it as perfect. It's just to give the idea.

Ok, but is your Fritzing image correct? Because it looks like your voltage divider is connected to RXI !! instead of 3.3V.

If your voltage on pin D6 and D7 are really close, you will get trigger continiously. So, check the voltage on those two pins.

The delta range is: minimum 2.32v, average 2.52v and maximum is 3.12v . Please, check in your breadboard that the continuous triggering is because these 200mv downwards and 600mv upwards is not enough delta to keep comparator at ease. I mean, "really close" is not specified in the 328 datasheet, at least, I didn't find it.


text:
Serial Monitor shows random texts While Reading Data from RTC DS3231 with Arduino Uno
I tried to set time on a RTC DS3231. After Uploading it with Arduino IDE, I try viewing the output in the Serial Monitor. However, if I start viewing the Serial Monitor, It starts showing encrypted lines. I have tried the example code and yet it shows the same.
The Setup code
#include <DS3231.h>
DS3231  rtc(SDA, SCL);

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

  rtc.begin();

  rtc.setDOW(SUNDAY);
  rtc.setTime(02, 17, 0);
  rtc.setDate(29, 03, 2020);
}

The loop code
void loop()
{
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  Serial.println(rtc.getTimeStr());

  delay (1000);
}

The output Screen Shot is

change the baud rate in Serial Monitor to match the baud rate set in sketch

Normally, you shouldn't show text as an embedded picture or video. Here everybody can see the wrong baud rate. :) Thanks for registering to StackExchange for this issue.


text:
Can we use ESP32 to program ESP32-CAM through ESP-IDF
Can we just use an ESP32 NodeMCU for example to program an ESP32-CAM? I saw a lot of people programming ESP32-CAM using an arduino Uno, can we do the same for ESP32 NodeMCU? Of course, in the "Arduino as ISP" programming mode.
If we can, is there anything more that I need? if not, why? and are there any other solutions to program it?
Moreover, I want to use ESP-IDF which is better than using the Arduino GUI app.

"Arduino as ISP" is something very different

I really dont even know what to do man. I really need help, sometimes when I power it up (ESP32-CAM) the LED does not even turn on, even if I press the reset button, I am so confused, it only lights up when I give it electricity from the FTDI, I think this board is broken or something...

you can't power an esp32 from FTDI 3.3 V pin. it can't provide enough current

Well, It actually worked fine, the led was flashing, but when I connect IO0 to GND, the flashing stops. If you have any video that explains ESP32-CAM very well, please notify me, it is one of these two: 1. The chip is not genuine. 2. I have a bad understanding about the chip.

it is 2. but please read https://arduino.stackexchange.com/tour

I have discovered how to use the ESP32 NodeMCU as a serial interface. In other words, make the ESP32 traverse ALL of the serial communication to the TX & RX pins directly without any interference. When you press the "RST" (Reset) button, it turns off, but when you release your finger, it will turn on. However, when it is turned off, it traverses all the serial communication to the TX & RX pins, which can then be used to program and contact with the ESP32-CAM. Of course, you can't keep pressing the "RST" button all the time, instead connect the "En" (Enable) pin to GND which will then disable the 3.3 voltage regulator (Same as if you were pressing the "RST" button), in other words, turns the ESP32 off. And then, connect any two GND pins together from both of the ESP32's. At last, upload your program to the ESP32-CAM.

A step by step guide could be found here https://www.instructables.com/Programming-ESP32-CAM-With-ESP8266/

All you need to program any ESP32 (Cam or not) is a serial interface.  How you make that serial interface is up to you.
Most ESP32 development boards have a USB to UART converter on them which you can use just like on an Arduino - keep the ESP32 you're using for the programming in RESET so it doesn't try and respond on the UART.
You could also program the "programmer" ESP32 as a UART passthrough to connect the USB UART through to the other UART so you don't need to mess with holding in RESET.


text:
FTDI Unrecognized USB device
I connected my FTDI (FT232RL) to my PC, windows 8.1. And it gave me a notification saying "USB device not recognized". However, I thought that the problem is from the cable that I am using to connect my FTDI with my PC, I tried another cable, same results. I am trying to program an ESP32-CAM, which has no boot loader, nor a way to connect it directly with the PC. However, I tried to upload the program (from arduino IDE) to the FTDI, It has said "Could not open port COM4", I have concluded that if I can only bypass this error, the upload will work fine with no errors. Windows is preventing any communication with this device, because it has not recognized it yet.
I have tried the following:

I reinstalled the FTDI driver using the '.exe' setup file, and installed many version many times.
I replaced the cable with another cable, because I suspected that the cable had an issue, but it made no difference.
I checked the wiring 10 times, nothing suspicious.
I have also tried to choose the driver manually from the device manager tab and downloaded the driver from the FTDI website, still did not work. There was a guide on how to do the "setting the driver up for the FTDI", I followed it, did not work too, but I followed the "Setting up the driver manually" part, there was a step that was not obvious enough for me, he chose a file that contains the driver, but which file exactly? only god knows.

However, I found some videos on the internet that does not require any driver (Linux sometimes work without any driver). Why is that? Why am I getting this? Why does other people are not getting this error? I saw a lot of people suffering from this FTDI chip. There should be a solution.

does the module use a genuine FTDI chip?

I really don't know, how can I even know if it is genuine or not? I bought it from aliexpress.com, most people gave the seller a good feedback for that product.

If it's from a cheap chinese site then it's probably fake.

check the FTDI site ... they may have a program that you can download and use to identify if your device is genuine

Do you have the product link?

@Fahad , https://www.aliexpress.com/item/32645814447.html?spm=a2g0s.9042311.0.0.27424c4dL473Vv , I think it is genuine, most people gave positive feedback.

It is possible that you just got a bad board. You can use this utility software: https://www.ftdichip.com/Support/Utilities.htm#FT_PROG
to configure FTDI ICs. Give this a try. If this can't detect it, well, you will have to order again.

Alright then, nothing worked out for the FTDI chip, I have concluded that my chip is fried. However, I want to answer this question, but there is not a clear solution. So, I am thinking of closing this question.


text:
How to reduce noise when using a load cell amplifier's 80 Hz mode?
I have four HX711s load cell amplifiers and each one reads one load cell. I was using the 10 Hz mode, however, this was making my application very slow, as I needed to take five readings and take the average.
When I put the 15 RATE in 1 there is a lot of noise, despite having sped up the reading of the weights; sometimes the variation is up to 3 digits at the end.
See the code for reading the modules where I already show the weights in kg:
n = 6;

for (int x=0; x<n; x++) {
  v1[x] = CELL1.read();
  v2[x] = CELL2.read();
  v3[x] = CELL3.read();
  v4[x] = CELL4.read();
}

v1m = 0;
v2m = 0;
v3m = 0;
v4m = 0;

for (int x=1; x<n; x++) { // sum of array
  v1m = v1m+v1[x];
  v2m = v2m+v2[x];
  v3m = v3m+v3[x];
  v4mv= v4m+v4[x];
}

// mean array
v1m = v1m/(n-1);
v2m = v2m/(n-1);
v3m = v3m/(n-1);
v4m = v4m/(n-1);

p1 = p;
p = ((v1m-v10)/(M[1]) + (v2m-v20)/(M[2]) + (v3m-v30)/(M[3]) + (v4m-v40)/(M[4]))/2.5; // show the weight in kg
p = p*o.7+p1*0.3; // convert to kg
// ... i print the p (weight in kg) now...

Please show your complete code, wiring and which deviations you actually get in comparison between 10 and 80SPS setting

I had a very similar problem with 4 load cells.  I ran 10,000+ readings at 80Hz, copied the serial monitor into MS Word to find my string (text) value labels and replace them with nothing. This lets me keep the numbers.  If you copy that into Excel and make a scatter plot graph you can see where your highs and lows are and their magnitudes.  I was able to simply write an IF condition to reject those outliers.  Interestingly the outliers are very large (positive or negative) and they weren't just random values. They were also occurring at a specific frequency that may have more to do with my application rather than being an element to your solution.

Your answer could be made more complete by including the part of your code that does the filtering for outliers, or by describing it in more detail. Did you use some kind of median filter or something different?


text:
Multidimensional array with date and numbers
I would like to create something similar to a multidimensional array.
I would like to get this effect.
setting = [
     0 => [// 0 is the day of the week, but it can be a number
         '1:25' => 25, // key is time. The value is a number (temperature)
         '7:12' => 22,
         '15: 30 '=> 21,
         '18: 00 '=> 23
         '22: 25 '=> 22
     ]
     1 => [
         '1:25' => 25,
         '7:00' => 21,
         '15: 00 '=> 22,
         '18: 00 '=> 25
         '22: 25 '=> 22
     ]
     2 => [
         '1:25' => 25,
         '7:00' => 21,
         '15: 32 '=> 21,
         '18: 40 '=> 25
         '22: 25 '=> 22
     ]
     .
     .
     .
     e.t.c
];

Then I would like to read these values. Days of the week and time are already downloading, but I do not know how to make such a board. I would like to download these values (temperature) to a variable.
Regards

what board are you talking about?

What exactly are you trying to do? It seems like you are suffering from an XY Problem and you're trying to solve a problem that stems from you trying to solve a different problem in the wrong way.

@jsotola Excuse me. I dealt with the project for work and forgot about my problem. I want to do this on Arduino UNO.

@Majenko This is not a problem of this type. The question is how to make such an array and how to read such values afterwards.

I would say you don't want to make an array like that.

@Majenko It may be different. I will download the temperature and the current time. I will fire the relay by time and temperature. I am taking the current time and temperature all the time. At 12 o'clock, if the temperature is less than 22 degrees, I would like the relay to turn on and heat until it reaches 22 degrees. By 16 o'clock I would like the relay to turn on when the temperature is less than 20 degrees, etc. And that's why I'm asking how to make such an array.
Regards

Then you should investigate struct and arrays (of fixed size) or linked lists (for variable size - not recommended on small Arduinos).

It just combines with struct, but I don't know how to "rewrite" the array I wrote in the first post to struct.


text:
Remove blocking delay() toneMelody function?
I would like to change the delay() into a nonblocking function in the code below. I've implemented it (a part of a tutorial from arduino.cc) in my code, but the delay() is blocking the rest of my code. Can anyone help me to change this?
void speelMelodie(int melodie){

if(melodie == 1){

      for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      tone(speaker, melody1[thisNote], noteDuration);

      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes); // <-- this one has to be changed

      noTone(speaker);
      }
  }

else if (melodie == 2) {
      // the same part as previous part (for loop)
  }

else if (melodie == 3) {
      // the same part as previous part (for loop)
  }
}

Look at the Arduino example program, BlinkWithoutDelay (File | Examples | Digital | BlinkWithoutDelay). It uses millis() to time the length of the 'on' and 'off' periods of the LED - just what you want to do with the tone.

Have you looked into examples and tutorials about millis()? Did you understand them? What exactly prevents you from changing your code to millis()?

Yes I have, but I don't know how to implement this in my code. I've 5 different melodies like above fragments.

What are you trying to achieve? From your code, it looks like you play a tone and then you pause for some milliseconds (i.e. silence) and then play the next tone. If that is the case, how millis() will help or what delay is blocking?

@Fahad , I have a lot of other code, I call this function. but due to the delay in this function I can't do with the rest of my inputs outside of this function.

Define  global vars befor setup()
unsigned long timeStamp = 0;
bool pauseOn = false;

and use it
void speelMelodie(int melodie) {

  if (melodie == 1) {

    for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      if (millis() - timeStamp < noteDuration && pauseOn == false) {
         tone(speaker, melody1[thisNote], noteDuration);
      } else { // reset value and change pauseOn to true
        pauseOn = true;
        timeStamp = millis();
      }
      int pauseBetweenNotes = noteDuration * 1.30;

      //delay(pauseBetweenNotes); // <-- this one has to be changed
      if (millis() - timeStamp < pauseBetweenNotes && pauseOn == true) {
          noTone(speaker);
      } else {
         pauseOn = false;
         timeStamp = millis();
      }
    }
  }
}

We need the state variable pauseOn to differentiate between the two states play note or silence. The code compiles, but you have to finetune in your program.A final tip Tutorials using delay() other than

for debuging or
in setup for initializing hardware

are of very low quality
-> Its like a blind person talking about color composition.

Thanks for this, but I get only two notes now.

Post your code completely by editing your question -its hard to find errors in fragments perhaps unrelated to the real problem

This is a part of a function that I call elsewhere, so it should be in this part. The whole code is very big.

Then you have to find it on your own. Now the function is non blocking and as we do not know the rest code it can be caused anywhere (check for other delay() and get rid of them) aso at least give the complete function if you want any further help (and the libs needed - just the include part and the global vars used in the function)

Allright. I will try it by myself first. Otherwise, when i'm stucking, I'll ask you for help.

There was still a delay () in it, so that was indeed a mistake. the rest of the function is a repeat of the given part.
I have edited my code above.

Now I have a constant stop start tone

You have to apply my changes in the same wy to all three parts first. Then ensure that your loop is not constantly calling the speelMelodie with new params. You can do this with a second bool changeMelodie = true/false; so the loop still goes into the function without everytime changing the params. Copy this part of the caller(loop) with some lines before and after and a rough structure what else is happening in the loop

Could you give me an example maybe? It isn't still totally clear for me.

Let us continue this discussion in chat.


text:
Crazy Results with I2C and I2C_Anything()
I have the following code in a Arduino Mega function to retrieve two 4-byte integers from a Teensy 3.2.
Wire.requestFrom(SLAVE_ADDR, sizeof(float)+ 2*sizeof(long));
mySerial.printf("\n<<<<<<<   In IsIRBeamAvail()  >>>>>>>>>>>>>>>>>>>>\n\n");
mySerial.printf("Wire.Available() reports %d\n", Wire.available());
I2C_readAnything(Fin1);
mySerial.printf("Read Fin1 %d, Wire.Available() reports %d\n",Fin1, Wire.available());
Fin2 = Fin1;
mySerial.printf("Fin1 = %d, Fin2 = %d\n", Fin1, Fin2);
I2C_readAnything(Fin2);
mySerial.printf("Read Fin2 = %d, Wire.Available() reports %d\n", Fin2, Wire.available());
mySerial.printf("Fin1 = %d, Fin2 = %d and SteeringValue = %2.2f\n", Fin1, Fin1, SteeringValue);
mySerial.printf("Read %f, Wire.Available() reports %d\n", SteeringValue, Wire.available());
mySerial.printf("Fin1 = %d, Fin2 = %d and SteeringValue = %2.2f\n", Fin1, Fin1, SteeringValue);

And this produces the following output:
<<<<<<<   In IsIRBeamAvail()  >>>>>>>>>>>>>>>>>>>>

Wire.Available() reports 12
I2C_readAnything: Sizeof(value) = 4
Read Fin1 5375, Wire.Available() reports 0
Fin1 = 5375, Fin2 = 0
I2C_readAnything: Sizeof(value) = 4
Read Fin2 = 10750, Wire.Available() reports 0
Fin1 = 5375, Fin2 = 0 and SteeringValue = 0.00
Read 0, Wire.Available() reports 4
Fin1 = 5375, Fin2 = 0 and SteeringValue = 0.00

This is driving me nuts, because while the Fin1 & Fin2 values are apparently received correctly, the Fin2 value is always reported as 0, even after it was explicitly set to be equal to Fin1 as a test (line 6 in the code).
The values obtained from the Teensy (5375 and 10750 in the output snippet) are correct, but I can't get Fin2 to print out correctly (the 'SteeringValue' issue is probably the same as the 'Fin2' problem, but I haven't gotten there yet).
I cannot for the life of me figure out what I'm doing wrong here.  Could someone walking by take a glance from 30 feet away and immediately see the problem?
TIA,
Frank
3/31/20 Update:
I finally got Wire.requestFrom() & I2C_Anything() to behave the way I thought it should, but I'm still left with a mystery - why the PrintEx version of printf refuses to print the values properly:  Here's the code snippet:
//get latest info from IR Demod Module
long Fin1 = 0; //03/30/20 needs to be 'long int' (4 bytes) here to match Teensy int (4 bytes)
long Fin2 = 23; //03/30/20 needs to be 'long int' (4 bytes) here to match Teensy int (4 bytes)
float SteeringValue;

mySerial.printf("\n<<<<<<<   In IsIRBeamAvail()  >>>>>>>>>>>>>>>>>>>>\n\n");

Wire.requestFrom(SLAVE_ADDR, sizeof(Fin1) + sizeof(Fin2)+ sizeof(SteeringValue));
mySerial.printf("Wire.Available() reports %d\n", Wire.available());

I2C_readAnything(Fin1);
mySerial.printf("Fin1 = %d\n", Fin1);

I2C_readAnything(Fin2);
mySerial.printf("Fin2 = %d\n", Fin2);

I2C_readAnything(SteeringValue);
mySerial.printf("SteeringValue = %2.3f\n", SteeringValue);

mySerial.printf("Fin1 = %d, Fin2 = %d, SteeringVal = %6.3f\n", Fin1, Fin2, SteeringValue);

And here's the output produced.  As you can see, the individual values print out correctly, but when combined into the last mySerial.printf() statement, things go awry.  Anyone have a clue?
Wire.Available() reports 12
I2C_readAnything: Sizeof(value) = 4
Fin1 = 1986
I2C_readAnything: Sizeof(value) = 4
Fin2 = 3972
I2C_readAnything: Sizeof(value) = 4
SteeringValue = 6239.219
Fin1 = 1986, Fin2 = 0, SteeringVal =  0.000

Frank
And one last update:  I compared the output obtained by using the StreamEx mySerial = Serial; object, and the one obtained by using the more traditional Serial.print() statement.  The code
    Serial.print("Fin1 = "); Serial.print(Fin1); Serial.print(", ");
Serial.print("Fin2 = "); Serial.print(Fin2); Serial.print(", ");
Serial.print("SteeringValue = "); Serial.println(SteeringValue);
mySerial.printf("Fin1 = %d, Fin2 = %d, SteeringValue = %3.2f\n", Fin1, Fin2, SteeringValue);

And the output:
Fin1 = 9185, Fin2 = 18370, SteeringValue = 28851.73
Fin1 = 9185, Fin2 = 0, SteeringValue = 0.00

The top line is entirely correct, but for some reason, the mySerial.printf() version gets it wrong. Ideas?
Frank

What is the type of Fin1 and Fin2? Also, on lines 10 and 12, you are actually printing Fin1, twice.

Fin1 & Fin2 are both 'long int' (4 bytes on Arduino Mega). These match the 4-byte 'int' type from the Teensy 3.2 slave.  And yes I know I'm printing things multiple times, but I don't think that changes the basic craziness of getting a correct result into Fin2 and then not being able to print it.

What library you are using for printf()?

Arduino PrintEx library

The devil is in the details. From the PrintEx repo doc, this is the formatting for printf:

%[flags][width][.precision][length]specifier

When you use long, you will have to provide the [length], and the lib only accepts "l" (Letter L).
#include <PrintEx.h>

long int Fin1 = 5;
long int Fin2 = 2;
float SteeringValue = 3.5;

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

  Serial.print("Fin1 = "); Serial.print(Fin1); Serial.print(", ");
  Serial.print("Fin2 = "); Serial.print(Fin2); Serial.print(", ");
  Serial.print("SteeringValue = "); Serial.println(SteeringValue);

  // This will fail
  mySerial.printf("Fin1 = %d, Fin2 = %d, SteeringValue = %3.2f\n", Fin1, Fin2, SteeringValue);

  // This will work as expected
  mySerial.printf("Fin1 = %ld, Fin2 = %ld, SteeringValue = %3.2f\n", Fin1, Fin2, SteeringValue);
}

void loop() {}

Line 16 is what you have. Line 19 is the format you should use.

Yep -that did the trick, although I would have sworn on a bible that I had tried the %ld modifier at some point.


text:
Why are begin() functions needed to initialize hardware (if they are)?
I'm writing a program for an ATmega microcontroller using the Arduino framework.
While implementing an hardware-related class (one to manage LEDs), I put some hardware initialization code such as pinMode(OUTPUT) in the class constructor. Then I realized that in all Arduino libraries I know the hardware initialization is done in a begin() or init(), so I created one for my Led class as well and moved pinMode() there.
Now I'm wondering if I really should define such initialization funcitons, i.e. why they are needed - or, if they are not, why so many libraries have them. I played around a bit and found that for example this code works on an ATmega1284 (it makes the LED on pin 28 light up).
struct Test {
  Test() {
    pinMode(28, OUTPUT);
    digitalWrite(28, HIGH);
    // other stuff
  }
  // ...
};

Test test;

void setup() {
}

void loop() {
}

I presume that this code is somehow ill-conceived, letting alone the fact that it lights up a led without any code in the main function (or maybe that is exaclty the problem?), but if so I can not see why. What did I not consider?
Should the code above be rather writte as in the following snippet, as the existence of all these begin() functions leads me to believe?
struct Test {
  Test() {
    // other stuff
  }
  void begin() {
    pinMode(28, OUTPUT);
    digitalWrite(28, HIGH);
  }
  // ...
};

Test test;

void setup() {
  test.begin();
}

void loop() {
}

Although Arduino API styleguide recommends to use begin() to set thing up. To me both are works and is a design consideration, provided that you know what have been configured and initialised by the Arduino.h and variants for a particular boards, and what you are trying to do in the construct will not be overrided by the init() within the Arduino Core main(). For example, you see many library use the construct to set thing up like LCD lcd(SDL, SDA);.

To your question about setup() and loop(), see the source code of Arduino Core main.cpp for better understanding.

It's all to do with the order of execution.
Constructors are executed before normal functions. That includes the main() function which eventually calls setup() and (repeatedly) loop(). One of the other things that main() does is call init() (or some variant of) which configures the hardware.
Since that happens after any global constructors have been run anything that the constructor did to the hardware could potentially be undone.
Thus it is normal to defer any hardware configuration until after main() has done the work of setting things up, and the convention is to use a begin() function to do it.

Thanks for the answer! And what is actually this init() function? Where is it defined? And, by the way, where is the main() function in an Arduino project?

It's all in the core. Read the cores source code.


text:
SI5351 Breakout 153,600Hz Square Wave Signal
I'm trying to generate a consistent 153,600Hz square wave signal with 50% duty cycle from a Adafruit SI5351 3.3-5v breakout board for use as a fixed synchronous serial clock reference, but the closest frequency I get from it is 142,857Hz which is too far off the target.
Originally, I followed this article (my device looks exactly like the one in the pictures) from Adafruit to no avail. I tried using the Adafruit library and the mentioned ClockBuilder software, but the article makes no mention of how to apply the values returned from the software into code, and messing with the values myself didn't help either.
So, I then moved on to using this library from etherkit. It's has a lot simpler interface, and was easy for me to get at least something being output.
Here is my current code using the etherkit library running on my Arduino Mega. It seems to only output 142,857Hz, even though I specified my target frequency of 153,600Hz.
//Arduino Mega
#include "si5351.h"
#include "Wire.h"

Si5351 si5351;

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

    if (!si5351.init(SI5351_CRYSTAL_LOAD_8PF, 0, 0))
    {
      Serial.print("Cannot communicate with SI5351.");
    }
    else
    {
      si5351.drive_strength(SI5351_CLK0, SI5351_DRIVE_8MA);
      si5351.output_enable(SI5351_CLK0, 1);
      si5351.set_freq(153600ULL * 100ULL, SI5351_CLK0);
    }
}

void loop(){}

But here is where it gets odd: I can set the frequency argument of set_freq to anything under 120000ULL * 100ULL and the output will be spot on, but anything above that amount will "snap" back to 142,857Hz, up to 190000ULL * 100ULL.
The other thing I got working against me is that I don't have access to a oscilloscope to more accurately measure it's output. My current solution is a Arduino UNO acting as a frequency measuring tool, running the following code:
//Arduino Uno
#define pin_MeasureThis A0

volatile unsigned long on_time;
volatile unsigned long off_time;

float lfreq;
float freq;
char freq_str[12];
char msg[32];

void setup()
{
  pinMode(pin_MeasureThis, INPUT);
  Serial.begin(9600);
}

void loop()
{
  on_time = pulseIn(pin_MeasureThis, HIGH);
  off_time = pulseIn(pin_MeasureThis, LOW);
  freq = 1000000 / (on_time + off_time);

  if (freq >= 0 && freq < 999999)
  {
      dtostrf(freq, 8, 0, freq_str);
  }

  if (freq != lfreq)
  {
    lfreq = freq;

    sprintf(msg, "%sHz", freq_str);
    Serial.println(msg);
  }
}

I tested my measuring code by comparing it's measurement against visible frequencies with a LED and it performed perfectly. I do understand that probably doesn't scale well for higher frequencies, but I really have no better way right now.
Here is a sample of the exact serial output I get back from my Arduino UNO measuring the CLK0 output of the SI5351 breakout board:
  ...
  142857Hz
  125000Hz
  142857Hz
  125000Hz
  ...

Any advice on how to get to a steady 153,600Hz signal would be much appreciated. Thanks.


text:
Arduino SIM900 No SMS received
I tried the tutorial in this link
https://lastminuteengineers.com/sim900-gsm-shield-arduino-tutorial/
to send an SMS message using a SIM900 GSM shield
I completed the section to send AT commands successfully but I can't get
the Arduino Uno to send an SMS. Below is the output I get after doing AT command tests
Initializing...
AT

OK
AT+CPIN?

+CPIN: READY

OK
AT+CSQ

+CSQ: 6,0

OK
AT+CCID

8944500105191448516F

OK
AT+CREG?

+CREG: 0,5

OK
AT+COPS?

+COPS: 0,0,"T-Mobile "

OK
AT+COPS=?

+COPS: (2,"T-Mobile ","T-Mobile ","310260"),,(0,1,4),(0,1,2)

OK

and below are the responses from the SMS code
Initializing...
AT

OK
AT+CMGF=1

OK
AT+CMGS="+1mycellphonenumber"

> Last Minute Engineers | lastminuteengineers.com

so no response from the AT+CMGS command and NO SMS received.
Plug is 5V 2A.
Any idea what might be causing the issue?
Below is the code I used for the Setup() function
void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("Last Minute Engineers | lastminuteengineers.com"); //text content
  updateSerial();
  mySerial.write(26);
}

Changed my SIM card to Ting from Hologram and it worked just fine!

It's OK to accept your own answer as the solution to the problem.

Normally in Setup() you have in the end this sequence
Serial.println("Connecting to the network...");

while( (sendATcommand("AT+CREG?", "+CREG: 0,1", 500) ||
    sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0 );

     sprintf(aux_str, "ATD%s;", phone_number);
     sendATcommand(aux_str, "OK", 10000);

     delay(seconds * 1000);

    Serial.println("ATH"); // disconnects the existing call

So after the registering you send
 Serial.println("AT+CMGS=\"1234567890\""); //CHANGE TO DESTINATION NUMBER

Did you use the \" for the embracing the number. Without your real command its hard to guess. Better use a test program Soft Serial GPRS Code, serial monitor is error prone.
EDIT The OP posted code parts. The code after:
  Serial.println("Initializing...");
  delay(1000);

should be in the loop()- Look at the linked examples how should communication take place if the code is run once so no recurring tasks like reading chars or similar.

I posted the Setup() function code I used above, the line below is to send the SMS. mySerial.println("AT+CMGS="+1mycellphonenumber"");


text:
serial is print twice?
I have a problem , when send 1 or 0 by Bluetooth module the serial monitor print two time (RECEIVED SMS) . what's the wrong ?
This is my code  :
   char BluetoothData = 0 ;
void setup() {
  // initialize serial communication:
  Serial.begin(9600);
    for (int pin = 1; pin <= 13; pin++)
     {
       pinMode(pin, OUTPUT); // sets the digitals pin  as outputs
       digitalWrite(pin, LOW); // sets the digitals pin off defult intial states
     }
       Serial.println("ALL LEDs NOW OFF \n ");
       Serial.println("Please, Enter : ( 1 to Turn on All LEDs )  or ( 0 to Turn off LEDs ) \n");
}
void loop() {
  // read the sensor:
  if (Serial.available() > 0) {

        BluetoothData = Serial.read();
            Serial.print("*** RECEIVED SMS *** : ==>> ");
            Serial.println(BluetoothData);

        if (BluetoothData == '1'){
        for (int Pin = 1; Pin <= 13; Pin++) {
          digitalWrite(Pin, HIGH);
          }
          Serial.println("ALL LEDs NOW ON");
         }
        // turn all the LEDs off:
   else if (BluetoothData == '0') {
        for (int Pin = 1; Pin <= 13; Pin++) {
          digitalWrite(Pin, LOW);
          }
          Serial.println("ALL LEDs NOW OFF");
         }
  }
   delay(100);
}

This is photo for serial monitor

Please do not post photos of the output, rather select the text, then copy/paste the text into the question, as indented code

for ease of readability and understanding: 1) please consistently indent the code.  Indent after every opening brace '{'.  Unindent before every closing brace '}'.  Suggest each indent level be 4 spaces.

the posted code does not contain a main() function, not the necessary #include statements.  So how are we to reproduce the problem?

I cannot understand all the functions and terms of the site.  I weak in that, is there a video that explains the matter?

Probably the first time because you received the character '1' or '0'.
The second character is probably a '\0' or '\d', an end-of-string or end-of-line character.
You can easily check this by printing the value of each received character, like
Serial.println((int)(BluetoothData));

You probably see the value for '0' (48), '1' (49), end of string '0' of end of line '13' or maybe '10' (new line).

thanks a lot man , true solution :)

you're welcome.

In the Arduino IDE you should select "No Line Ending" from the menu, instead of "New line". Otherwise you are sending an extra "\n".


text:
Using esp8266 instead of xbee
I am using xbee pro s2c to get data from arduino (temp, pressure etc.) and I am sending data another xbee module and read these data from serial port.
Question is that I want to use esp8266 instead of xbee. Is it possible? Can I communicate 2 esp module like xbee?

you would just need one ESP, which connects to both your wifi and the sensor. You could use 2 with ESP-NOW to get a non-wifi module communication going, but it's simpler to use wifi. You also likely don't even need an arduino; sensors can connect directly to the ESP.

You can make two ESP8266 modules talk together, yes. It's not "simple" like an XBee, since you have a generic WiFi network interface, so there's many many different ways of doing it. Typically one would be running as a WiFi Access Point (SoftAP) and the other would connect to it. Then you'd run some "server" code on one module (typically the SoftAP one) and the other acts as a client and connects to it (or sends data to it).


text:
Counter variable gets reset to 0 without resetting it(Mega)
(Arduino Mega2560) I'm trying to test placing a counter n in a for loop, the problem is, every time it gets out and goes back to the for loop, the n is reset again, so it prints "counter: 245" every time. However, when I comment out *b++=data; and data++; it does count properly. What exactly is going on ?!
Code:
uint8_t i=0;
uint8_t buf[245];
uint8_t *b=buf,*b2=buf;
uint8_t data=10;
int n=0;

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

void loop() {
for(i=0; i<245 ;i++){
  *b++=data;
  data++;
  delay(50);
  n++;
  Serial.println(buf[i]);
  }
  data=0;
  delay(5000);
  Serial.println("counter:");
  Serial.println(n);
  delay(5000);
}

b is heading off into the unknown and you're blasting all your other variables with junk.

Oh I see ! I have never tried pointers before, can I do b=0 to reset it or it's done a different way ?

b = buf; will reset b to the start of the buf variable memory area. Your b++ goes up and up and up otherwise with no limit. After 254 increments it will be pointing at something after buf - which sounds like n to me.

You never reset your b pointer. The first time through it works its way through the memory reserved for buf. The second time through your loop it's already at the end of that memory and you then start incrementing (and filling) past that overwriting other variables - the first of which sounds like it might be n - so *b++=data is writing data (245) to n.
You need to reset b each time you go through loop so it starts at the beginning of the array each time:
b = buf;

Thanks Majenko, it makes sense now.

@Majenko ... upvoted ... my mistake indeed.