text:
NodeMCU unable to communicate with MFRC522 RFID reader
I am creating a project that will read the RFID card or tag data, store that into a mysql database and display the data via PHP.
I am using NodeMCU, RC522 RFID reader and Ardunio IDE to do that.
Below is my Arduino code.  It successfully connects with WiFi (that I can see via serial monitor) but gives no response when I touch the RFID card to the reader.
I can't find the error.
/*
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# RFID MFRC522 / RC522 Library : https://github.com/miguelbalboa/rfid #
#                                                                     #
#                 Installation :                                      #
# NodeMCU ESP8266/ESP12E    RFID MFRC522 / RC522                      #
#         D2       <---------->   SDA/SS                              #
#         D5       <---------->   SCK                                 #
#         D7       <---------->   MOSI                                #
#         D6       <---------->   MISO                                #
#         GND      <---------->   GND                                 #
#         D1       <---------->   RST                                 #
#         3V/3V3   <---------->   3.3V                                #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN D2  //--> SDA / SS is connected to pinout D2
#define RST_PIN D1  //--> RST is connected to pinout D1
MFRC522 mfrc522(SS_PIN, RST_PIN);  //--> Create MFRC522 instance.

#define ON_Board_LED 2  //--> Defining an On Board LED, used for indicators when the process of connecting to a wifi router

//----------------------------------------SSID and Password of your WiFi router-------------------------------------------------------------------------------------------------------------//
const char* ssid = "apiece solution";
const char* password = "apiece@123";
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//

ESP8266WebServer server(80);  //--> Server on port 80

int readsuccess;
byte readcard[4];
char str[32] = "";
String StrUID;

//-----------------------------------------------------------------------------------------------SETUP--------------------------------------------------------------------------------------//
void setup() {
  Serial.begin(115200); //--> Initialize serial communications with the PC
  SPI.begin();      //--> Init SPI bus
  mfrc522.PCD_Init(); //--> Init MFRC522 card

  delay(500);

  WiFi.begin(ssid, password); //--> Connect to your WiFi router
  Serial.println("hello");

  pinMode(ON_Board_LED,OUTPUT);
  digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board

  //----------------------------------------Wait for connection
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    //----------------------------------------Make the On Board Flashing LED on the process of connecting to the wifi router.
    digitalWrite(ON_Board_LED, LOW);
    delay(250);
    digitalWrite(ON_Board_LED, HIGH);
    delay(250);
  }
  digitalWrite(ON_Board_LED, HIGH); //--> Turn off the On Board LED when it is connected to the wifi router.
  //----------------------------------------If successfully connected to the wifi router, the IP Address that will be visited is displayed in the serial monitor
  Serial.println("");
  Serial.print("Successfully connected to : ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  Serial.println("Please tag a card or keychain to see the UID !");
  Serial.println("");
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//

//-----------------------------------------------------------------------------------------------LOOP---------------------------------------------------------------------------------------//
void loop() {
  // put your main code here, to run repeatedly
  readsuccess = getid();

  if(readsuccess) {
  digitalWrite(ON_Board_LED, LOW);
    HTTPClient http;    //Declare object of class HTTPClient

    String UIDresultSend, postData;
    UIDresultSend = StrUID;

    //Post Data
    postData = "UIDresult=" + UIDresultSend;

   // http.begin("http://192.168.1.6/NodeMCU_RC522_Mysql/getUID.php");  //Specify request destination
    //http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header

    int httpCode = http.POST(postData);   //Send the request
    String payload = http.getString();    //Get the response payload

    Serial.println(UIDresultSend);
    Serial.println(httpCode);   //Print HTTP return code
    Serial.println(payload);    //Print request response payload

    http.end();  //Close connection
    delay(1000);
  digitalWrite(ON_Board_LED, HIGH);
  }
  else
  {
    Serial.println("hi");
     delay(1000);
  }
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//

//----------------------------------------Procedure for reading and obtaining a UID from a card or keychain---------------------------------------------------------------------------------//
int getid() {
  if(!mfrc522.PICC_IsNewCardPresent()) {
    return 0;
  }
  if(!mfrc522.PICC_ReadCardSerial()) {
    return 0;
  }

  Serial.print("THE UID OF THE SCANNED CARD IS : ");

  for(int i=0;i<4;i++){
    readcard[i]=mfrc522.uid.uidByte[i]; //storing the UID of the tag in readcard
    array_to_string(readcard, 4, str);
    StrUID = str;
  }
  mfrc522.PICC_HaltA();
  return 1;
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//

//----------------------------------------Procedure to change the result of reading an array UID into a string------------------------------------------------------------------------------//
void array_to_string(byte array[], unsigned int len, char buffer[]) {
    for (unsigned int i = 0; i < len; i++)
    {
        byte nib1 = (array[i] >> 4) & 0x0F;
        byte nib2 = (array[i] >> 0) & 0x0F;
        buffer[i*2+0] = nib1  < 0xA ? '0' + nib1  : 'A' + nib1  - 0xA;
        buffer[i*2+1] = nib2  < 0xA ? '0' + nib2  : 'A' + nib2  - 0xA;
    }
    buffer[len*2] = '\0';
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//

do you feel that your code is easily readable?

your code is OK, I've made a very similar project and... got the same issue. Solution was not in code only in power supply. RFID need very efficient current source and stable voltage. Check the power source, if you used 7805 as linear voltage stabilizer your project will don't work.


text:
How to flash a NodeMCU (ESP8266) with an external FTDI programmer?
Hi my USB to UART bridge (CP2102) seems to be broken on one of my NodeMCU Dev Boards with ESP8266.
It seems to be just that specific board since all other boards that I have can be flashed without problems.
I have a FTDI Programmer like this one:
FTDI Programmer
Now I would like to flash the Nodemcu using the FTDI programmer but I'm not sure how to wire it up.
I know that those programmers cant power up the ESP8266 by itself thats why I would use a micro USB cable that doesnt have a data wire to power up the nodemcu.
This is how I would wire everything up:

Is this the correct way to wire up the programmer with the nodemcu? I want to be sure that nothing is going to mess up with the nodemcu or the programmer.
NodeMCU       FTDI
GND    ---->  GND
RX     ---->  TX
TX     ---->  RX

Looks fine to me. Just hold the FLASH button and tap RST before you want to program to put it into bootloader mode. You may want to try that with the existing USB connection first before you go through the rigmarole of wiring up an FT232 board.

@Majenko yeah I tried the build in Serial Connection but on this specific Nodemcu I keep getting: ERROR Running command failed: could not open port 'COM3': PermissionError(13, 'Zugriff verweigert', None, 5)

Assuming your FTDI Basic is the 3.3V version, then yeah that will work fine provided you that manually reset the board yourself and enter the boot-loader using the buttons.
If you're independently powering the boards you may want to insert some series resistance in the RX and TX connections in case your signal receiving end is not powered while the sending side is.  In short you don't want the TX signal from one of your devices (boards) trying to power the receiving device (board) through its protection/clamp diodes.
In regard to comment about resistor value:
The value of the resistor depends on what you can get away with in terms of its effect on the signal and how much current is allowed through the clamp diodes on the other board.  A couple of Kbyte is probably sufficient, better than nothing in any case. Use a bit more if you can and still get a reliable signal through.  If you have the boards both powered before you connect them and you're careful about connecting them, then there's no opportunity for that.  It may also just be that they're robust enough that you don't need them at all.  I usually put some in though.  The second reason which I didn't state above is just that it protects you from being outright stupid and accidentally connecting them to the wrong thing; wrong signal, or to VCC or GND on the other side.

which resistors should I use and how exaclty do I wire them up? (The programmer that I have has jumper connectors for 5v and 3.3v)

They're just in series with the signal, which hopefully will be clear in the above.  I'm addressing that only briefly though, otherwise there's more in there about that then just answering the question.

Is it also possible to connect it like this: https://imgur.com/a/Tb7Llow
I'm not sure if the programmer is going to be able to power the nodemcu up but at least then I dont need to mess up with resistors etc. is this possible?

Right, that removes the "independently powering" concern.  Just be careful your code doesn't do something like use pinMode with OUTPUT on the RX pin and you should be fine.

Even on an Arduino UNO, where the serial transceiver and and the microcontroller are powered together, resisters are still in place to protect against accidentally driving serial pins the wrong way; it lets people be a bit more careless.  What you've shown is something I would do, because I know not to try to drive one of the serial pins opposite the FTDI.  If it was something I was putting "into the field" as it were, I'd be more inclined to have them in there, just in case I screw up.

Ok so I tried to flash it while powering the esp with the programmer. Unfortunately Im still not able to flash the esp. I opened the serial monitor on the com port of the programmer to see what boot mode the esp is starting if I press the flash button and then press the reset button this is the output:
ets Jan  8 2013,rst cause:2, boot mode:(1,7)
this should be correct. But its the same case as if I try with the build in USB to UART connection. It cant establish the connection for flashing and just times out. :( I think that I just have a faulty Chip (serial monitor was closed while flash)

Let us continue this discussion in chat.

source: Stack Exchange

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

sort: votes


text:
Unable to upload sketch to Lolin S3 Pro (ESP32-S3)
I'm trying to upload a simple sketch to the new Wemos Lolin S3 Pro but unfortunately I can't seem to get it to work. I get the following error message:
    Connecting......................................

A fatal error occurred: Failed to connect to ESP32-S3: No serial data received.
For troubleshooting steps visit: https://docs.espressif.com/projects/esptool/en/latest/troubleshooting.html
Failed uploading: uploading error: exit status 2

The following board is causing problems:
https://www.wemos.cc/en/latest/s3/s3_pro.html
It seems that there is no USB to UART chip and also no boot button.
As board I selected the "LOLIN S3 Pro" in the Arduino IDE and under Platformio I had selected the "lolin_s3".
I have also tried it under platformio with the following build flags but unfortunately without success:
build_flags = -DARDUINO_USB_MODE=1 -DARDUINO_USB_CDC_ON_BOOT=1

I am really perplexed what could be the cause?
Btw: I bought 3 of these boards and all 3 have the same issue.

OK I managed to solve it although I find its a little bit annoying it seems that you need to always set this board in download mode manually. (Press and hold boot and click reset button once).
If you are using Arduino IDE use the following options:

USB CDC On Boot -> Enabled
Upload Mode -> Hardware CDC / UART0

If you are using PlatformIO use the following build flags:
build_flags = '-DARDUINO_USB_MODE=1' '-DARDUINO_USB_CDC_ON_BOOT=1'

Also a good source: https://espressif-docs.readthedocs-hosted.com/projects/arduino-esp32/en/latest/tutorials/cdc_dfu_flash.html

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


text:
Arduino MKR GMS alternative
I’m starting on a project about monitoring the soil in the agriculture field and also to visualise the data remotely. The aim of this project is collect the atmospheric data as well as the soil related parameters and then send them to cloud where they’ll be presented on the dashboard. I decide to use Arduino as my development board and Arduino MKR GMS 1400 would be perfect for this project. However this board is quite expensive. So just wondering that are there any alternative I can use for this project
Thank you

sounds like any microcontroller would be sufficient ... not really an Arduino question

There are multiple options for this project as you just want to send/ upload data on the cloud server rather than using Arduino MKR 1400 you can use any of the following.

Arduino UNO with GSM module: As per your requirement you can use Arduino UNO to read the data from the sensor and the GSM module will be used to upload the same on the cloud server. There are various GSM modules available in the market which are cheap also and good. You can also use SIM800 one of the GSM module.

Other GSM modules which you could use can be,
SIM900, Quectel EC-20, Quectel M95. You can also visit SIMCONN website where you can find multiple GSM module options.

You can also use ESP8266 or ESP32 which are Wi-Fi modules but in this case you will require a internet/ Wi-Fi connection near the controller. ESP8266/ ESP32 will read data from the sensors and can also upload the same to the cloud servers. But as you said you are using them to monitor agriculture field it won't be possible to have a Wi-Fi which will cover such long range.

One of the possible solutions to the problem is to use RF-link to transmit data and collect it at a base-station and from the base station you can upload/ send them to the server.

You can also make use of the LoRa Network to communicate along the fields and then receive data from the whole field at a base station and then upload them to the server. But this could be a more expensive solution.

Instead of using the LoRa network you also could use 433mhz modules with an antenna to extend range communicating with a base station, but I'm not sure if the Antenna is helping enough and the range might not be covered though.


text:
BLDC motor erroneous running with digital potentiometer
I am using this digital potentiometer http://www.farnell.com/datasheets/31917.pdf to control a BLDC motor with Arduino Mega. When I am running the below code, the motor runs at the lowest speed when I am setting i = 0 in forward() function.
const int CS = 10;
const int INC = 9;
const int UD = 8;

void setup() {
  pinMode(CS, OUTPUT);
  pinMode(INC, OUTPUT);
  pinMode(UD, OUTPUT);
  digitalWrite(CS, HIGH);
  digitalWrite(INC, HIGH);
  digitalWrite(UD, HIGH);
}

void forward() {
  for (int i = 0; i <= 100; i += 10) {
    setResistance(i);
    delay(10);
  }
}

void loop() {
  forward();
}

void setResistance(int percent) {
  digitalWrite(UD, LOW);
  digitalWrite(CS, LOW);
  for (int i = 0; i < 100; i++) {

    digitalWrite(INC, LOW);
    delayMicroseconds(1);
    digitalWrite(INC, HIGH);
    delayMicroseconds(1);
  }

  digitalWrite(UD, HIGH);
  for (int i = 0; i < percent; i++) {
    digitalWrite(INC, LOW);
    delayMicroseconds(1);
    digitalWrite(INC, HIGH);
    delayMicroseconds(1);
  }

  digitalWrite(CS, HIGH);
}

The problem is when I set the value of i in the forward() function to 70 or 80 the motor runs sometimes at a much faster speed but other times when I upload the code with the 70/80/any value other than 0, the motor doesn't move at all. When i is set to 0, the motor runs every time at a super slow speed but for other values it sometimes moves at a faster speed, other times it doesn't move at all.
I am not sure what is causing this issue. Please help.

it is difficult to guess the information about the motor and about how it is connected to the arduino

BLDC describes a family of motors, it is (Brushless Direct current) motor. Some have the sensors internal, some supply communication signals, some supply just phase etc.  Anything at this point would be a SWAG until more information is supplied.


text:
How can I read the data stored in EEPROM although is powered OFF based on the simple code I wrote?
I need help regarding on EEPROM library. Based on the code below, for every 2 sec, I want to store the int for increase where it will keep increasing by 1. Then, I upload to my Arduino Nano and open Serial Monitor to let it run for about 20 seconds. The serial monitor shows that Increase Count:10.
Then I unplug the Arduino Nano, closed the Serial Monitor, wait for 5 sec, then plug back to computer and turn on the Serial Monitor, then the Serial Monitor start to shows Increase Count:1, which indicated it start to recount again from 1,2,3,4.....
I thought that EEPROM will store the last number it counted which is 10, then when I unplug and plug back it should continue to count from 10, 11, 12, .......
So I would like to ask community whether my execution code and the method is correct or not. If not, can you advice me on how I can execute it correctly. Thank you in advance!
#include <EEPROM.h>

int addr=5;
int storagedata;
int increase;

void setup()
{
  storagedata=EEPROM.read(addr);
  Serial.begin(9600);

  timevalue=millis();
}

void loop()
{
  if (millis()-timevalue>=2000)
  {
    increase=increase+1;

    EEPROM.update(addr,increase);
    storagedata=EEPROM.read(addr);

    Serial.print("Increase Count:");
    Serial.println(storagedata);

    timevalue=millis();
  }
}

Yup, true. That is why I need some guidance. Thanks

increase is a global variable and will implicitly initialized with the value zero. Then you are reading the EEPROM data into the variable storagedata in setup(). And then in loop() you are increasing increase from zero to one and write that to EEPROM. This value then gets read back into storagedata. So now increase and storagedata have the same value: one. So the counting begins on every reset at 1.
It is unclear, why you even have 2 variables for this. One would be enough (unless you want to test the EEPROM for some reason). In setup() read the data into increase. Then the counting starts with the number in EEPROM.

strange what some people consider as useful answer

@Juraj I'm not sure, what you are criticizing here. Can you explain that a bit more? Is my answer not good in some way? Or is it about the fact, that such an easy answer gets more upvotes, as more complex ones? (Which I also wonder about)

I wonder how is the answer useful for anybody else then OP

@Juraj About that we could have a full discussion. Here we often have question, from whose answers others will most likely not profit. We have the possibility to dismiss those questions and close them, or answer them to help. Or - if you have an answer to the question, which would also help others - you can add your own answer.

Hey there, thank you for highlighting my error and I learned so much from your reply. Is fixed and it works fine.

The problem is that you fail to initialize increase during setup(). The variable is undefined when the code enters the loop() function, even regardless of whether this is the first boot or not. You should change storagedata to a local variable in loop() and use increase to keep the value (or vice versa).

You never use the value you read in setup().  Go through your loop() function one line at a time:
// this does not use the value read in setup, variables are initialized to 0
// so the first time through this loop it will set 'increase' to 1
increase=increase+1;

// you are updating EEPROM with the value of 'increase' which is 1 the first
// time this is executed
EEPROM.update(addr,increase);

// you are reading the '1' that was just written into 'storagedata', you have
// never used the value you read in 'setup()' and have now overwritten it
storagedata=EEPROM.read(addr);

I'm not sure why you have two separate variables, but in setup() you just need to
initialize increase as the value read from EEPROM:
storagedata=EEPROM.read(addr);
increase=storagedata; // start with stored value instead of default 0


text:
How can I store a value of 1000 over to EEPROM of Arduino Nano?
I need some of your feedback and guidance. In my prototype project powered by Arduino Nano(Space Constraint), it will operate continuously until it reach a maximum of 100 hours. Once it reached 100 hours mark, Nano will prompt users to do servicing/maintenance etc.
So in order to preserve the operating time from losing when powered off, I used EEPROM library to store the data. Based on my research, EEPROM.update(addr,value), each addr can hold one byte, which is 0-255 values. To prevent my EEPROM die from storing operating time of 100 hours, I used flag method, where every 5 mins of operation it will increase flag and store the flag value to EEPROM.
Is there other method other than changing the 5 mins benchmark?
Below is the simple/direct code that I wrote, the original code is too complex, and I have put a few comment especially the "Ideal Command" that I want.
#include <EEPROM.h>

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

  regenflag=EEPROM.read(regenaddr);
}

void loop()
{
regenflag=EEPROM.read(regenaddr);

if(totaltime>=300000)//Every 5min machine operated, increase regenflag (Fixed)
  {
    regenflag=regenflag+1;
    Serial.print("How many times it Operated==> ");
    Serial.println(regenflag);
    unblink=1;//Flag for other operation

    EEPROM.update(regenaddr,regenflag);
    regendata=EEPROM.read(regenaddr);

    totaltime=0;
}

/////////////////////////////////Ideal Command/////////////////////////////////////////////////////////
if (regendata>=1200) //100hrs=6000mins (6000mins/5mins=1200 times)
{
  Serial.println("Need to do Servicing")
}

use EEPROM.put and EEPROM.get https://www.arduino.cc/en/Reference/EEPROMPut


text:
Does HC-05 module buffers the data received?
I am using HC-05 bluetooth module for sending large data(80-100KByte) from my phone to arduino-uno.
I had found that this module has a flash chip of 8Mbit  (SST39VF800A) but the datasheet of HC-05 has nothing about buffering of the data to be transmitted or data received.
I need clarity about the buffering of data so that I can change the data rate from the phone for better communication.

Mhh, interesting question. As bluetooth itself is packaged, I think the module needs to at least buffer a few packages. This answer states, that maximum package size could be around 1KB. But to be sure, one would to read the firmware code or ask the one, who wrote that. I'm not sure, if that firmware is opensource.

I didn't find any help in any data-sheets I could find, either. So I'd suggest a simple experiment, sending increasingly large packets before the other side attempts to read anything, until some data goes missing. The packets don't even need to be very sophisticated if all you want to know is whether N_received == N_sent and for what maximum 'N'.
Update:

All bytes were received correctly if there is no delay but with
increasing delay in reading from HC-05 data was not fully received and
with delay greater than 800ms only 63Bytes were received.

If you're collecting data as it arrives, then you can't measure the buffering. When you wait until all data has been set before you try to read any, the number of bytes you receive is the buffer size. It sounds like a 63 byte buffer, probably only what the HC-05's hardware UART can buffer, without using any of its memory to increase that.

I did the experiment by sending 100B and 1000B of data separately which took 4ms and 70ms respectively. All bytes were received correctly if there is no delay but with increasing delay in reading from HC-05 data was not fully received and with delay greater than 800ms only 63Bytes were received.

I think the buffer is FIFO since the data received were FIRST 63 bytes.


text:
converting int or float into bytes array in arduino
I am trying to send data from one arduino to another over ethernet using udp protocol.
In arduino writing data over udp is like this
UDP.write(buffer, size);

where buffer is an array to send as a series of bytes and size is the size of the array.
Now, i am reading a sensor value from a0 pin of the arduino it will be stored either in int or float type variable. As mentioned earlier udp only sends byte type array. so all i want to do is convert the value stored in the variable to the byte type array.
my variable will be.
pinMode(A0,INPUT);
int data;
byte data_array[Size];

and in loop
data=analogRead(A0);

now i have convert this value in data_array;
Please provide the suggestion with proper explanation.
Thank you

UDP.write((const byte*) &data, sizeof(data));


text:
Is it possible to change and save I2C address programatically?
I want to drive 3 i2c devices on a single i2c line. Is it possible to achieve this without using A0,A1,A2 pins?
I thought the address of i2c devices should be programmatically changeable.
2 mcp23017 and si5351 chips I use.

Some I2C devices can have their addresses changed programatically, most can't. The datasheet will tell you. You could drive the Ax pins from the Arduino to change them at will, but to what end?

Why don't you want to use the address configuration pins? That's exactly what they are there for.

@Mat bc hw designer forget to connect these pins to mcu :(
If it was OK to change programmatically, this would make my life easier.

If the pins are not connected in hardware (left open floating), the MCP23017 will show undefined behavior. It may randomly change addresses (even during operation), which is useless. These pins must be connected properly.

@projecti2c: you don't connect these pins to the MCU (in usual settings). You look at the datasheet and tie them e.g. to ground or VCC depeding on what address you want. The address selection pins don't change during normal operations.

As far as I can see in the datasheets of the 2 mentioned chips, they don't provide a way to change the address programmatically over the I2C bus. They only have address pins, which have to be tied to Vcc or ground for setting the address. Most ready to use boards with such chips already have pullup or pulldown resistors for this. If you use the blank chips, you absolutely need to tie the address pins to a fixed value. Normally this is done semi-permanently.
You can also connect the address pins to Arduino output pins to dynamically change the addresses.
There is no other way to change the addresses but to use the address pins.


text:
ESP32 Post Request Not Working
This sample code for the esp32 doesn't work. When contacting the website I get a 301 error and the website acts as if nothing was ever recieved. Note: Been using arduino for 2 years.
/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "lol";
const char* password = "u tried";

//Your Domain name with URL path or IP address with path
String serverName = "http://requestbin.net/r/63agtdpl";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

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

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());

  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      HTTPClient http;

      String serverPath = serverName + "?temperature=24.37";

      // Your Domain name with URL path or IP address with path
      http.begin(serverPath.c_str());

      // Send HTTP GET request
      int httpResponseCode = http.GET();

      if (httpResponseCode>0) {
        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);
        String payload = http.getString();
        Serial.println(payload);
      }
      else {
        Serial.print("Error code: ");
        Serial.println(httpResponseCode);
      }
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

doesn't't the site require a secure connection https?


text:
Arduino create Json Array with double values and 2 decimal point
How i can create a Json Array with double values and 2 decimal point using the ArduinoJson Library?
https://arduinojson.org/v6/how-to/configure-the-serialization-of-floats/
In the folowing small example it is possible to write to the Json file a double value with 2 decimal point.
#include <ArduinoJson.h>

double round2(double value) {
  return (int)(value * 100 + 0.5) / 100.0;
}

double round3(double value) {
  return (int)(value * 1000 + 0.5) / 1000.0;
}

double var1 = 1.23456789;
double var2 = 5.05599991;

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

  StaticJsonDocument<200> doc;
  doc["hello"] = "world";
  doc["var1"] = round2(var1);
  doc["var2"] = round3(var2);

  serializeJsonPretty(doc, Serial);

}

In my sketch right now i am able to create the Json Array with the values read from a Analog input. Only the created Json Array have 9 decimal points. I do not know how to implement in my sketch, folowing the aboth example that the values inside the Json array have only two decimal points.
Follow my sketch.
#include <ArduinoJson.h>

#define ADC_Range_Pin  35  // Pin Range Sensor

unsigned long scale_previousMillis = 0;
const long scale_interval = 100; // Interval
const byte NUM_SAMPLES = 20;
double buffer_range [NUM_SAMPLES];

// Range Sensor Instanzen-----------------------------
double Current_range = 0; //4-20 mA
double rawADCValue_range = 0;
double ADCVoltage_range = 0; //0-3,3 V
double range = 0; //0-50mm
unsigned long range_t;

double mapfloat(double x, double in_min, double in_max, double out_min, double out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

double round_range(double value) {
  return (int)(value * 100 + 0.5) / 100.0;
}

void Read_Scale() {

  StaticJsonDocument<1000> doc;

  static int scale_counter = 0;

  if (millis() - scale_previousMillis >= scale_interval) {
    scale_previousMillis = millis();

    rawADCValue_range = 0;
    for (int i = 0; i < 100; ) {
      if (millis() - range_t  >= 1) {
        rawADCValue_range += analogRead(ADC_Range_Pin);
        i++;
        range_t = millis();
      }
    }

    ADCVoltage_range = (double)(rawADCValue_range / 100.0) * (3.3 / 4095.0);
    Current_range = mapfloat(ADCVoltage_range, 0.8, 3.3, 4, 20);
    range = mapfloat(Current_range, 4, 20, 0, 50);

    buffer_range[scale_counter] = range ;

    scale_counter ++;

    JsonArray rangeValues = doc.createNestedArray("Range");

    if (scale_counter >= NUM_SAMPLES)
    {
      for (int i = 0; i < NUM_SAMPLES; i++) {
        rangeValues.add (buffer_range[i]);
      }

      serializeJson(doc, Serial);
      Serial.println();
      scale_counter = 0;
      Serial.println();

    }
  }
}

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

void loop() {
  Read_Scale();
}

You defined the rounding function round_range(), but never used it.
You want to round the numbers that you are putting into the array within
the JSON document:
rangeValues.add(round_range(buffer_range[i]));


text:
How to print something when a character touches a character
I am making a stickman rush game, where it goes up and down and then there is a object that scrolls to the left. Whenever that stickman touches the object, it prints game over. However when the object is below the stickman, it prints game over even though its not touching. Can someone explain why this is happening?
Code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

byte customChar[] = {
  B01110,
  B01110,
  B01110,
  B00100,
  B01110,
  B10101,
  B00100,
  B01010
};

byte gameObstical[] = {
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111
};

int vX = A0;
int vY = A1;
int sw = 8;

int xPosition = 0;
int yPosition = 0;
int SW_state = 0;
int mapX = 0;
int mapY = 0;

int screenWidth = 16;
int screenHeight = 2;

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

  pinMode(vX, INPUT);
  pinMode(vY, INPUT);
  pinMode(sw, INPUT);

   lcd.begin(16, 2);
  lcd.createChar(0, customChar);
  lcd.home();
  lcd.write(byte(0));

  lcd.createChar(1, gameObstical);
  lcd.write(byte(1));

}

void loop() {

  int stickManPosition = 0;
  int obsticalPosition = 0;
  int stickManPosition2 = 0;
  int obsticalPosition2 = 0;

  for (obsticalPosition = 15; obsticalPosition >= 0; obsticalPosition--) {
  lcd.setCursor(obsticalPosition, 1);
  lcd.write(byte(1));
  lcd.print(" ");
  delay(150);

  xPosition = analogRead(vX);
  yPosition = analogRead(vY);
  SW_state = digitalRead(sw);
  mapX = map(xPosition, 20, 1003, -500, 500);

    Serial.println("-----------");
  Serial.println(mapX);
  Serial.println("-----------");

    if (mapX > 200) {

    lcd.clear();
    lcd.setCursor(stickManPosition, 0);
    lcd.write(byte(0));

  } else if (mapX < -200) {

    lcd.clear();
    lcd.setCursor(stickManPosition, 1);
    lcd.write(byte(0));
    }

  if (stickManPosition == obsticalPosition) {
    lcd.clear();
    lcd.print("Game Over.");
      } else if (
    }
  }

Any help would be great.

Your code says to print Game Over if stickManPosition == obsticalPosition, so it is doing exactly that. You need to save what row the stick and obstacles are on and compare that too.

I dont know how to do that.. Can you give me an example?

You check StickMan and Object only X position not check Y position
incase you can check StickMan Y or check StickMan action like this code below.
or try this sim https://www.tinkercad.com/things/1LiyoY5n1mS-copy-of-stickman-rush/editel?sharecode=X6rMj1GjrKoAH95qWKY21z98ttyAs5aOTAKYy6hVJ3c
// Defind it on top
bool stickManIsJump = false;

// Added some code to check StickMan isJump or not
if (mapX > 200) {
  lcd.clear();
  lcd.setCursor(stickManPosition, 0);
  stickManIsJump = true;        /////////////// ADDED
  lcd.write(byte(0));
} else if (mapX < -200) {
  lcd.clear();
  lcd.setCursor(stickManPosition, 1);
  stickManIsJump = false;       /////////////// ADDED
  lcd.write(byte(0));
}

if (stickManPosition == obsticalPosition && !stickManIsJump) {      /////////////// ADDED
  lcd.clear();
  lcd.print("Game Over.");
}


text:
MCU Recommendations for Audio Pitch Shifting
I'm looking to use a MCU for audio sampling. I want to sample incoming audio and pitch shift it (without speeding it up/slowing it down). A bit about the build. I'm planning to make a circuit board that can take in a single audio source and output three or four different pitch-shifted sounds in real time, with each output being its own pitch-shifted sound. If possible, I would like to have a potentiometer for each output that could in effect change how pitch shifted each output is, sort've of like a tuning knob. These outputs will eventually get summed together to produce a chord-like sound.
I'm not quite sure what exact requirements are needed for this, just that the sampling rate should be around 44KHz (standard audio sampling rate). Of course, I would like the outputs to replicate the original sound as much as possible, just pitch-shifted. I am assuming as well that the way I pitch-shift and sample could affect the requirements. Also, I would like to avoid SMT if I can.
Given these requirements, what do you suggest the best MCU to use is? I would like to use Arduino to program the MCU. I really only need the chip itself (I think?), as I plan to create a separate circuit board for this (although would I need an Arduino board to initially program the chip?)
I'm fairly new to the Arduino world, so apologies in advance if I miss something obvious or mess up terminology. I do come from a background in analog circuitry and programming though. Just looking for as much help as I can get from people who know more than me but am eager to learn about this all.
Thanks!

I don't know exactly what MCU would suit best, but forget about an Arduino Uno, Nano, Micro or Mega. Maybe a Due would be suitable. Also you need external ADCs and DACs as the internal ADCs are 10 bit only. Beyond that the CPU speed of a 16 MHz typical Arduino is probably not enough for the (probably?) massive number crunching need for pitch shifting.

I'd suggest the Teensy 4.0 - you're going to need lots and lots of processing power.

use a rasp pi for that, it's going to be WAY easier and more flexible for relatively complex processing.

What kind of ADC resolution are you aiming at?

I get the impression that you haven't done this sort of thing before, on any scale. Pitch shifting is a totally non-trivial process.  I suggest you start out on a regular computer and try to get a single channel working to your satisfaction.  Then, if you are still determined to do this on a smaller system, you will at least know what you are up against and will be able to decide what systems are appropriate.  Sorry if it sounds like I'm trying to throw cold water on your idea, because I'm sure it would be a fun instrument to play.  But I think you would be getting in way over your head if this isn't already your field of expertise.

Thank you for the advice @Boggyman , I appreciate the honesty. I am starting to realize that what you've said is indeed the correct way to go about it, as I want to be able to understand the process fully once I implement it. Nothing wrong with some learning! :)


text:
Arduino NRF24LO1
I have a problem with transmiter (Arduino uno) and receiver (Arduino nao). When I am trsmiting that I receive that:
An this is my code for receiver
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN  7
#define CSN_PIN 8

const byte thisSlaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN);

char dataReceived[10]; // this must match dataToSend in the TX
bool newData = false;

//===========

    void setup() {

        Serial.begin(9600);

        Serial.println("SimpleRx Starting");
        radio.begin();
        radio.setDataRate( RF24_250KBPS );
        radio.openReadingPipe(1, thisSlaveAddress);
        radio.startListening();
    }

    //=============

    void loop() {
        getData();
        showData();
    }

    //==============

    void getData() {
        if ( radio.available() ) {
            radio.read( &dataReceived, sizeof(dataReceived) );
            newData = true;
        }
    }

    void showData() {
        if (newData == true) {
            Serial.print("Data received ");
            Serial.println(dataReceived);
            newData = false;
        }
    }

and transmitter
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN  7
#define CSN_PIN 8

const byte slaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char dataToSend[10] = "Message 0";
char txNum = '0';

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleTx Starting");

    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
}

//====================

void loop() {
    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {
        send();
        prevMillis = millis();
    }
}

//====================

void send() {

    bool rslt;
    rslt = radio.write( &dataToSend, sizeof(dataToSend) );
        // Always use sizeof() as it gives the size as the number of bytes.
        // For example if dataToSend was an int sizeof() would correctly return 2

    Serial.print("Data Sent ");
    Serial.print(dataToSend);
    if (rslt) {
        Serial.println("  Acknowledge received");
        updateMessage();
    }
    else {
        Serial.println("  Tx failed");
    }
}

//================

void updateMessage() {
        // so you can see that new data is being sent
    txNum += 1;
    if (txNum > '9') {
        txNum = '0';
    }
    dataToSend[8] = txNum;
}

Do you see an error?


text:
Rosserial. Arduino Publishing custom msg (6 float64 values and header) and subscribe Vector3Stamped msg from Arduino mega2560 is not working!
Rosserial Arduino custom msg publisher. I am publishing custom msg (6 float64 values and header) and subscribe Vector3Stamped msg from Arduino mega2560. But is not working!
The error I get is the following (the custom publisher is publishing correctly but the usual subscriber is not working):

Creation of subscriber failed: need
more than 1 value to unpack

When I have the following in Arduino/libraries/Rosserial_Arduino_Library/src/ros.h
 #elif defined(__AVR_ATmega2560__)
       typedef NodeHandle_ <ArduinoHardware, 15, 15, 512, 512> NodeHandle

while the error is different when changing Arduino/libraries/Rosserial_Arduino_Library/src/ros.h to the following:
#elif defined(__AVR_ATmega2560__)
   typedef NodeHandle_<ArduinoHardware, 15, 15, 512, 512,FlashReadOutBuffer_> NodeHandle;

The error I get in this case is the folowing (the custom publisher is not working but the usual subscriber is working)

Creation of publisher failed: need
more than 1 value to unpack
Tried to
publish before configured, topic id
115

My arduino code is the following:
#include <HardwareSerial.h>
#include <ODriveArduino.h>
#include <Wire.h>
#include <ros.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Vector3Stamped.h>
#include <geometry_msgs/Twist.h>
#include <ros/time.h>
#include <mybot/encoderMsgStamped.h>

#define ROBOT_WIDTH (480) //MILLI METER
#define WHEEL_DIAMETER (165.1)  // MILLI METER
#define WHEEL_CIRC (518.676947108) //circumference OF THE WHEEL
#define CPR_ENCODER (90)

HardwareSerial& odrive_serial1 = Serial1;
HardwareSerial& odrive_serial2 = Serial2;
HardwareSerial& odrive_serial3 = Serial3;
//axis0(M0)-left
//axis1(M1)-right
ODriveArduino odrive1(odrive_serial1);
ODriveArduino odrive2(odrive_serial2);
ODriveArduino odrive3(odrive_serial3);

// cmd_vel variables to be received to drive with
float demandx;
float demandz;

// timers for the sub-main loop
unsigned long currentMillis;
long previousMillis = 0;    // set up timers
float loopTime = 100;  //100ms
long forward0;
long forward1;
long turn0;
long turn1;

// position and velocity variables read from the ODrive
long posfl,posfr,posml,posmr,posrl,posrr;

long posfl_old,posfr_old,posml_old,posmr_old,posrl_old,posrr_old;
long posfl_diff,posfr_diff,posml_diff,posmr_diff,posrl_diff,posrr_diff;
float posfl_mm_diff,posfr_mm_diff,posml_mm_diff,posmr_mm_diff,posrl_mm_diff,posrr_mm_diff;

ros::NodeHandle nh;

//function that will be called when receiving command from host
void handle_cmd (const geometry_msgs::Twist& cmd_vel) {

     demandx = cmd_vel.linear.x;
     demandz = cmd_vel.angular.z;
}

ros::Subscriber<geometry_msgs::Twist> cmd_vel("/cmd_vel", handle_cmd);   //create a subscriber to ROS topic for velocity commands (will execute "handle_cmd" function when receiving data)
mybot::encoderMsgStamped pos_msg;                                //create a "pos_msg" ROS message
ros::Publisher pos_pub("encoderPos", &pos_msg);                          //create a publisher to ROS topic "encoderPos" using the "pos_msg" type

void setup() {
  nh.initNode();                            //init ROS node
  nh.getHardware()->setBaud(115200);         //set baud for ROS serial communication
  nh.subscribe(cmd_vel);                    //suscribe to ROS topic for velocity commands
  nh.advertise(pos_pub);                  //prepare to publish speed in ROS topic
  odrive_serial1.begin(115200);
  odrive_serial2.begin(115200);
  odrive_serial3.begin(115200);
  odrive1.SetVelocity(0,0);
  odrive1.SetVelocity(1,0);
  odrive2.SetVelocity(0,0);
  odrive2.SetVelocity(1,0);
  odrive3.SetVelocity(0,0);
  odrive3.SetVelocity(1,0);
  odrive1.SetPosition(0,0.0);
  odrive1.SetPosition(1,0.0);
  odrive2.SetPosition(0,0.0);
  odrive2.SetPosition(1,0.0);
  odrive3.SetPosition(0,0.0);
  odrive3.SetPosition(1,0.0);
  Serial.begin(115200);
  while (!Serial) ;

}

//_________________________________________________________________________

void loop() {
  nh.spinOnce();
  currentMillis = millis();
  if (currentMillis - previousMillis >= loopTime) {  // run a loop every 100ms
     previousMillis = currentMillis;          // reset the clock to time it
     float modifier_lin = 1.03;        // scaling factor because the wheels are squashy / there is wheel slip etc.
     float modifier_ang = 0.92;        // scaling factor because the wheels are squashy / there is wheel slip etc.

     forward0 = demandx * 1.927982351202 * modifier_lin ; // convert m/s into counts/s
     forward1 = demandx * 1.927982351202 * modifier_lin; // convert m/s into counts/s
     turn0 = demandz * 0.46271576428  * modifier_ang;    // convert rads/s into counts/s
     turn1 = demandz * 0.46271576428 * modifier_ang;    // convert rads/s into counts/s

     forward1 = forward1*-1;      // one motor and encoder is mounted facing the other way
     odrive1.SetVelocity(1, forward0 + turn0); //-1 the motors are on opposite direction
     odrive1.SetVelocity(0, forward1 + turn1);
     odrive2.SetVelocity(1, forward0 + turn0); //-1 the motors are on opposite direction
     odrive2.SetVelocity(0, forward1 + turn1);
     odrive3.SetVelocity(1, forward0 + turn0); //-1 the motors are on opposite direction
     odrive3.SetVelocity(0, forward1 + turn1);

    // get positions from ODrive
    posfr = odrive3.GetPosition(1) *-1;
    posfl = odrive3.GetPosition(0);

    posmr = odrive2.GetPosition(1) *-1;
    posml = odrive2.GetPosition(0);

    posrr = odrive1.GetPosition(1) *-1;
    posrl = odrive1.GetPosition(0);

    // work out the difference on each loop, and bookmark the old value
    posfl_diff = posfl - posfl_old;
    posfr_diff = posfr - posfr_old;
    posfl_old = posfl;
    posfr_old = posfr;

    posml_diff = posml - posml_old;
    posmr_diff = posmr - posmr_old;
    posml_old = posml;
    posmr_old = posmr;

    posrl_diff = posrl - posrl_old;
    posrr_diff = posrr - posrr_old;
    posrl_old = posrl;
    posrr_old = posrr;

    // calc mm from encoder counts
    posfl_mm_diff = posfl_diff /0.1735184116;
    posfr_mm_diff = posfr_diff /0.1735184116;

    posml_mm_diff = posml_diff /0.1735184116;
    posmr_mm_diff = posmr_diff /0.1735184116;

    posrl_mm_diff = posrl_diff /0.1735184116;
    posrr_mm_diff = posrr_diff /0.1735184116;

     publishPos();
  }
 }

void publishPos() {
  pos_msg.header.stamp = nh.now();      //timestamp for odometry data
  pos_msg.fl = posfl_mm_diff;
  pos_msg.ml = posml_mm_diff;
  pos_msg.rl = posrl_mm_diff;
  pos_msg.fr = posfr_mm_diff;
  pos_msg.mr = posmr_mm_diff;
  pos_msg.rr = posrr_mm_diff;
  pos_pub.publish(&pos_msg);

}

Note: With usual publish and subscribe msgs and the following Arduino/libraries/Rosserial_Arduino_Library/src/ros.h everything works fine for both publishing and subscribing:
 #elif defined(__AVR_ATmega2560__)
 typedef NodeHandle_<ArduinoHardware, 15, 15, 512, 512,FlashReadOutBuffer_>  NodeHandle;

What is it that's actually responsible for producing the Creation of subscriber failed message?

write a simple sketch that publishes one fixed message

For what it's worth, avr-gcc implements its double type as a single precision, 32-bit float.  This may be a problem for your use of float64, irrespective of whatever problem you're encountering now.


text:
Sending data to server
I have an SD card have a very big file (1M character). i try to load it into memory in terms of 4K character array ( The maximum I could do using Arduino Mega). but this take almost 250 call to the server. And this is too much. Is there any way better to do it. I am using firebase as my server and i am touching the limit and this is inacceptable to the stability of the program

So I guess you are using an ESP8266 with AT firmware for Wifi connection? Or do you use an ethernet shield?

client.write(file); doesn't work?

@chrisl I use SIM800L

@Juraj I guess this is not available i use micro sd interface and SIM800L and there is no such function as you mentioned

I don't think, that you can get around the 4k limitation with this hardware. Is the number of calls the problem, or the time needed for doing the whole transmission?

@chrisl Both are problems

please post your code ... overwrite any sensitive information

I doubt that the GSM can send data in such large chunks. on TCP networks data are send in 1.5kB packets. so I doubt making the buffer larger will help. it is simply how things are done: read buffer, write buffer until everything is copied. I guess the optimal buffer size will be 512 bytes or less

@Juraj Ok, Is there any better solution to send data to servers in this large chunks?

better? put the SD card in a computer

I need to send data periodically and automatically


text:
Motors not working with a motor Shield
Got a Duratech motor shield today, and I'm wondering why my motors do not run. Appreciate any help. The code I am using is the Adafruit sample code, Motorparty. The servos work however the motors do not.
Here is a photo of my setup, code is below:

/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438

This sketch creates a fun motor party on your desk *whiirrr*
Connect a unipolar/bipolar stepper to M3/M4
Connect a DC motor to M1
Connect a hobby servo to SERVO1
*/

#include <Wire.h>
#include <Servo.h>
#include <Adafruit_MotorShield.h>

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Connect a stepper motor with 200 steps per revolution (1.8 degree)
// to motor port #2 (M3 and M4)
Adafruit_StepperMotor *myStepper = AFMS.getStepper(200, 2);
// And connect a DC motor to port M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(3);

// We'll also test out the built in Arduino Servo library
Servo servo1;

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("MMMMotor party!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Attach a servo to pin #10
  servo1.attach(10);

  // turn on motor M1
  myMotor->setSpeed(200);
  myMotor->run(RELEASE);

  // setup the stepper
  myStepper->setSpeed(10);  // 10 rpm
}

int i;
void loop() {
  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, FORWARD, INTERLEAVE);
    delay(3);
 }

 for (i=255; i!=0; i--) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, BACKWARD, INTERLEAVE);
    delay(3);
 }

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, FORWARD, DOUBLE);
    delay(3);
 }

  for (i=255; i!=0; i--) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, BACKWARD, DOUBLE);
    delay(3);
 }
}

You can try to replace the motor with an LED and a resistor. This way you can check, if there is at least something coming out (the LED will only light up in one drive direction). Also you can try measuring the voltage with a multimeter. From the picture I cannot really see, how everything is connected. Please provide a schematic or wiring diagram


text:
Stm32 Blue Pill Internal reference voltage Arduino IDE
I want to use the internal reference voltage (1.2V) of stm32f103 blue pill using Arduino IDE. I searched the whole internet but couldn't find anything. I need help with this. Thanks.

Did the whole internet include the datasheet for the chip?

Link to the core you're using, please. It should implement analogReference(INTERNAL) or something similar.

Maybe this will help a little: http://www.efton.sk/STM32/STM32_VREF.pdf (usualy it can be used to compute VREF+ or VDDA, as it can't be used directly as ADC reference)

And (different family, but it should be similar) https://community.st.com/s/question/0D50X00009XkePgSAJ/use-adc-with-internal-vref-stm32l151

There's no way of using the internal 1,2v reference as the ADC reference. (in the same way that you can do on an AVR)
You can only use the ADC to read the internal vref, and use that value to adjust the next ADC reading you take. Like a compensation factor.


text:
Millis timer question
Trying to figure out how to do this in millis. So right now the code works just fine, plays mp3_play(2) while a push button is closed then plays mp3_play(1) when its open. Lets say I want mp3_play(2) to play while the push button closed but after 4 seconds if the button is still closed another audio file will be triggered to play. Cant figure that one out.
thanks
Jason
void fire(){

  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {

    if (reading != buttonState) {
      buttonState = reading;

      if (buttonState == HIGH) {
        mp3_play (1); //power down sound
      }

      if (buttonState == LOW) {
        mp3_play (2);  // fire sound
      }

    }
  }
  lastButtonState = reading;
}

Do you want to keep playing the other audio if it is past 4 seconds? or just once?

Hi, if the 3rd audio file could play once, that would be great. Thanks

You have to keep track of time once a button is pressed (LOW). So buttonLowTime is initialized every time you press the button. In the if logic, you first check if the buttonstate is LOW and if the said time has been passed.
But you also mentioned you want to play the audio once. So you need to keep track if you already played the audio. So, a flag, timeoutAudioPlayed has been created to keep track of that. So, now, the 3rd audio will only play if:

The button is pressed
and is pressed for more than said time (BUTTON_LOW_TIME_MAX)
and if the audio hasn't been played.

void fire()
{
  static int buttonLowTime = 0; <-------------------
  static bool timeoutAudioPlayed = true; <---------

  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState)
  {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay)
  {
    if (reading != buttonState)
    {
      buttonState = reading;

      if (buttonState == HIGH)
      {
        mp3_play (1); //power down sound
      }

      if (buttonState == LOW)
      {
        mp3_play (2);  // fire sound
        buttonLowTime = millis(); <-----------
        timeoutAudioPlayed = false; <---------
      }
    }
  }

  // The logic for timeout audio <------------
  if((buttonState == LOW) && (millis() - buttonLowTime) > BUTTON_LOW_TIME_MAX && timeoutAudioPlayed == false)
  {
    mp3_play (3);
    timeoutAudioPlayed = true;
  }

  lastButtonState = reading;
}

Great, I really appreciate it. Thanks

Thanks for the help Fahad. One little issue after trying the code, its works great for a few times, then it only plays the (3) file with a button press and not the (2) anymore.

I can just speculate the reason. I changed the timeout logic, from lastButtonState to buttonState. Because lastButtonState is true even without going through the debounce check. I updated the code above. Let me know if that works.

Unfortunately it still has the same problem, works a few times as intended, then breaks. Thanks Fahad

I changed static int buttonLowTime to static long buttonLowTime and it seems to be working fine now.

Oh, my bad. It should have been long, and NOT int. Good catch!

thanks again...


text:
Http request in interrupt esp8266 not working
So i have this code that whenever i click a button a interrupt starts.
In this interrupt i want to do a get request to a webserver.
The thing is seperate the code, the interrupt code works and without an interrupt the http request also works.
But when i put this together it doesn't.
Does anybody have an idea why this doesn't work?
// Libraries
#include <ESP8266HTTPClient.h>
#include<ESP8266WiFi.h>

char ssid[] = "";
char pass[] = "";

int ledpin = 5; // D1(gpio5)
int button = 4; //D2(gpio4)
int buttonState=0;

ICACHE_RAM_ATTR void ISR() {
  static unsigned long last_interrupt_time = 0;
  unsigned long interrupt_time = millis();

  if (interrupt_time - last_interrupt_time > 200)
  {
      Serial.println("Drukknop ingedruk");
      Serial.println("Sending message to server");
       if (WiFi.status()==WL_CONNECTED)
      {
        HTTPClient http;
        String url="<httpurl>";
        http.begin(url);
        http.addHeader("Content-Type","text/plain");
        int httpCode=http.GET();
        Serial.println(httpCode);
        String payload=http.getString();
        Serial.println("While sending I received this from server : "+payload);
        http.end();
      }
      else
      {
        Serial.println("Internet Problem!");
      }
  }
  last_interrupt_time = interrupt_time;
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid,pass);

  while(WiFi.status() !=WL_CONNECTED)
  {
    delay(500);
    Serial.println("Waiting for connection");
  }

  Serial.println("Connected...");
  delay(1000);
  if (WiFi.status() ==WL_CONNECTED)
  {
    Serial.println("Wi-Fi Connected!");
  }
  delay(5000);
  Serial.println("ok");
  pinMode(button, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), ISR, RISING);

}
void loop() {

}

Doing something as complex as a HTTP request in an interrupt is a very very silly idea. Instead set a flag in the interrupt routine and examine that in the main loop() function to perform your HTTP request.

Thank you, this works

@ThomasVanRaemdonck if it works (and it should) please accept Majenko's answer as correct; that helps other users see the correct answer and gives Majenko credit.


text:
Using PortB as a sink, not working
Out of ideas here, i try using PB0-3 as sinks for a LED matrix and the pins just won't sink.
My test code:
void setup() {
  //bitClear(SPCR, 6);
  pinMode(PD5, OUTPUT);

  pinMode(PB0, OUTPUT);
  pinMode(PB1, OUTPUT);
  pinMode(PB2, OUTPUT);
  pinMode(PB3, OUTPUT);

  digitalWrite(PB0, LOW);
  digitalWrite(PB1, LOW);
  digitalWrite(PB2, LOW);
  digitalWrite(PB3, LOW);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(PD5, HIGH);
  delay(1000);
  digitalWrite(PD5, LOW);
  delay(1000);
}

(Using bog standard Blink as a starting point for tests)
My controller is an ATMega328P programmed using USBaspLoader on my own PCB.
If i connect the physical pin that should be sinking with a piece of wire to ground the LED starts blinking, so the "sending" part seems to work but the "receiving" part doesn't.
As you can see i tried manually disabling the SPI port, no luck either.
I tried different controllers, among them a good old ATMega8-16, nothing seems to work.
I even breadboarded a test circuit but no luck, PortB wont sink.

Why are you using the likes of PB3 with digitalWrite() etc?

PB3 etc don't refer to Arduino pins. Instead they refer to the bits in the internal registers.
To use digitalWrite() etc you must use Arduino pins not internal register bit numbers.
The pin to port/bit mapping is defined by what board you have selected, and if you want to look it up you should examine the pins_arduino.h file for your selected board.

Thanks, i thought, because the compiler wasn't complaining, that they where defined as such. Is there some way to look at the intermediate code?

You mean the assembly code? You can disassemble the elf file with avr-objdump -S I guess, but that's probably not of any help to you.  In general PBx is defined as x (PB3 is defined as 3) and is intended to be used as PORTB |= (1 << PB3).


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:
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.


text:
Ultrasonic Sensor as Unlock Sensor
Is it possible to use ultrasonic sensors maybe HC SR04 type as unlock sensors? I'm figuring out if it can replace matrix keypad?
For example 6 HC SR04 are used to be an input sensor waiting for a pattern to unlock a certain thing? Usually, in matrix keypad we will push [ 6,0,1,7] as the password is it possible to replace that with ultrasonic sensors as the receiver of input, and if it i possible, what type of code to be used?

I guess you can make it so that when anyone stands in front of it then it unlocks but that doesn’t make it very secure.

Short answer: yes.
General answer: you can use any input device for use as unlock mechanism. You can use a keypad, several single buttons, you can even use a single ultrasonic sensor (and depending on the distance differences from that sensor create a pattern), you can use a microphone, a temperature sensor (that will be tricky to unlock something though).
I would start with a typical example of an ultrasonic sensor sketch and program a pattern recognition algorithm in it. How that sketch would look like exactly, depends on your requirements (how you want to store the pattern, should it be hardcoded or changeable).
First try one sensor, than try multiple (I never tried, but I guess it's possible). If not by a default library, you have to write your own (that will be tricky possibly). Than think about the pattern recognition (values of the ultrasonic sensor in the correct order), than about changing/storing the 'code'.


text:
Finding address of OLED using I2C communication and Arduino
It is known that address of OLED SSD1306 is 3C. The frame format is as follows:

The figure implies that the binary pattern should be 01111000 for the first frame (considering write mode and the second last bit is a dont care).
So I was trying to send the first frame using Wire.h library. The following is a code
Wire.beginTransmission(0b01111001);
But i receive a nack (return value of 2)
However, If I send 00111100, i receive a ack(return value of 0). What is wrong in my interpretation?

You should scan the bus, maybe the display has a different address. You can use this sketch: https://playground.arduino.cc/Main/I2cScanner/

I referred to this link. It shows the address is 3c but that should not be the case because the above pic is of ssd1306 datasheet

You misinterpret how the Wire library is used. Though the first byte in the transmission is called the address byte, the actual address consists only of the 7 higher bits in that byte. The direction bit is not in the address.
So the Wire.beginTransmission() method wants the address as parameter, without the direction bit. That bit is set corresponding to the used function (0 for Wire.beginTransmission() and 1 for Wire.requestFrom()).
0b0111100 is the real address (when connnecting the address pin to ground)(note, that there are only 7 bits, since the address only has 7 bits). The write operation address byte will then be 0b01111000, though the library is hiding that way from you. You need to provide the 7 bit address to the function.

the second last bit is a dont care

As mentioned above, that is not correct. This bit (the least significant bit of the address) is set by the address pin SA0. It seems, that you have it tied to ground, which sets the corresponding bit in the address to zero. If you would tie it to Vcc, it would be 1.

I understand where I was wrong. Thank you. However, I have one more question. How do I send the read/write bit??

@shivamag000 as chrisl wrote you don't manually send it. The read/write bit is automatically handled by Wire.startTransmission() (clears the bit to address the slave in write mode) and Wire.requestFrom() (sets the bit to address the slave in read mode). It's important to only use the 7-bit address, preferably in another format than binary, which can be a bit confusing

Yes, the data direction bit is handled by the library. When you use the write functions (Wire.beginTransmission() and Wire.endTransmission()) it will use zero for the direction bit. If you use the read function Wire.requestFrom(), it will use 1 for the direction bit.

Also keep in mind, that the actual transmission is done in Wire.endTransmission(). Before that no data will be transmitted.

Thank you @chrisl

I2C has a 7-bit address space. The device's actual address is 0b0111100 (=0x3c). The sequences 0b01111001 and 0b01111000 address the same slave while the first one (least significant bit is 1) starts a read transmission, the second one starts a write transmission.
Those least significant bits are nothing you need to care about when using Wire.h: the mode of operation is automatically set when using Wire.startTransmission(addr) (returns 0 when slave ACK'ed write command) and Wire.requestFrom(addr) (returns 0 when slave ACK'ed read command).

Even if I send 0b01111000, a nack is received

@shivamag000 that's not what you wrote in your question ("However, If I send 00111100, i receive a ack") and a return value of 0 means that the slave ACK'ed

@shivamag000 also, 0b01111000 is not what you are supposed to pass to Wire.beginTransmission(). It takes the 7-bit address. You better don't mess with binary format, simply do Wire.beginTransmission(0x3c)...

can you please show the reference where it says that wire.begin takes seven bit addresses

@shivamag000 https://www.arduino.cc/en/Reference/WireBeginTransmission

Thank you @Sim son


text:
Arduino program using i2c stops working after printing to OLED a few times
A NOTE ON THE PROJECT AND PROGRAM STRUCTURE
I am developing an open source Smart Watch project using Arduino.
The code can be found here: https://github.com/shivangsgangadia/SmartWatch
The code is too large and divided into multiple files, hence I cannot paste it here within the question, hence I request you to look into the github repo.
So far I have interfaced an OLED (128 X 64 SSD1306) and RTC (DS3231 in ZS-042).
I have written libraries for both, which have been included in Github repo.
The program structure allows to add multiple "Modules" which are basically like apps. There is a static State class that holds the program state such as modules to be serviced, and time from RTC.
Each "Module" can be a "App" or "Overlay". Overlays are always visibles, there can be mutiple overlays active, but only 1 app can exist at a time.
WHAT I AM TRYING TO DO ?

Read RTC into State class's static variables
Display once
Attach interrupt to set boolean flag when the RTC gives interrupt (alarm
set to 1 minute) Service interrupt in loop by:

Read RTC into State class's static variables
Reset alarm for RTC
Update display

WHAT IS THE PROBLEM ?
The program works fine 2-3 times, i.e. does what's expected after servicing 2-3 interrupts (hence 2-3 minutes), but after that the print on the OLED becomes mangled and the program stops altogether.
WHAT HAVE I TRIED TO SOLVE IT ?
With Serial.println() in many areas such as before and after OLED::writeString is called in respective classes, I concluded that the RTC is not the issue, but the OLED somehow causes the program to stop.
Removing OLED::writeString statements does allow the rest of the printing to continue for more than 2-3 times, but the program eventually does stop. I have tried replacing the wires and the breadboard, but nothing seems to have any effect.

I can't see anything immediately obvious (kudos to you for your tidy programming style and your lack of anything String related). Chances are it's the I2C communication. It's not great over wires or with breadboards. You can try adding smaller (1kΩ) pullup resistors on the I2C wires.

Thanks for the compliment ! I tried adding 1k pullups and passing the OLED connections through the ZS04 module's extra pinouts and it still doesn't work.

This is wrong in many ways:
String input = Serial.readString();
serialInputBuffer = new char[input.length()];
input.toCharArray(serialInputBuffer, input.length());

What's fatal is that you later don't free the memory allocated with new. Don't use String and new. Both use heap memory and will fragment it with these small allocations until there is no space for the next allocation. I see you have dynamic allocation in other parts of the sketch and there it looks like you have a delete, but they still cause the fragmentation problem.
Use a global buffer like char serialInputBuffer[64]; and use:
int l = Serial.readBytes(serialInputBuffer, sizeof(serialInputBuffer));
serialInputBuffer[l] = 0;

In the scale function, there is a dynamically allocated array. Replace it with a class variable, which acts as a buffer which can hold the maximum number of bytes you expect the use to scale their byte to.
Again, dynamic allocations will cause fragmentation even if the memory is released properly.

I have tried commenting out the whole Serial piece, and it still has no effect.

@ShivangGangadia, you have multiple dynamic  allocations in other parts of the sketch and there it looks like you have a delete, but they still cause the fragmentation problem.

I replaced all dynamic allocations with statics within modules. Still, has no effect at all

@ShivangGangadia, why do you use pgm_read_word to read bytes?

Because the bytes that I need, that is font, are in PROGMEM

@ShivangGangadia, pgm_read_byte?

@ShivangGangadia, you allocate toReturn in scale many times but you don't delete it. (only the last one in writeString)

You were right ! I though I could get away with just one dynamic allocation, but embedded systems are really unforgiving. Please review and approve the edits I have requested so that I can acccept this as the correct answer.

Don't use the Wire library.  If you look closely at twi.c, you'll find it has blocking calls with (potentially) infinite loops.  Eventually a condition will occur that causes one of the blocking calls to hang forever.
See this post and this post for details
Use something like SBWire
Frank

I replaced the Wire library with SBWire. Still no improvement.

OK, so now you are back to basic troubleshooting.  Temporarily abandon your project, and create a new one with just the Arduino and the OLED - nothing else - and the simplest possible code to drive it.

Once you have this simple project working, you'll know right away if the OLED and it's driver are the problem

Did the step by step, will accept the answer by Juraj


text:
Making a Bluetooth Mouse with Arduino
I'm trying to make a bluetooth mouse using Arduino. I will be using an analog 2 axis thumbstick as the sensor. I understand that it's possible to do this with the Arduino connected directly to the computer (https://www.arduino.cc/reference/en/language/functions/usb/mouse/). Would it be possible for the arduino to instead communicate wirelessly using bluetooth? The controller I'm interested in is here: https://www.dfrobot.com/product-1259.html
Thank you!

With that specific board, yes you can.  According to this review:

Bluno also supports the HID (Human Interface Device) mode. When running in this mode, Bluno simulates an input peripheral (keyboard, mouse…) connected via BLE.


text:
Debugging RN 42 HID Mouse
I'm trying to use the RN 42 and Arduino Uno to control a bluetooth mouse. I configured the RN 42 with the commands S~,6 and SH,0220 and R,1 to put the device in HID mouse mode. Is there anything I missed? Below is the sketch I am using to send mouse reports to the bluetooth. The sketch compiles fine, but moving the joystick does not move the cursor. I included a line of code at the end to print on the serial port whatever data is being sent through software serial to the bluetooth. However when I view the serial monitor, I get back a lot of reversed question marks. Anyone know why this is? Thanks in advance.

const int bluetoothTx = 4;    // TX pin of RN-42, Arduino D2 (configure as RX pin of Ard)
const int bluetoothRx = 3;    // RX pin of RN-42, Arduino D3 (configure as TX pin)
const int button = 5;
const int xAxis = A0;         // joystick X axis
const int yAxis = A1;         // joystick Y axis
int range = 12;               // output range of X or Y movement
int responseDelay = 5;        // response delay of the mouse, in ms
int threshold = range / 4;    // resting threshold
int center = range / 2;       // resting position value

SoftwareSerial BT(bluetoothTx, bluetoothRx); // args SoftwareSerial(RXpin, TXpin)

void mouseCommand(byte buttons, byte x, byte y) {
  BT.write((byte)0xFD);
  BT.write((byte)0x05);
  BT.write((byte)0x02);
  BT.write((byte)buttons);
  BT.write((byte)x);
  BT.write((byte)y);
  BT.write((byte)0x00);
}

int readAxis(int thisAxis) {
  // read the analog input:
  int reading = analogRead(thisAxis);

  // map the reading from the analog input range to the output range:
  reading = map(reading, 0, 1023, 0, 12);

  /* threshold prevents the mouse from reading small unintentional movements.
  If the output reading is outside from the rest position threshold, use it: */
  int distance = reading - center;

  if (abs(distance) < threshold) {
    distance = 0;
  }

  // return the scaled distance for this axis:
  return distance;
}

void setup() {
  pinMode(button, INPUT);
  pinMode(bluetoothTx, INPUT); // bluetoothTX is equivalent to arduino RX pin
  pinMode(bluetoothRx, OUTPUT);
  Serial.begin(115200);  // Begin the serial monitor at 115200bps
  BT.begin(115200);  // RN-42 defaults to 115200bps
}

void loop() {
  // read and scale the two axes:
  int xReading = readAxis(xAxis);
  int yReading = readAxis(yAxis);
  int buttonState = digitalRead(button);

  // move the mouse:
  mouseCommand(buttonState, xReading, yReading);
  delay(responseDelay);

  if(BT.available())  // If there's data being sent to the bluetooth module
  {
    // Send any characters the bluetooth receives to the serial monitor
    Serial.print((char)BT.read());
  }
}

what do you mean control a bluetooth mouse? ... a mouse is an input device, not an output device

I think the OP want to configure and use the RN42 (which is a bluetooth chip) as HID mouse to use with a PC. The Arduino would then read from the joystick and send the data to the RN42 to move the cursor correspondingly on the PC

@Tadashi Have you GPIO11 of the RN42 on high level, when powering up?

Thanks for the responses. The problem with getting no response from the mouse was that the bluetooth did not auto reconnect to the computer after powering down. I solved this by sending the command SM,6 for auto reconnect and then R,1 to reboot.

However, I ran into but fixed a few bugs after I connected the RN 42. For anyone trying to make an HID mouse, I have a few troubleshooting tips. My mouse was swerving to the top left of my screen because the resting position of the joystick was not at the center of the range (12) that I wanted the analog pot values to be mapped to. This was because my joystick did not output 1023 as a max value. I scaled 1023 down by .6 to solve this. Another issue was that upon moving the joystick, my mouse would follow a single trajectory and not move anywhere else. Increasing the response delay solved this.

I know that it's been a long time, i am working on the same project as you Ponderosa, have you been able to make it work? I am using an esp32 board with the same joystick. Hoping to get a reply from you. Thank you

The problem with getting no response from the mouse was that the bluetooth did not auto reconnect to the computer after powering down. I solved this by sending the command SM,6 for auto reconnect and then R,1 to reboot.


text:
Code for Degrees not
Using Audrino Nano and MKS SERVO42 42 Stepper Motor With Driver Board Closed Loop with the LCD. I have got the motor going by using the menu on board. Now able to run Code1 https://github.com/makertut/Arduino-Closed-loop.git out of GitHub and it runs as it is designed. Line 5 int numstep = 1030; cc runs the number of steps indicated and changing this number will determine the movement.
I can do the math to calculate the degrees for number of step for a particular stepper. I would like to use degrees instead of steps for my program. Does anybody know how to code this?
Thanks Greg

convert the angle to step count

You can find the number of steps per revolution in the specification of the stepper motor. Then just calculate the angle from the steps. Simple rule of three

If you can calculate the number of steps per degree you can calculate the number of degrees per step. It's high school math. Not even high school math. It's bordering on preschool math...

Thanks for reply. I said I could do the math in my question. Maybe I wasn't clear in my question or didn't supply enough info. I going to monitor multiple sensors, When one sensor is detected I want the stepper to turn to a certain degree such as 45, If another, different sensor is detected it would move to that place say 90.  Every sensor would be assign a specific degree or position.  Will steps act the same as degrees?  If  the stepper is at 90 degrees (or 50 steps) and the first sensor is then detected will it move to the 45 degree position (or 25 steps) position.   360/1.8=200

This is basic algebra 1.
Say steps / degree = 5
So write that as 2 fractions:
steps   5
----- = -
degree  1

Then take the reciprocal of both sides:
degrees   1
------- = -
step      5


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

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

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

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


text:
how to get esp32 ip address ,which is being connected to local network
I need to know the IP address of ESP32 on the local network(without printing ip on serial monitor ). The idea is to do mDNS or UDP broadcast to send the IP to the android application. The app will then use that IP to do the communication. Is there someone who has already done it?

You have already answered it yourself.  The idea is to do mDNS... - that is exactly what mDNS is for. You don't know the IP address, so you look it up with mDNS.

You don't. You configure mDNS (as you already suggested in your question...!) and the client device then queries mDNS to find the device by the name you allocated it.
Look at the ESPmDNS library examples for how to use mDNS.
Edit: if you really want the IP, you can do WiFi.localIP() (station mode) or WiFi.softAPIP() (access point mode).


text:
Which Protocol to use to control WiFi (esp 32) enabled Led Light
I am developing a Wifi based Led light (for learning purpose). I have little knowledge about web server, clients, Web protocols. I will be using ESP32 as Controller cum WiFi module.
There are two ways to control Led light over WiFi.
Locally
Remotely // as of now am focusing on locally
Android/iOS app will be handling all the control part (Flutter app)
Which protocols can I use to control Led light, locally?
will set up multiple esp32 at that time its hard to control the device both devices will have different ip
Kindly help!
if anyone give good example it would be helpful

Personally I use MQTT and a Mosquitto server running on the internet. Then I simply use MQTTPanel on my phone.

google esp32 wifi led

There are many ways to do this. I recommend Adafruit IO which has an MQTT backend and a nice configurable dashboard frontend, and is free for small environments. I’ve recently moved to my own Mosquitto MQTT broker and Node Red frontend.

the thing is its not possible to place a server for controlling an led in local network , i want to use my app as a server to contollig all the devices connected to my router

You can use your ESP as a server by the following code and then put your DigitalWrite(1, HIGH) line in the code like the following:
 String line = client.readStringUntil('\r');
 Serial.print(line);
if(line=="ledon")
{
DigitalWrite(1, HIGH);
}

and at this point you just can call the following link to turn the led on
http://192.168.*.**/ledon

or whatever the starting of your ipv4 is.


text:
Using L298N bridge to control smart lock
I want to use L298N bridge to power up and control simple smart lock. It requires 12V power supply, so I've used L298N bridge to power this smart lock.
I removed jumper from enA pin and connected enA 12V to Arduino Nano D8 pin.
I sent value 255 through this pin but smart lock did nothing. Any suggestions?
I'm using BLE controller to send turn on/off signal from Android App (but its not relevant in this case, because analogWrite is called).
Lock:
https://www.aliexpress.com/item/32949292074.html
Here is code:
#define enA 8

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

void loop() {
 String msg = bluetooth.read(); //using BLE controller to get message from Android app.

 if(msg == "ON"){
   analogWrite(enA, 255);
 } else if(msg == "OFF"){
   analogWrite(enA, 0);
 }

}

Here is setup:

https://majenko.co.uk/blog/importance-sharing-grounds

Also: you need to control the direction pins or it won't know what to do.

So I have to ground everything including BLE controller through breadboard like this? https://i.imgur.com/ZueUc82.png (and I'm powering Arduino through USB port)

that item from aliexpress is not a smart lock ... it is a solenoid

It looks to me like you failed to tie the grounds of the Arduino and the H-Bridge together.

You really don't want an L239D to control that lock. It's overkill.  The L239D is a H-bridge that is designed to drive loads in two different polarities (forward / backwards on a motor for example).
That lock is merely a spring-loaded solenoid. You give it power and it pulls the lock back. You remove power and the spring closes it again.
All you need is a simple transistor circuit just like you'd use for a relay.

Since you insist on using an L239D, here's a schematic for you:

simulate this circuit – Schematic created using CircuitLab

I understand that but I dont have time to buy transistor and everything is delayed due to corona. I know that its overkill :D Also I have to apply power to IN1 pin too? IN1 ---- D9 and digitalWrite(9, HIGH); ?

And IN2, which has to be the opposite level to IN1. IN1 and IN2 define the direction of current flow through the load. EN1 defines the level of current through the load.

Ive tried to connect ground pins through breadboard but now L298N is not powered for some reason. Before red LED turn on as I powered adapter. Isnt Arduino powered by USB from laptop a reason?

Don't forget the L239D's ground needs connecting.

Ahh so https://i.imgur.com/ZueUc82.png L239D ground can go to minus pins or straight to the top GND pin in Arduino

Thanks its working. I'm more of a sw guy than hw guy (Android apps) but I had to do this.


text:
HM-10 controller is not responding to AT commands
I recently purchased new HM-10 module, because old one was clone and it lacks AT+TYPE command. I connected it to my Arduino and I don't know why but I cant see any response in SerialMonitor.
I even tried to use this ble_help() function which worked on my old HM-10 controller but here nothing is returned.
Pins:

TXD --- D2
RXD --- D3

Here is my code:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); //Create software serial instance, pins of your choice

char c = ' ';

// Initialization
void setup()
{
  Serial.begin(9600);
  Serial.print("Sketch:   ");   Serial.println(__FILE__);
  Serial.print("Uploaded: ");   Serial.println(__DATE__);
  Serial.println(" ");

  BTserial.begin(9600);
  Serial.println("BTserial started at 9600");
  ble_help();
}

String str_ii = "";
int ii_0 = 0;
void ble_help(){
  BTserial.println("AT+HELP"); // list all AT+ commands
  while (true){ // loop to print all AT+ commands
    char in_char = BTserial.read();
    if (int(in_char)==-1 or int(in_char)==42){continue;}
    str_ii+=in_char;
    if (in_char=='\n'){
      if (str_ii==String('\r')+String('\n')){
        if (ii_0 == 0){
          ii_0 = 1;
          continue;
        }
        break; // break after more than 1 empty carriage return and newline
      }
      Serial.print(str_ii);
      str_ii = "";
    }
  }
}

// Arduino Execution Loop
void loop()
{
  // Read from the Bluetooth module and send to the Arduino Serial Monitor
  if (BTserial.available())
  {
    String hm10msg = "";
    char c;

    while((c = BTserial.read()) != -1) {
      hm10msg += c;
      delay(10);
    }

    Serial.println("Received: " + hm10msg);
  }

  // Read from the Serial Monitor and send to the Bluetooth module
  if (Serial.available())
  {
    c = Serial.read();
    BTserial.write(c);
    //Serial.write(c);
  }
}

Have you tried different baudrates for the HM-10? It might be configured for a different baudrate than 9600

I will try. But 9600 should be default as far as i know

Tried every possibility but it doesnt work

With a new module like this, I just skip the code and connect it straight to my PC with a UART-USB adapter. That way, I can send commands directly from the Serial Monitor and also try out different baud rates easily. Do you have an adapter like this? If you don't, it's possible to use the one on your Nano.

Ok its working now. I have to use BTserial.print(c) instead of BTserial.write(c).


text:
How to load scal factor external to the code?
We know that, we need calibration factors (scale factors) to read current sensor data (ACS758) to arduino. I am also using voltage reader using voltage divider circuit for my project. I need to build 5 such boards and need to change calibration factor in main program everytime due to tolerance of componenets. Currently for one of my board reference_factor is 0.81 and this will change due to resistor tolerance for other boards.
Because of this issue I need to maintain 5 different codes for 5 different boards. These sensor values controls on and off of certain relays. (Not shown in the code).
can I load this referrence_factor externally through text file or as any other medium so that I need not change the code everytime.? I am using arduino Nano.
int reference_Factor = 0.81;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // read the raw data coming in on analog pin 0:
  int lightLevel = analogRead(A0);
  // Convert the raw data value (0 - 1023) to voltage (0.0V - 5.0V):
  float voltage = lightLevel * reference_factor;
  // write the voltage value to the serial monitor:
  Serial.println(voltage);
}

You can store it in EEPROM.  Write a method in setup that will see if EEPROM has been written and if it hasn't then it will let you input a number to use.  You set it up on the first powerup at the factory.  From there on out it sees that EEPROM has been written and skips that bit and instead reads the factor out of EEPROM.

By the way, your current code is flawed.  You should look up what types of values an int variable can hold.

Thanks for your reponse. I have indeed used float in my actual code.

You should always post the "actual code" when asking for help.  Otherwise you end up getting answers that don't apply to your "actual code" and then you've wasted both our time and yours.

As written in the comments you coulduse eepron, but in your scenario it has one big disadvantage: Everything has to be written at compile time (aka when you programm the Nano, you have also to fill the eeprom with the relevant values), so e.g. if you have a temperature depending factor you want to change while on the field...
I would go for a SD-card reader:

Cheap to get (2$)
Easy to handle in code (read from a file is a standard function)
using a PC compatible file systen FAT enables reading/writing onto the SD card on a PC/other device without recompiling your code.
If you switch sensors for whatever reason, just write a new scale.txt file to the SD-card, insert and reboot the nano to get the new values
you could still use eeprom as a fallback scenario

As a tip (also mentioned in the comments by Delta_G) int for something like 0.01 is not what you want - define as float and watch out for the "conversion trap" when using with other variables not defined as float.

Thanks for your respnse. As I have not attached complete code here, int is a typo error. I do undertsnd the data structure. I have indeed used float in my code. I wish to know whats the difference here in directly uploading code and uploading code using EPROM? I need to edit in the main code for all 5 boards even if I will be using EPROM right?

Yes either loading the eeprom from the program (5 versions) or via an extra program you flash before loading (5 flash eeprom versions + 1 identical program) or some kind of input (button presses/led blink to enter during first start - 1 program). Thats why I proposed SD as hassle free ;-)

No you wouldn't have to load the EEPROM at compile time.  You could compile the same code for all boards.  What you would need is some code in setup that check if a value has already been set in EEPROM.  If it hasn't then it calls a function that asks you over the serial monitor and lets you enter the number and stores it in EEPROM.  This code would only run the very first time the board is turned on.  After that nobody will ever see that prompt unless you blank the board and reload.


text:
Will L293D arduino shield lose functionality if I connect it with jumpers instead of mounting on arduino?
I'm new to arduino and have bought a L293D motor driver shield which have no heads on the pins. I looked at the pinout and it seems that shield does not use any of the pins "by default". So will it work properly if I connect it like it isn't a shield(without mounting), because I need to use other pins and it would be nice if I don't need to solder them. I know it's some basic stuff but I want to avoid messing up at the very beginning if I don't have to. Thanks.

As long as you connect all the pins that need to be connected there is no reason the shield has to be mounted on top of the Arduino.

Thank you for answering, missing headers confused me on this shield.


text:
Why do I keep blowing up Nanos when I solder them?
I have blown up 2 Arduino Nanos and I'm trying to figure out what I'm doing wrong.
In both cases, I was powering the boards with a 16V supply (I know this is high, but the regulator datasheet says it is good to 25V, and the regulator was not damaged). I unplug the supply and USB cable and then start soldering to one of the pins (A6). When I plug the board back in, the L LED does not flash, indicating the bootloader has been erased. The POW light is on and I still measure 5V, indicating the regulator is working. When I connect the board to my PC, the serial port pops up just fine. But when I try to upload a sketch, the IDE times out and says it cannot communicate with the board.
I attempted to reprogram the bootloader using a raspberry pi but avrdude also says it cannot find the device either. It looks like the microcontroller is blown.
My iron tip is grounded, so my best guess is some residual power in the supply travels through the microcontroller to my iron and shorts something out. But this seems unlikely seeing as A6 is an input and grounding it should be just fine even when the supply is fully on.
Any ideas what I could be doing wrong? FYI, I am cross-posting this on the Arduino forums.

What circuit are you soldering the Nanos to and are you using the Vin pin correctly? Have you tested this configuration on a breadboard? Cross-posting to what other StackExchange sites?

http://forum.arduino.cc/index.php?topic=680237

If your nano is a cheap chinese clone then it could die just by you looking at it wrong.

Check your soldering temperature and that you are not overheating the microcontroller, or any other component on the board.  Also check your flux.  Some types are more conductive than others and you will need to take care cleaning with isopropanol.

Thanks. The configuration works fine until the soldering event. Yes, it's a clone; maybe that is the issue. I am not overheating the microcontroller; the point where I'm soldering is pretty far from it. I am cleaning the flux.

"when the supply is fully on"  do you solder while the circuit is powered?!

No. I unplug the supply and USB before soldering.

something else is at play here .... please post a couple of clear, well lit pictures of the soldered board ... top and bottom views ... board should fill most of the picture

My advice would be not to solder directly to the Nano pins.  Instead, use the appropriately sized DIL socket, and solder to the pins of that instead.   Then plug in the Nano once the soldering is complete.

the OP would probably have to solder the headers to the board first


text:
Does MFRC522 module read all 13.56 MHz RFID tags?
Hello everyone. Does MFRC522 module read all 13.56 MHz RFID tags?
Or there are different types of the 13.56 MHz tags that the MFRC522 module reads only one type of them?

The second sentence of the datasheet: The MFRC522 supports all variants of the MIFARE Mini, MIFARE 1K, MIFARE 4K, MIFARE Ultralight, MIFARE DESFire EV1 and MIFARE Plus RF identification protocols.

Thanks a lot...