text:
ST7789 TFT display only shows a correct image while Arduino reset button is held down - Why?
I am trying to get the ST7789 TFT display to work with Arduino. I followed online guides  for connections and am using the fast library fron github and included workbench ino (https://github.com/cbm80amiga/Arduino_ST7789_Fast).
Problem: The program runs and drives the display but the image is corrupt and only partial. I discovered that if I quickly and firmly press the reset button - and keep it pressed down - the image at the moment of reset press suddenly becomes full and good (albeit static because reset is pressed). Ofcourse as soon as I release the reset button the program restarts with the same corrupt image (the pictures below illustrate the issue).

I could not find a description of this particular problem by online searching. Here is what I tried to fix it (all to no avail):

I confirmed all pins are correct as defined in the ino script.
I ensure only the 3.3v power line is used. I have never connected the Vcc to 5 v
I tried with a genuine Arduino UNO as well as a clone - both show the same behaviour.
I used 1k:2k resistor voltage dividers for the data lines, res and DC - these did not help. In fact the display did not work at all with the voltage dividers, only the backlight came on and the screen flickered slightly. I checked that I was getting ~3v in the middle of each divider.
I used two separate ST7789 display boards, bought from two separate sellers on different occasions - both show the same behaviour.

[Edits in response to comments below]

The same behviour occurs when using a sketch that uses the standard Adafruit libraries (as opposed to the fast library linked above).
The same corruption is seen when run on an arduino nano clone. However, with the nano, pressing the reset button shows only a fleeting glimpse of the full image prior to resetting (i.e. holding down the reset button does not preserve a static image on the screen).

Any ideas about what is going on and how to fix it? Thanks.

Maybe that "fast" library is just too fast? Have you tried the Adafruit ST7789 library? We know that one works properly.

Did your program constantly clear the screen (with fillScreen()) in a loop?

As different UNOs as well as different displays show the same behaviour, it's the software, most probably. Did you try what Majenko suggests?

Regarding fillscreen, no. In the besnchmark test shown fillscreen is used to clear the screen inbetween benchmark tests. The setup function ploughs through each test. At the end is prints the results to the screen and leaves it like that. The loop function is empty. So you are left with a static screen of results (shown in my pictures above). The corruption is constant throughout regardless of animation, clearing screen or static images. Only press-holding the rest make the image full and clear. Perhaps something to do with grounding / changing constant voltages somewhere caused by the reset?

I managed to load an example that uses the standard Adafruit libraries (not the fast libraries) - from here link. It 'works' but with the same problem described above - corrupt image until press-hold of reset then image becomes full and clear. So not a problem with the 'fast' library.

Just as I was about to dispose mine I stumble on your post. You saved me man! Thanks

I found the answer to this problem. After reading multiple web pages / YouTube videos from multiple authors on this device and ~all of them warning you must never connect the Vcc to 5v or it will destroy the display, I found one or two that suggested you could use 5v because in this particular module there is a built-in regulator. So, faced with the thing being useless anyway, I decided to take the plunge and connect the Vcc of the TFT to the 5v pin of the Arduino and - hey presto - it works perfectly (see picture below: note the clear full image without the reset button being held down and also notice the voltage pin of the TFT is now connected to Arduino 5v compared to the pictures in my question).

The picture below shows the back of my TFT display module and, from what I have read, it is the J3Y transistor that is key to the voltage regulation in this module.

I hypothesise that pressing the reset button must have allowed equalisation of the voltages somehow but it is beyond my knowledge to explain it. I tried measuring the 3.3v pin on the Arduino with a voltmeter while holding down the reset button but I could see no change (the TFT module was not in situ for this test so maybe there is some interaction between Arduino and the TFT circuitry during reset).
Please note: I suspect this is a peculiarity of the particular TFT display module I have. Please DON'T run your 3.3v devices at 5v unless you have good reason to believe that they can take it. I only tried this after reading a couple of pages (including the detailed specs on the TFT module seller's listing) that suggested it would be OK with my particular TFT module - your's may be different. But if you have the same problem you see in my question then maybe that is something to consider.
Thanks to those who have responded.

I had the same problem and running 5V solved it for me as well. Let's just hope it will hold in the long run.

That transistor(!) with it's two base resistors and 100R current limiting resistor is only there for the backlight. It has nothing to do with the VCC. The capacitor in between is connected between VCC and GND.

Interestingly, my 240x320 2.4" ST7789 display has exactly the same problem when connected to 5V and works well only when connected to 3V3 which is opposite compared to your display. The display was listed as 5V/3V3 but I had to use 3V3 and a level shifter. And I had to connect BL to Vcc.


text:
Max7219 7-segment display not working
when I connect VCC pin to the 5V and GND to the GND on the Arduino MEGA, then sometimes the display glows and sometimes it doesn't. It kinda looks like some contacts are bad because it starts to work mostly when I move it somehow, but I'm sure the problem is not in contacts as they defintely touch.
I also measured voltage on the display and it showed correctly ~5V.
Where could be the problem? Thanks
//Edit
I am using those displays to build simple autopilot panel for MSFS20 using MobiFlight. There is not any code, you just have to define what pins you connected and that's it. But even if it turns on, then all the leds stay on.
There might be a problem since I soldered the pins into the display so I could damage the board, it's a cheap one from China. Is there a way how to test if it's a board problem?

just because the two components touch, it does not mean that there is an electric connection ... corrosion on component leads can have insulating quality ... the 5 V reading is meaningless for a bad connection ... you would read 5 V if nothing was conected to the power pins

Well I have a 3 of these displays and they all behave same

I read 5V on the display, not on the arduino

you are not understanding .. a reading of 5 V is not an indication of the component fitness ... a burned out light bulb still has full voltage at its base

it sounds like the serial data line may have a problem

Oh I see, what can I do then?

@Elayer213 Sorry, currently we cannot really help you. We can just guess, because you didn't gave much information. Please show your circuit and also show, how you have connected everything (as jsotola wrote, touching doesn't mean good connection, especially if data should run over that connection). Please also show the code in your question. You can edit it and add all these information

source: Stack Exchange

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

sort: votes


text:
File created, but not logging data
I am starting using Arduino and have very little to none experience coding. However, I have managed to code and understand how it works.
The problem that I have is that I am unable to log (record) data from the three sensors attached (Adafruit Anemometers). All of them work properly; the data file is created. However, there is no data (or time reference) being written on the file.
When I verify the code, it's approved...Therefore, it should work, right?.=/
Then, I uploaded code.
I am using an Arduino uno with an SD Logger shield (Data Logging Shield v1.0, from Deek-Robot(TM)), which uses a DS1307 RTC.
All comments are more than welcome!
Thanks in Advance
#include "SD.h"
#include <Wire.h>
#include "RTClib.h"

// A simple data logger for the Arduino analog pins
#define LOG_INTERVAL  60000 // mills between entries
#define ECHO_TO_SERIAL   0 // echo data to serial port
#define WAIT_TO_START    0 // Wait for serial input in setup()

// the digital pins that connect to the LEDs
#define redLEDpin 3
#define greenLEDpin 4

// The analog pins that connect to the sensors
#define Anemometer0           // analog 0
#define Anemometer1           // analog 1
#define Anemometer2           // analog 2

RTC_DS1307 RTC; // define the Real Time Clock object

//Setup Variables of Anemometers

//Anemometer0
const int sensorPin0 = A0; //Defines the pin that the anemometer output is connected to
int sensorValue0 = 0; //Variable stores the value direct from the analog pin
float sensorVoltage0 = 0; //Variable that stores the voltage (in Volts) from the anemometer being sent to the analog pin
float windSpeed0 = 0; // Wind speed in meters per second (m/s)

//Anemometer1
const int sensorPin1 = A1; //Defines the pin that the anemometer output is connected to
int sensorValue1 = 0; //Variable stores the value direct from the analog pin
float sensorVoltage1 = 0; //Variable that stores the voltage (in Volts) from the anemometer being sent to the analog pin
float windSpeed1 = 0; // Wind speed in meters per second (m/s)

//Anemometer2
const int sensorPin2 = A2; //Defines the pin that the anemometer output is connected to
int sensorValue2 = 0; //Variable stores the value direct from the analog pin
float sensorVoltage2 = 0; //Variable that stores the voltage (in Volts) from the anemometer being sent to the analog pin
float windSpeed2 = 0; // Wind speed in meters per second (m/s)

float voltageConversionConstant = .004882814; //This constant maps the value provided from the analog read function,
//which ranges from 0 to 1023, to actual voltage, which ranges from 0V to 5V
int sensorDelay = 1000; //Delay between sensor readings, measured in milliseconds (ms)

//Anemometer Technical Variables
//The following variables correspond to the anemometer sold by Adafruit but could be modified to fit other anemometers.

float voltageMin = .4; // Mininum output voltage from anemometer in mV.
float windSpeedMin = 0; // Wind speed in meters/sec corresponding to minimum voltage

float voltageMax = 2.0; // Maximum output voltage from anemometer in mV.
float windSpeedMax = 32; // Wind speed in meters/sec corresponding to maximum voltage

// for the data logging shield, we use digital pin 10 for the SD cs line
const int chipSelect = 10;

// the logging file
File logfile;

void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);

  // red LED indicates error
  digitalWrite(redLEDpin, HIGH);

  while(1);
}

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

  Serial.begin(9600);
  Serial.println();

#if WAIT_TO_START
  Serial.println("Type any character to start");
  while (!Serial.available());
#endif //WAIT_TO_START

  // initialize the SD card
  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(10, OUTPUT);

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");

  // create a new file
  char filename[] = "LOGGER00.CSV";
  for (uint8_t i = 0; i < 100; i++) {
    filename[6] = i/10 + '0';
    filename[7] = i%10 + '0';
    if (! SD.exists(filename)) {
      // only open a new file if it doesn't exist
      logfile = SD.open(filename, FILE_WRITE);
      break;  // leave the loop!
    }
  }

  if (! logfile) {
    error("couldnt create file");
  }

  Serial.print("Logging to: ");
  Serial.println(filename);

  Wire.begin();
  if (!RTC.begin()) {
    logfile.println("RTC failed");
#if ECHO_TO_SERIAL
    Serial.println("RTC failed");
#endif  //ECHO_TO_SERIAL
  }

  pinMode(redLEDpin, OUTPUT);
  pinMode(greenLEDpin, OUTPUT);

   // If you want to set the aref to something other than 5v
  //analogReference(EXTERNAL);
}

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

  DateTime now;

  // delay for the amount of time we want between readings
  delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));

  digitalWrite(greenLEDpin, HIGH);

  // log milliseconds since starting
  uint32_t m = millis();
  logfile.print(m);           // milliseconds since start
  logfile.print(", ");
#if ECHO_TO_SERIAL
  Serial.print(m);         // milliseconds since start
  Serial.print(", ");
#endif

  // fetch the time
  now = RTC.now();
  // log time
//logfile.print(); // seconds since 2000
  logfile.print(", ");
  logfile.print(now.year(), DEC);
  logfile.print("/");
  logfile.print(now.month(), DEC);
  logfile.print("/");
  logfile.print(now.day(), DEC);
  logfile.print(" ");
  logfile.print(now.hour(), DEC);
  logfile.print(":");
  logfile.print(now.minute(), DEC);
  logfile.print(":");
  logfile.print(now.second(), DEC);

#if ECHO_TO_SERIAL
  Serial.print(now.get()); // seconds since 2000
  Serial.print(", ");
  Serial.print(now.year(), DEC);
  Serial.print("/");
  Serial.print(now.month(), DEC);
  Serial.print("/");
  Serial.print(now.day(), DEC);
  Serial.print(" ");
  Serial.print(now.hour(), DEC);
  Serial.print(":");
  Serial.print(now.minute(), DEC);
  Serial.print(":");
  Serial.print(now.second(), DEC);
#endif //ECHO_TO_SERIAL

//Anemometer0
const int sensorPin0 = A0; //Defines the pin that the anemometer output is connected to
int sensorValue0 = 0; //Variable stores the value direct from the analog pin
float sensorVoltage0 = 0; //Variable that stores the voltage (in Volts) from the anemometer being sent to the analog pin
float windSpeed0 = 0; // Wind speed in meters per second (m/s)

//Anemometer1
const int sensorPin1 = A1; //Defines the pin that the anemometer output is connected to
int sensorValue1 = 0; //Variable stores the value direct from the analog pin
float sensorVoltage1 = 0; //Variable that stores the voltage (in Volts) from the anemometer being sent to the analog pin
float windSpeed1 = 0; // Wind speed in meters per second (m/s)

//Anemometer2
const int sensorPin2 = A2; //Defines the pin that the anemometer output is connected to
int sensorValue2 = 0; //Variable stores the value direct from the analog pin
float sensorVoltage2 = 0; //Variable that stores the voltage (in Volts) from the anemometer being sent to the analog pin
float windSpeed2 = 0; // Wind speed in meters per second (m/s)

float voltageConversionConstant = .004882814; //This constant maps the value provided from the analog read function,
//which ranges from 0 to 1023, to actual voltage, which ranges from 0V to 5V
int sensorDelay = 1000; //Delay between sensor readings, measured in milliseconds (ms)

//Anemometer Technical Variables
//The following variables correspond to the anemometer sold by Adafruit but could be modified to fit other anemometers.

float voltageMin = .4; // Mininum output voltage from anemometer in mV.
float windSpeedMin = 0; // Wind speed in meters/sec corresponding to minimum voltage

float voltageMax = 2.0; // Maximum output voltage from anemometer in mV.
float windSpeedMax = 32; // Wind speed in meters/sec corresponding to maximum voltage

  logfile.print(", ");
  logfile.print(A0);
  logfile.print(", ");
  logfile.print(A1);
  logfile.print(",");
  logfile.println(A2);

#if ECHO_TO_SERIAL
  Serial.print(", ");
  Serial.print(Anemometer0);
  Serial.print(", ");
  Serial.print(Anemometer1);
  Serial.print(",");
  Serial.println(Anemometer2);
#endif //ECHO_TO_SERIAL

  digitalWrite(greenLEDpin, LOW);
}
´´´

You "verified", yes. But did you "upload"?

you don't open the file if it exists

@Juraj That bit of code is to create a new file with sequential numbering. It will find the first file that doesn't exist in LOGGER00.CSV to LOGGER99.CSV and open that.

Yes @Majenko, the code was uploaded correctly to the board. But I haven't mentioned that in the written explanation, thanks for pointing that out. Should the file contain some data and date/time?

I suspect you aren't giving it enough time to flush the data to the SD card and it's only in the buffer. You should call logfile.flush(); after each iteration.

Did you make a copy paste error, when putting the code in the question? You have a part in loop() where you again define the global variables like sensorPin0

Your delay statements seems really weird to me. Why are you doing this? If you want to read at a specific interval, you should use millis() like in the BlinkWithoutDelay example and avoid delay() completely

@chris|, yes... I made an error. Thanks for noticing!

Thanks for all your help. I managed to log data in the SD card including date and time. The new code is the following:
#include <SPI.h>
#include <SD.h>
#include "RTClib.h"

RTC_DS1307 rtc; // create local instances of library class objects

DateTime time;

File dataFile;

const int chipSelect = 10;

// Anemometer at 0.15 magl

const int sensorPinA0 = A0; //Defines the pin that the anemometer output is connected to
int sensorValue0 = 0; //Variable stores the value direct from the analog pin
float sensorVoltage0 = 0; //Variable that stores the voltage (in Volts) from the anemometer being sent to the analog pin
float WindSpeed0 = 0; // Wind speed in meters per second (m/s)

float voltageConversionConstant0 = .0048828125; //This constant maps the value provided from the analog read function, which ranges from 0 to 1024, to actual voltage, which ranges from 0V to 5V
// hence, this value corresponds to 5.00V/1024. Check https://forum.allaboutcircuits.com/threads/why-adc-1024-is-correct-and-adc-1023-is-just-plain-wrong.80018/
int sensorDelay0 = 60000; //Delay between sensor readings, measured in milliseconds (ms)

//Anemometer Technical Variables
//The following variables correspond to the anemometer sold by Adafruit but could be modified to fit other anemometers.

float voltageMin0 = .4; // Mininum output voltage from anemometer in mV.
float windSpeedMin0 = 0; // Wind speed in meters/sec corresponding to minimum voltage

float voltageMax0 = 2.0; // Maximum output voltage from anemometer in mV.
float windSpeedMax0 = 32; // Wind speed in meters/sec corresponding to maximum voltage

// Anemometer at 0.5 magl

const int sensorPinA1 = A1; //Defines the pin that the anemometer output is connected to
int sensorValue1 = 0; //Variable stores the value direct from the analog pin
float sensorVoltage1 = 0; //Variable that stores the voltage (in Volts) from the anemometer being sent to the analog pin
float WindSpeed1 = 0; // Wind speed in meters per second (m/s)

float voltageConversionConstant1 = .0048828125; //This constant maps the value provided from the analog read function, which ranges from 0 to 1024, to actual voltage, which ranges from 0V to 5V
// hence, this value corresponds to 5.00V/1024. Check https://forum.allaboutcircuits.com/threads/why-adc-1024-is-correct-and-adc-1023-is-just-plain-wrong.80018/
int sensorDelay1 = 1000; //Delay between sensor readings, measured in milliseconds (ms)

//Anemometer Technical Variables
//The following variables correspond to the anemometer sold by Adafruit but could be modified to fit other anemometers.

float voltageMin1 = .4; // Mininum output voltage from anemometer in mV.
float windSpeedMin1 = 0; // Wind speed in meters/sec corresponding to minimum voltage

float voltageMax1 = 2.0; // Maximum output voltage from anemometer in mV.
float windSpeedMax1 = 32; // Wind speed in meters/sec corresponding to maximum voltage

// Anemometer at 1.2 magl

const int sensorPinA2 = A2; //Defines the pin that the anemometer output is connected to
int sensorValue2 = 0; //Variable stores the value direct from the analog pin
float sensorVoltage2 = 0; //Variable that stores the voltage (in Volts) from the anemometer being sent to the analog pin
float WindSpeed2 = 0; // Wind speed in meters per second (m/s)

float voltageConversionConstant2 = .0048828125; //This constant maps the value provided from the analog read function, which ranges from 0 to 1024, to actual voltage, which ranges from 0V to 5V
// hence, this value corresponds to 5.00V/1024. Check https://forum.allaboutcircuits.com/threads/why-adc-1024-is-correct-and-adc-1023-is-just-plain-wrong.80018/
int sensorDelay2 = 60000; //Delay between sensor readings, measured in milliseconds (ms)

//Anemometer Technical Variables
//The following variables correspond to the anemometer sold by Adafruit but could be modified to fit other anemometers.

float voltageMin2 = .4; // Mininum output voltage from anemometer in mV.
float windSpeedMin2 = 0; // Wind speed in meters/sec corresponding to minimum voltage

float voltageMax2 = 2.0; // Maximum output voltage from anemometer in mV.
float windSpeedMax2 = 32; // Wind speed in meters/sec corresponding to maximum voltage

void setup() {
 Serial.begin(9600);
 while (!Serial) {;} // wait for serial port to connect.
 Serial.print("Initializing SD card...");
 if (!SD.begin(chipSelect)) {
 Serial.println("Card failed, or not present");
 while (1); // loop forever
 }
 Serial.println("Have SD card");
 rtc.begin();
}

void loop() {

sensorValue0 = analogRead(A0); //Get a value between 0 and 1023 from the analog pin connected to the anemometer
sensorValue1 = analogRead(A1); //Get a value between 0 and 1023 from the analog pin connected to the anemometer
sensorValue2 = analogRead(A2); //Get a value between 0 and 1023 from the analog pin connected to the anemometer

sensorVoltage0 = sensorValue0 * voltageConversionConstant0; //Convert sensor value to actual voltage
sensorVoltage1 = sensorValue1 * voltageConversionConstant1; //Convert sensor value to actual voltage
sensorVoltage2 = sensorValue2 * voltageConversionConstant2; //Convert sensor value to actual voltage

//Convert voltage value to wind speed using range of max and min voltages and wind speed for the anemometer
if (sensorVoltage0 <= voltageMin0){
WindSpeed0 = 0; //Check if voltage is below minimum value. If so, set wind speed to zero.
}

else {
  WindSpeed0 = (sensorVoltage0 - voltageMin0)*windSpeedMax0/(voltageMax0 - voltageMin0); //For voltages above minimum value, use the linear relationship to calculate wind speed on A0.
    }

if (sensorVoltage1 <= voltageMin1){
WindSpeed1 = 0; //Check if voltage is below minimum value. If so, set wind speed to zero.
}

else {
  WindSpeed1 = (sensorVoltage1 - voltageMin1)*windSpeedMax1/(voltageMax1 - voltageMin1); //For voltages above minimum value, use the linear relationship to calculate wind speed on A1.
    }

if (sensorVoltage2 <= voltageMin2){
WindSpeed2 = 0; //Check if voltage is below minimum value. If so, set wind speed to zero.
}

else {
  WindSpeed2 = (sensorVoltage2 - voltageMin2)*windSpeedMax2/(voltageMax2 - voltageMin2); //For voltages above minimum value, use the linear relationship to calculate wind speed on A2.
    }

 time = rtc.now(); // Read RTC
 String dataString = ""; // Assemble data

log:
 dataString = time.timestamp(DateTime::TIMESTAMP_DATE);
 dataString += ", ";
 dataString += time.timestamp(DateTime::TIMESTAMP_TIME);
 dataString += ", ";
 dataString += String(sensorVoltage0);
 dataString += ", ";
 dataString += String(WindSpeed0);
 dataString += ", ";
 dataString += String(sensorVoltage1);
 dataString += ", ";
 dataString += String(WindSpeed1);
 dataString += ", ";
 dataString += String(sensorVoltage2);
 dataString += ", ";
 dataString  += String(WindSpeed2);
 dataFile = SD.open("Speedlog.txt", FILE_WRITE);
 if (dataFile) { // Write to logfile

 dataFile.println(dataString);
 dataFile.close();
 Serial.println(dataString);
 delay(1000); // pause for one second between sensor logs
 }
 else {
 Serial.println("error opening datalog.txt");
 }
}

You shouldn't use a String, and you don't need to because you can just write all the bits to the file without concatenating them first. If you must, you should remove String dataString = ""; from the loop and add it as a global at the top; it may help a bit with keeping your heap intact, but it's better to avoid String altogether.

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


text:
Sim800L-v2.0-network-problem
I am having trouble to get Sim800L-v2.0 to work. I believe that I am supplying the necessary amount of current (5.0V, 2.1A máx power source, using solid copper wires - circuit photo). The Net LED keeps blinking every second, meaning that it was unable to connect to the network.
Serial monitor readings:
15:57:32.630 -> AT
15:57:32.630 -> OK

16:02:15.391 -> at+cops=?
16:02:23.775 -> +COPS: ,(0-4),(0-2)
16:02:23.775 ->
16:02:23.775 -> OK

16:02:29.075 ->  AT+CPIN?
16:02:29.075 -> +CME ERROR: SIM not inserted

16:02:51.008 -> AT+CREG?
16:02:51.008 -> +CREG: 0,0
16:02:51.008 ->
16:02:51.008 -> OK

16:02:59.639 -> AT+CSQ
16:02:59.639 -> +CSQ: 0,0
16:02:59.639 ->
16:02:59.639 -> OK

16:08:09.354 -> +CFUN: 1
16:08:09.354 ->
16:08:09.354 -> OK

Inspecting the readings, it indicates that the sim card is not inserted at all, which is odd. While searching for some tips on the subject, I did encounter one or another claiming that the problem might be related to the incorrect capacitor used in the circuit module, not really sure though...
Any ideas to solve the issue? Is it a module problem, or am I missing some steps?
Thanks in advance!

#include <SoftwareSerial.h>

//Porta do Arduino onde o pino TX do Módulo GSM esta conectado
#define TX_PIN 10

//Porta do Arduino onde o pino RX do Módulo GSM esta conectado
#define RX_PIN 11

//Cria comunicacao serial via software nas portas digitais definidas acima
SoftwareSerial serialGSM(TX_PIN, RX_PIN);

void setup() {
  //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  while(!Serial);

  //Inicia comunicacao serial com o GSM
  serialGSM.listen();
  serialGSM.begin(9600);
  delay(1000);

  Serial.println("Setup Completo!");
}

void loop() {
  //Le as mensagens vindas do GSM para escrevê-las no monitor serial
  if(serialGSM.available()){
    Serial.write(serialGSM.read());
  }

  //Le as mensagens vindas do monitor serial para copiá-las para o GSM
  if(Serial.available()){
    serialGSM.write(Serial.read());
  }
}

Where are you and what network are you trying to use?

Europe, SIM card is 4g I guess, but some claim that it can switch to 2g and 3g

What network? Some networks no longer provide GSM.

I am not sure I understand, will you kindly explain? Where can I get the network you're refering to? Thanks

You should already know that information. Who did you get the SIM from? T-mobile? Vodafone? And which country specifically are you in, since the networks vary from country to country.

Ah sorry, We give it another name, that is why I got confused...I tried with Meo/Altice.Country: Portugal

Ok, that's all fine. MEO provides E-GSM (900MHz) and DCS (1800MHz) which the 800L works with. That rules that out.

Any idea why it does not work?

Not at the moment. You've exhausted my go-to answers so far...

Can you please add the code? This would make it a bit easier.

I added the code at the end of the topic, thanks.

Did you put the SIM in correctly? It will also seat on some of these boards when it is 180° off.


text:
How do I split an incoming char?
I am sending a list of joystick positions via the serial connection to the arduino in the following format
515;520
Which would be parsed as:
x=515
y=520
How would I split these values up, and convert them to an integer?
MyReceiver:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);
char val;

void setup() {
  xBeeSerial.begin(38400);
  Serial.begin(38400);
}
void loop() {

  if(xBeeSerial.available()>0){
   val = xBeeSerial.read();
   Serial.print(val);
  }

}

My Coordinator:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
int deger1;
int deger2;
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);
void setup() {

   xBeeSerial.begin(38400);
}

void loop() {

  deger1 = analogRead(A0);
  deger2 = analogRead(A2);
  char buf[1000];
  const char *first = " ";
  const char *second = ";";
  char val[4];
  char deger[4];

  strcpy(buf,first);
  sprintf(val,"%d",deger1);
  strcat(buf,val);
  strcat(buf,second);
  sprintf(deger,"%d",deger2);
  strcat(buf,deger);

  Serial.print(buf);
  xBeeSerial.write(buf);
  delay(200);
}

Put all characters into a char array. Then use strtok() for splitting and atoi() for converting to integer. Here is the reference for strtok(). You can even open the online editor with the example there (click on "Edit and run") and play with it, until you understand, how it works.

And you can look at my answer to this question. It already explains how to use strtok(). Arduino split comma separated serial stream

I examined but i can not. Can you help me in the code selection above?

Where in the code above are you trying to split a string? I cannot know, where you want to do that. And what do you mean by "I can not"? What exactly is the problem? Have you looked at some tutorials on strtok(). Have you tried yourself in the online editor in the reference, that I linked to? Is my answer to the other question not clear enough? I need to know, where exactly the problem is, so that I'm not just writing down the same stuff as in my other answer, but helping you with the problem.

I cannot directly transfer the data I get from xBee into char buffer[].


text:
Arduino - ServoMotor Control and SoftwareSerial
My two arduino communicating serially with XBee. The receiver arduino also controls the servo motor. Servo works stably when there is no xBee connection. But when Arduino's serial communication, there is a problem in the operation of the servo motor. Servo motor stuttering while rotate, so stuttering occurs.
Can you help me?
My Coordinator Code:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
int deger3;
int deger4;
String d1,d2,d3;
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);

void setup() {
  Serial.begin(38400);
  xBeeSerial.begin(38400);
}void loop() {

  deger3 = analogRead(A0);
  deger4 = analogRead(A2);

  String deger5 =  (String)deger3 + ";" + (String)deger4 ;

  xBeeSerial.println(deger5);

  delay(50);
}

My Receiver Code:
#include <SoftwareSerial.h>
#include <Servo.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);
String d1,d2,d3;

const int trigPin = 4;
const int echoPin = 3;
long duration;
int distance;
Servo myServo;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  xBeeSerial.begin(38400);
  Serial.begin(38400);
  myServo.attach(11);
}
void loop() {
  for(int i=15;i<=165;i++){
    myServo.write(i);
     delay(10);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, 11200);
    distance= duration*0.034/2;

    if(xBeeSerial.available()>0){
      d1=xBeeSerial.readString();
    }
  }

  for(int i=165;i>15;i--){
    myServo.write(i);
     delay(10);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, 11200);
    distance= duration*0.034/2;

    if(xBeeSerial.available()>0){
      d1=xBeeSerial.readString();
  }
 }
}

What exactly is this "problem in the operation of the servo motor"? Please edit that into your question.

I arranged. Stuttering.

When SoftwareSerial enters an interrupt each time it receives a character and busy-waits (delays) to time in each data sample as the bits in the character come in.  No other interrupt service routines can run while this is happening.  It also turns off interrupts when it sends.
The servo library for the AVR uses timer interrupts to generate the servo position signals.
When characters are being received, SoftwareSerial will interfere with the generation of the servo position signal because only one interrupt service routine can run at a time.
You may be able to mitigate the problem adding significant delay between characters sent, reducing the total number of characters sent.  This would limit the interference and give servo time to get back to its correct position from however far it managed to deviate over the course of an inbound serial character.
There are also alternative libraries that use the AVR's Input Capture feature on an ICP pin to do some of the work of serial in hardware, and that may work for you.  Here's one example library.
@ocrdu has rightly prompted me to add that there are servo libraries that will do the servo signal generation in hardware.

I removed some material regarding I2C/Wire because this was probably completely useless advice with XBee being involved.

Maybe a servo library that doesn't use interrupts can be found also?

Yeah, I had a thought to add that, but don't off-hand know of one. If you have a recommendation I'll put it in, or if you put one in a separate answer I'll up-vote it.

Perhaps I'll add in https://www.arduino.cc/reference/en/libraries/servo-hardware-pwm/   if you add an answer, I'll remove it and specifically call out your answer.


text:
Can I control solid state relay directly from arduino digital pin?
I want to switch on/off some AC device using solid state Omron G3MB relay
I know that for magnetic relay there should be transistor and flyback diode, but what about SSR?
Can I connect it directly to arduino digital pin without any transistors and anything else?
In a closer look on special arduino module, we can see some extras. Are they necessary? I want to put solid state relay (not separated module) into my custom PCB, and I'm confused about that extras.

yes, that's the idea; it's just a resistor and an LED as far as Arduino sees.

Mate, according to the datasheet you provided it's safe to hook the arduino, but to be safe put a resistor in between, just to be sure the SS relay don't pull up to much current from the Arduino, as this may casue harm to your device.

@k.Cyborg am I misreading the datasheet? The way I read it, there are multiple (sub-) models of the G3MB. Some of which don't require a resistor, but some do.

According to the datasheet there are multiple models.
Some already have an input resistor for the led (in the opto-isolator) inside the package, but some don't. For the ones that don't have a resistor inside, you'd need to add one yourself, to limit the current to around 10mA.
Some models also have a snubber circuit inside the package. The need for this depends on what kind of load is connected (inductive vs. resistive (AFAIK)).
I thinks the green thing, in the picture, is a fuse. On the other side of the SSR you can see and indicator led, transistor, and 3 resistor (one to limit current to the SSR, one to limit the current through the indicator led, and on for the base of the transistor.). They probably use a transistor, because the current for the SSR and the indicator led combined, is to high for certain micro controllers.

the transistor is likely used as a current limiter for the ssr's led, just like commercial fotek et al.

The answer is a qualified yes.  In this case the relay is optically isolated from the load so there is no cross conduction. You need to connect the relay to the Arduino power +5 and Ground supply. I would not connect more then one to any arduino pin as the relay has a max requirement of 20mA. Not all SS relays are the same so you need to check there specs if you use another one.


text:
ov2640 with 18 pin and no arducam shield
I bought this ov2640 camera module with 18 pins and I don't have shield to insert it to. I am looking for a library or working code on this my camera sensor but all I kept getting was arducam examples or at most ov7670 example code. Can anybody help me out here?
The image of the module is at this link https://i.sstatic.net/tUVg0.jpg
PS: I am using an arduino due
(Edit: Added image of camera module)

not an Arduino specific question

@jsotola, sorry, why would this be not arduino specific? the questions asks how to wire a camera module to Arduino Due without the Arduino shield usually used for this type of camera

I am using arduino due

There is a datasheet for the module at https://www.mpja.com/download/35647mpdata.pdf
It references the Arducam library at https://github.com/ArduCAM/Arduino/tree/master/ArduCAM.
The library specifically supports this camera type. By studying the camera specific code you may get a better idea of what is required. To connect the module directly to a Due, the work that was designed to be done by the intended shield would need to be replicated. Which seems non-trivial.

Thank you. I had a headway. The library can help you connect to the ov2640 camera and communicate with it through sccb interface. There is a whole lot of spi interface configuration that doesn't apply in my own case, so I didn't use the spi pin. Getting the snapshot of what is in the D0 - D7 pins without an assistant of library is not as trivial for a learner as you think. I am using arduino due and would like to facilaitate this using DMA. I want to send the snapshot straight to sd card.

You’re welcome, I’m glad the suggestion helped you progress. As I thought, non-trivial (i.e., complicated).  A further suggestion might be to finalize the basics of interfacing directly to the camera before introducing DMA? It may be worth a separate question on the DMA idea? If you resolve the direct interface you might consider posting an answer to this question, I’m sure there will be other readers interested in how you did it.


text:
ESP8266 with HC05 : expecting to receive more bytes then the 63 received
I'm trying to read a Ant BMS 32H with a ESP8266 and a HC05 module.
BMS is sending 146 bytes when asking for these by sending DB DB 0 0 0 0 (HEX)
I did test with my android phone and the app 'Serial Bluetooth Terminal' and I receive/see the 146 bytes.
When doing this with the ESP8266/HC05 I only receive 63 bytes.
I saw already that I shouldn't use delays before reading the serial buffer, as this could cause buffer overflows.
I have no clue on what the reason could be ... hope someone has some more knowledge then I do ...
Please see my code I use ( I didn't post the Process_Data() routine as this one is called afterwards )
Initial I tried without the cosmetic visualization ( extra lines of code taking cpu cycle to execute) and it give the same result
The result I receive :
---------------------------------------------------
Sending request (6 bytes) : DB DB 0 0 0 0  Answer :
00:AA 01:55 02:AA 03:FF 04:02 05:7B 06:08 07:43 08:08 09:43
10:08 11:47 12:08 13:41 14:08 15:3B 16:08 17:45 18:08 19:41
20:08 21:46 22:08 23:43 24:08 25:41 26:08 27:43 28:08 29:46
30:08 31:44 32:08 33:41 34:08 35:49 36:08 37:41 38:08 39:43
40:08 41:42 42:08 43:3F 44:08 45:3F 46:08 47:46 48:08 49:44
50:08 51:4F 52:08 53:38 54:08 55:3E 56:08 57:47 58:08 59:47
60:08 61:45 62:08
Bytes received : 63

My .ino :
#include <SoftwareSerial.h>;
SoftwareSerial EEBlue(12, 13); // RX | TX // AT command mode
// byte message[] = {0x5A, 0x5A, 0x5A, 0x00, 0x00, 0x5A, 0xDB, 0xDB, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x0A };
byte message[] = {0xDB, 0xDB, 0x00, 0x00, 0x00, 0x00 };
byte bms[147]; // 82 + 65 = 147 bytes
int i;
int x;
int highbyte, lowbyte;
uint16_t a16bitvar;
unsigned int BattSOCG;
float BattPowerG;

void setup()
{
  Serial.begin(115200);
  delay(500);
  EEBlue.begin(38400);  //38400 Baud for AT commands , set by command : AT+UART=38400,1,0 or AT+UART=9600,1,0
  delay(500);
  Serial.println();
  Serial.println("Serial and Bluetooth started.");
  Serial.println(); Serial.println("");
}

void loop()
{
  AskBMSData();
  GetBMSData();
  Process_Data();
  delay(3000);
}

// ---------------------------------------------------------
void AskBMSData()
{
  Serial.print("Sending request ("); Serial.print(sizeof(message)); Serial.print(" bytes) : ");
  for (i=0; i<sizeof(message); i++)
  {
    Serial.print(message[i], HEX);
    Serial.print(" ");
  }

  EEBlue.write(message, sizeof(message));
}

void GetBMSData()
{
  Serial.println(" Answer :");
  // Feed any received bluetooth data to Terminal.
  i=0;
  while (EEBlue.available()) {
    bms[i]= EEBlue.read();
    if(i<10) Serial.print("0");
    Serial.print(i); Serial.print(":");
    if(bms[i]<16) Serial.print("0");
    Serial.print(bms[i], HEX);
    Serial.print(" ");
    x = (i+5)/10; x = 10*x-1; if(i==x) Serial.println();
    i++;
  }
  Serial.println(); Serial.print("Bytes received : ");Serial.println(i);Serial.println();
}

// --------------------------------------------------------

Code changed based on Chrisl's response to :
void GetBMSData()
{
  Serial.println(" Answer :");
  // Feed any received bluetooth data to Terminal.
  i=0;
  if (EEBlue.available()) {
      while (i<146) {
        bms[i]= EEBlue.read();
        i++;
        }
  }

  for (z=0; z<i; z++) {
    if(z<10) Serial.print("0");
    Serial.print(z); Serial.print(":");
    if(bms[z]<16) Serial.print("0");
    Serial.print(bms[z], HEX);
    Serial.print(" ");
    x = (z+5)/10; x = 10*x-1; if(z==x) Serial.println();
  }
  Serial.println(); Serial.print("Bytes received : ");Serial.println(i);Serial.println();
}

with result :
---------------------------------------------------
Sending request (6 bytes) : DB DB 0 0 0 0  Answer :
00:AA 01:55 02:AA 03:FF 04:02 05:71 06:08 07:23 08:08 09:23
10:08 11:26 12:08 13:21 14:08 15:1B 16:08 17:25 18:08 19:1E
20:08 21:27 22:08 23:24 24:08 25:1E 26:08 27:23 28:08 29:27
30:08 31:25 32:08 33:1F 34:08 35:28 36:08 37:21 38:08 39:22
40:08 41:22 42:08 43:1C 44:08 45:23 46:08 47:28 48:08 49:26
50:08 51:31 52:08 53:17 54:08 55:1E 56:08 57:28 58:08 59:29
60:08 61:25 62:08 63:FF 64:FF 65:FF 66:FF 67:FF 68:FF 69:FF
70:FF 71:FF 72:FF 73:FF 74:FF 75:FF 76:FF 77:FF 78:FF 79:FF
80:FF 81:FF 82:FF 83:FF 84:FF 85:FF 86:FF 87:FF 88:FF 89:FF
90:FF 91:FF 92:FF 93:FF 94:FF 95:FF 96:FF 97:FF 98:FF 99:FF
100:FF 101:FF 102:FF 103:FF 104:FF 105:FF 106:FF 107:FF 108:FF 109:FF
110:FF 111:FF 112:FF 113:FF 114:FF 115:FF 116:FF 117:FF 118:FF 119:FF
120:FF 121:FF 122:FF 123:FF 124:FF 125:FF 126:FF 127:FF 128:FF 129:FF
130:FF 131:FF 132:FF 133:FF 134:FF 135:FF 136:FF 137:FF 138:FF 139:FF
140:FF 141:FF 142:FF 143:FF 144:FF 145:FF
Bytes received : 146

you are printing six characters for every one received ... you could use hexadecimal addressing to reduce the number of lines printed ... first line would be 00 : AA 55 AA FF 02 71 08 23 08 23 08 26 08 21 08 1B ... second line 10 : 08 25 08 1E 08 27 08 24 08 1E 08 23 08 27 08 25

Indeed a nice way to visualize the output, but as I like to pick out certain byte visually, I like to be able to see at first view with one I need. But way of visualizing doesn't change/solve the problem, as now I do the visualization afterwards ones I have all bytes in variables.

I see 2 things, that might give you problems. First the one with a higher chance of being the important point:
You use
while (EEBlue.available())

in your GetBMSData() function. With serial (and especially over a packeted protocol like bluetooth) the sender might introduce pauses in the transmission of the data (for example when it needs to wait for more data, doing other tasks than sending or when a bluetooth packet ends and a new one must be send). You cannot control if and when these pauses happen. They might be big enough so that your while() loop can clear the internal buffer of the SoftwareSerial library without already having received the full message.
With serial you cannot think of a message as one block of data, which arrives together at the same time. You need to account for it to take its time. For example you could loop inside that function, until you have received the full message. That would fit to your current code structure. Something like this:
while(i<146){
  if(EEBlue.available()){
    bms[i]= EEBlue.read();
    i++;
  }
}

Note: If for whatever reason less than the expected number of bytes is send, this code will block forever - or until it received that many bytes.
Or - if you want to do it non-blocking (also rewriting the rest of the code), then you could just allocate a buffer big enough for the whole message and only place the bytes as they arrive inside that buffer. The rest (like sending the data out over Serial can then be done, when you have all the data bytes of the message. In this case you don't need a while loop, since the loop() function already handles the looping. You just test on very loop iteration if data is available and read it. After you read a byte you test for the message being complete. If yes, do the printing and processing.

The second problem is not that probable, but I still want to include that here. You are doing quite some printing inside the while loop, printing at least 6 bytes for every received byte. Serial can take some time and if it takes to long you can fill up your buffer in the background, effectively loosing data. I would suggest using the while loop to just read() the bytes and save them in your array. The printing can then be done after the full message was received. For the human reading the Serial printout it will not be different, but you can prevent losing data this way.

I don't know exactly how to implement "For example you could loop inside that function, until you have received the full message." I tried to change my code, see edit original post

I added a small code snippet to my answer. Hope that helps


text:
Arduino data-types
(Im new to the arduino side of stackexchange). Im working on a worksheet for to begin with arduino. I have prior experiences working with arduinos, but problem is new for my field of expertise. Any help will be well appreciated (need help pls uwu)
Problem statement:

I tried different methods to obtain those values, but all are to vain.
Methods that I tried so far:

using limits.h, floats.h and inbuild variables of those library -- Problem: Im getting wrong minimum and maximum values for float and double:
Code:

#include <stdio.h>
#include <limits.h>
#include <float.h>
#include <math.h>

char fltmax[250];
char fltmin[250];
char dblmax[250];
char dblmin[250];

void sint() {
  Serial.print("Range of signed int: ");
  Serial.print(INT_MIN);
  Serial.print(" to ");
  Serial.print(INT_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(int));
  Serial.println(" bytes");
}
void usint() {
  Serial.print("Range of unsigned int: 0 to ");
  Serial.print(UINT_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(unsigned int));
  Serial.println(" bytes");
}
void schar() {
  Serial.print("Range of signed char: ");
  Serial.print(SCHAR_MIN);
  Serial.print(" to ");
  Serial.print(SCHAR_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(signed char));
  Serial.println(" bytes");
}
void uschar() {
  Serial.print("Range of unsigned char: 0 to ");
  Serial.print(UCHAR_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(unsigned char));
  Serial.println(" bytes");
}
void slong() {
  Serial.print("Range of signed long: ");
  Serial.print(LONG_MIN);
  Serial.print(" to ");
  Serial.print(LONG_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(signed long));
  Serial.println(" bytes");
}
void uslong() {
  Serial.print("Range of unsigned long: 0 to ");
  Serial.print(ULONG_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(unsigned long));
  Serial.println(" bytes");
}
void sshort() {
  Serial.print("Range of signed short: ");
  Serial.print(SHRT_MIN);
  Serial.print(" to ");
  Serial.print(SHRT_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(signed short));
  Serial.println(" bytes");
}
void usshort() {
  Serial.print("Range of unsigned long: 0 to ");
  Serial.print(USHRT_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(unsigned short));
  Serial.println(" bytes");
}
void flt() {
  Serial.print("Range of float: ");
  dtostrf(FLT_MIN, -1, 50, fltmin);
  Serial.print(fltmin);
  Serial.print(" to ");
  sprintf(fltmax,"%e", FLT_MAX);
  puts(fltmax);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(float));
  Serial.println(" bytes");
}
void dbl() {
  Serial.print("Range of double: ");
  dtostrf(DBL_MIN, -1, 50, dblmin);
  Serial.print(dblmin);
  Serial.print(" to ");
  dtostrf(DBL_MAX, -1, 0, dblmax);
  Serial.print(dblmax);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(double));
  Serial.println(" bytes");
}

void setup() {
  Serial.begin(115200);
  sint();
  usint();
  schar();
  uschar();
  slong();
  uslong();
  sshort();
  usshort();
  flt();
  dbl();
}

void loop() {
}

Other than using dtostrf(), I found better alternatives at exchange here too such as: Print unsigned long long in ESP8266 and https://www.tutorialspoint.com/c_standard_library/c_function_sprintf.htm

I tried combining both where the test code that I used before actual implementation:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <float.h>
#include <limits.h>

void setup () {
  char str[30];
  Serial.begin(115200);
  snprintf(str, 30, "Value of float max = %e", FLT_MAX);
  /*puts(str);*/
  Serial.print(str);
  return(0);
}
void loop(){

}

But puts(str) is not getting printed in the serial monitor.  Then It clicked, that I have to use Serial.(code) for it to get printed in serial monitor, but it ended up in Serial.puts(str) code not found. Then I tried just Serial.print(str), but it just outputs Value of float max = ? (Initially, before I wrote this problem here, it output Va only, which i have no idea how it changed, but its still wrong). What do I do now? also, Why cant I use puts to print in serial monitor?
The board im using for this is Arduino UNO (ATmega328P)

There are two issues here.
One is that the Arduino core uses Serial to handle serial I/O, rather
than the traditional libc interface (printf(), puts() and co.). The
avr-libc does provide the traditional stdio functions, but these will
not work unless you tell them where stdout is, which is a bit complex.
The take away is to just use the methods of Serial for accessing the
serial port.
Then there is the question: why did it print “Value of float max = ?”.
The reason is that the avr-libc does not provide by default support for
formatting floating point numbers with sprintf(). That support is
quite expensive in flash space, and it is omitted unless you link with a
specific version of the avr-libc. The simple workarounds are:

Use Serial.print() to both format and print floating point numbers,
which is inconvenient for very small or very large numbers.
Use dtostre() or dtostrf() to format them.

In your case, dtostre() is a better fit:
void setup() {
    char val[40];
    Serial.begin(9600);
    Serial.print("Range of float: ");
    dtostre(FLT_MIN, val, 5, 0);
    Serial.print(val);
    Serial.print(" to ");
    dtostre(FLT_MAX, val, 5, 0);
    Serial.print(val);
    Serial.println();
}

void loop(){}

prints:
Range of float: 1.17549e-38 to 3.40282e+38

Ahh I see, I'll read up the documentation of dtostre(), my guess its similar to dtostrf(), but the output is rather %e instead of %f, but I'll read just in case. Also, I just found out that DBL_MIN and FLT_MIN does not provide the absolute minimum of the data type but rather the positive minimum value :) I'll just add a dash symbol manually and use DBL/FLT_MAX for the minimum value. Though its not ethical/code of stackexchange to say thank you in the comments, I'll still thank you, i've been stuck on this question for the past week :'(


text:
Proteus potentiometer value always highest

#include <Servo.h>

#define potpin A0
int savebutton=2;
int button1=3;
int button2=4;
int button3=5;

Servo servo1;
Servo servo2;
Servo servo3;

int servo1ipos=90;
int servo2ipos=90;
int servo3ipos=90;

int val=0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(savebutton,INPUT);
  pinMode(button1,INPUT);
  pinMode(button2,INPUT);
  pinMode(button3,INPUT);

  servo1.attach(6);
  servo2.attach(7);
  servo3.attach(8);
  servo1.write(servo1ipos);
  servo2.write(servo2ipos);
  servo3.write(servo3ipos);

}

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

}

int servocontrol(){
  if(digitalRead(button1)==LOW){
    potvalue();
    Serial.println(val);
    servo1.write(val);
    delay(200);
  }
}
int potvalue(){
    val=analogRead(potpin);
}

Basicly I only read 1023 value instead of potentiometer value I couldnt figure it out need help.
Update:
I came up solution by connecting 5V into Arduino's VCC pin.

I don't know Proteus - does it automagically connect the VCC and GND pins of the Uno to sensible nets?

@Mat yes also you can see from voltmeter I can change voltage with potentiometer.

@Mat I dont  know you mentioned about VCC on arduino but yeah I solve the problem with connecting 5V into Arduino's VCC pin. Thanks.

Please take the [tour] to learn how this site works. Especially, please don't mark a question with "[SOLVED]", this is not a forum. Instead, write an own answer and mark, after you are allowed to do it. Visitors select answered question after the number of answers and the green mark, not by the title.

Oh, you put your solution as the comment on your edit--that makes it very difficult to see. You should write up your work as an answer, and give yourself a green checkmark for solving your own problem.  Or at the very least, copy your edit summary message into your question.

@DaveX I added on my post thanks for information.

I came up solution by connecting 5V into Arduino's VCC pin.


text:
Arduino Nano: Send a few bytes over Serial with as little delay as possible
My scenario is the following:
I have a few buttons connected to an Arduino Nano, which is connected to my PC over Serial. Now I want to send a few bytes whenever a button is pressed, to be interpreted by my Computer. However, I noticed a significant, unregular delay (feels like something between almost instantaneous transmission up to a delay of easily ~300 milliseconds), until the message is received by my computer, and I want to get rid of that.
I understand that Arduinos make use of a Serial Buffer, and only send over data once the buffer is full (or some sort of timeout probably), and I think that is the culprit - however I don't see a way of forcing the Arduino to send the data ASAP. I tried just sending over exactly 64 bytes (which, according to what I read, should be the buffer size), but that doesn't help as well (can I however decrease the buffer size or is there a way to send bytes exactly until the buffer is full?)
I don't think baudrate changes anything either, as I'm experiencing problems with the "ping" rather than with the bandwidth (and I also tried anything from 9600 to 115200).
Maybe I'm also completely wrong and the delay happens on the side of my computer, but I don't know if there is anything to change that - I'm looking at the Serial Monitor or at a small pyserial script, both of which have the delay:
arduino = serial.Serial(serial_port}, 115200, timeout=.1)
while True:
    data = arduino.readline().decode("UTF-8").strip()
    if data:
        print(data)

The code on the Arduino-side boils down to:
#include <digitalWriteFast.h>

#define button1_pin 2

int button1_state = 0;
int last_button1_state = 0;

void setup() {
  Serial.begin(115200);
  pinMode(button1_pin, INPUT_PULLUP);
  while (!Serial) { delay(50); }
  Serial.println("Started");
}

void loop() {
  button1_state = digitalReadFast(button1_pin);

  if (button1_state != last_button1_state) {
    if (button1_state == LOW) {
      Serial.write("d\n");
    } else {
      Serial.write("u\n");
    }
    last_button1_state = button1_state;
    delay(20);
  }
}

Then there's also the weirdest thing which I noticed but am not sure about if it's at all plausible:
When the window of the Serial Monitor (the one that ships with the Arduino IDE) is not completely full (meaning there are only some 1-20 rows and the window doesn't need to scroll), I notice the aforementioned delay, but if the Serial Monitor is full (so new content will be on the last line and the window automatically scrolls a bit), I don't. As soon as I clear the output of the window, it's there again. I don't know what to make of this observation, because I definitely don't have any reasonable clue why that may be the case, so maybe it's also just my imagination :shrug:. Using the python-code there is no such behaviour, and the transimission always seems to have a ping of at least 200-300ms.
I hope my problem is understandable, and like I said I am really unsure what even is the culprit (and I see that it's also highly likely that it's on the side of my computer), but does anybody have any idea how I can decrease this delay? Thanks a lot!

"only send over data once the buffer is full" - You are thinking wrong here. As soon as any byte is in the send buffer (put there by Serial.write() or its siblings) the transmission begins in the background (orchestrated through interrupts). The baudrate also defines how long the transmission of a byte needs, so it also correlates to the "ping" in a way. Have you tried changing the timeout value in the python code? At the moment you have 0.1 (I guess this is seconds). Does this change anything in the outcome?

Ohh, that's good to know, thanks! But that only confuses me more tbh ^^ And no, changing the timeout doesn't change anything. Because of @hcheung 's answer I tried other timeout-values, but as mentioned, the timeout is only maximal time one call of readline() waits until it returns, and neither increasing nor decreasing changes something.
Note however that I see the same issues in the Arduino IDE's Serial Monitor, so I don't think this problem is on the side of pyserial.

My question is resolved, thanks for your contribution :)

"Slowing down to speed up". -   a Chinese proverb

The problem is with your python code. Not sure what your computer's operating system is, but if you are using Mac or Linux, if you run top on command line, you will see you have a high CPU utilization causing by your python script. This is because your your python while True loop constantly looping without giving the chances for other processes on your computer to use the CPU, bear in mind that Linux, MacOS or Windows are not designed as a real-time operating system.
So how to solve the problem? put your while True loop to sleep for a short period of time, this allows other processes on your computer to have chance to run and you will see the CPU utilization go down significantly and everything will running smoothly.
import time
arduino = serial.Serial(serial_port}, 115200, timeout=.1)
while True:
    data = arduino.readline().decode("UTF-8").strip()
    if data:
        print(data)
    time.sleep(0.01)

With this slight delay, I've seen some CPU utilisation drop from 90% to 3.5%. This is quite a common mistake that many python programmers made, including some quite experienced programmers who are not familiar with network programming.
Try it out and let me know.

Interesting suggestion! First of all, I'm using Linux.
Second, I know the difference between active and passive waiting, but I as far as I understand, when I have a Serial connection with a timeout, is passive waiting - as far as I understand pyserial's documentation @ https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial , readline() returns either if it receives something, or it times out (0.1secs in my case) - which means the time.sleep(0.01) is superflous, as it already waits 0.1 seconds per iteration. I also only have maximally 1% CPU utilization by this script.

Also, I see the same issues on the Arduino IDE's Serial Monitor, which made me think the problem is on the Arduino side in the first place

Haha now to the big BUT:
Because I didn't trust what I saw in the serial Monitor/python's print I also wrote another test script which reacts to the click by sending a serial message back to the Arduino triggering an LED, and as far as I could judge, this LED had the same delay as the prints... however in the thread that reacts to the button-click, my code was while True: if not led_queue.empty(): serial.write(led_queue.get()), which is very ACTIVELY waiting, and as soon as I added a time.sleep(0.1) in THAT method, the LED reacted instantaneously!!! So you're right after all!

Timeout is different, it is for breaking out from constant polling Serial. Arduino is an MCU which is architecturally different from CPU, and  is designed for running a super loop without much of the background processes running like Linux.

But fact is, when I set the timeout of the Serial connection to, say, two seconds, and add a print in the loop body (not conditional on if there is data or not) the print is only executed every two seconds (or whenever there is data sent from the Arduino) - so the timeout acts the same way an added time.sleep would do

Answering my own question in case anybody experiences the same problem eventually: @hcheung's answer was almost correct after all - see the comments to that question.
Important take-away however:
don't trust the Serial Monitor or Python's print to check how quickly the arduino and your computer communicate!
When ponging back to the Arduino to let it trigger an LED, I noticed that the actual transmission is definitely faster than my eye, far from the 200ms delay I mentioned in the question.
So the problems for me were
a) the other code I used to test the connection but didn't post here was faulty
b) The delay I saw in the Serial Monitor/python's print is not the delay of the serial communication but apparently somewhere later in the printing of the respective content.
Serial communication is definitely faster than the human eye :)

TL;DR: Any time there is an OS, windowing system, etc. involved that isn’t explicitly hard real-time, results are non-deterministic by definition.


text:
Difference between DS1307 and IN1307N, I am using RTClib for making rtc module using IN1307N getting RTC is not running
#include <Wire.h>
#include "RTClib.h"

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {

#ifndef ESP8266
while (!Serial); // for Leonardo/Micro/Zero
#endif

Serial.begin(9600);
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}

if (! rtc.isrunning()) {
Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
// This line sets the RTC with an explicit date & time, for example to set
// January 21, 2014 at 3am you would call:
// rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
}
}

void loop () {
DateTime now = rtc.now();

Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(" (");
Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
Serial.print(") ");
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();

Serial.print(" since midnight 1/1/1970 = ");
Serial.print(now.unixtime());
Serial.print("s = ");
Serial.print(now.unixtime() / 86400L);
Serial.println("d");

// calculate a date which is 7 days and 30 seconds into the future
DateTime future (now + TimeSpan(7,12,30,6));

Serial.print(" now + 7d + 30s: ");
Serial.print(future.year(), DEC);
Serial.print('/');
Serial.print(future.month(), DEC);
Serial.print('/');
Serial.print(future.day(), DEC);
Serial.print(' ');
Serial.print(future.hour(), DEC);
Serial.print(':');
Serial.print(future.minute(), DEC);
Serial.print(':');
Serial.print(future.second(), DEC);
Serial.println();

Serial.println();
delay(3000);
}

If i use 57600 i'll get random symbols in one line 1 line.
I have connected PIN5 IN1307N to A4, PIN4 IN1307N to A5

What about pull-ups on SDA/SCL?

yup applied. 10k to vcc

Maybe try to use 4k7 (or two 10k in parallel) and shorter wires but it's a wild guess. And you can try I2C scanner if RTC is even found. BTW value 165 is not so random as you think. It's 0xF*10 + 0xF e.g. 0xFF to BCD code.

Scanning...
No I2C devices found

Check your wiring: A4 = SDA -> PIN5,  A5 = SCL -> PIN6 (PIN4 is GND terminal)

yup thats connected..

Following this circuitry solved my issue but still i've not understand the difference between DS1307 and IN1307N.

There shouldn't be any difference. Just different factory making the chip.

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


text:
Stepper and Line tracker
I am making a program which will use stepper motors and a line tracking sensor. The idea is that when the linetracker detects a black surface both steppers must move forward, and when the linetrackers is not detecting black surface it should scan the surface for a black surface.
I made some code which makes the robot move forward if the linetracker has a set value. The problem is that when I implement the code for the line-tracker. My steppers are going to run very laggy probably because the arduino is constantly scanning if the value of the linetracker is below 500.
My question is, is there a way to program the line tracker without having it interfere on my stepper motors? (The stepper motors run smooth without the linetracker)
#include <RedBot.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
//Code voor de LCD
#define I2C_ADDR       0x3F // Define I2C Address (use i2c scanner if necessary)
#define BACKLIGHT_PIN  3
#define En_pin         2
#define Rw_pin         1
#define Rs_pin         0
#define D4_pin         4
#define D5_pin         5
#define D6_pin         6
#define D7_pin         7
#define LED_OFF        0

#define LED_ON         1
//Hier worden de eigen functies gemaakt door HEX code
uint8_t battery_1[8]=   {0xe,0x1b,0x11,0x11,0x11,0x11,0x11,0x1f};
uint8_t battery_2[8]=   {0xe,0x1b,0x11,0x11,0x11,0x11,0x1f,0x1f};
uint8_t battery_3[8]=   {0xe,0x1b,0x11,0x11,0x11,0x1f,0x1f,0x1f};
uint8_t battery_4[8]=   {0xe,0x1b,0x11,0x11,0x1f,0x1f,0x1f,0x1f};
uint8_t battery_5[8]=   {0xe,0x1b,0x11,0x1f,0x1f,0x1f,0x1f,0x1f};
uint8_t battery_6[8]=   {0xe,0x1b,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f};
uint8_t battery_7[8]=   {0xe,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f};
LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

RedBotSensor left_sen    =    RedBotSensor(A3);
RedBotSensor right_sen   =    RedBotSensor(A2);
int lineStandard         =    800;

void setup()
{
  scherm();
  //stepper 1
  pinMode(13,OUTPUT);   // Step
  pinMode(12,OUTPUT);   // Dir
  //stepper 2
  pinMode(11,OUTPUT);   //Step 2
  pinMode(10,OUTPUT);   //Dir 2
  Serial.begin(9600);
  Serial.println("IR Sensor Readings:: ");
  //delay(500);
}

void loop()
{
  Serial.print(left_sen.read());
  Serial.print("\t");
  Serial.print(right_sen.read());
  Serial.println();

  if(right_sen.read() > lineStandard)
    {
      left();
    }

  else if(left_sen.read() > lineStandard)
    {
      right();
    }

  if((left_sen.read() > lineStandard) && (right_sen.read() > lineStandard) )
    {
      Stop ();
    }

  else
    {
      forward();
    }
}

void right()
{
  //stepper 1
  digitalWrite(13,HIGH);
  delayMicroseconds(1500);
  digitalWrite(13,LOW);
  delayMicroseconds(1500);
  //stepper 2
  digitalWrite(11,LOW);
  delayMicroseconds(1500);
  //Oranje lampje, rechter kant
  //digitalWrite(3,HIGH);
}
void Stop ()
{
  digitalWrite(13, LOW);
  delay(1500);
  digitalWrite(11, LOW);
  delay(1500);
  //Rood lampje aansturen
  //digitalWrite(2,HIGH);
}
void left()
{
  //stepper 1
  digitalWrite(11,HIGH);
  delayMicroseconds(1500);
  digitalWrite(11,LOW);
  delayMicroseconds(1500);
  //stepper 2
  digitalWrite(13,LOW);
  delayMicroseconds(1500);
  //Oranje lampje, linker kant
  //digitalWrite(4,HIGH);
}
void forward()
{
  //stepper 1
  digitalWrite(13,HIGH);
  delayMicroseconds(1500);
  digitalWrite(13,LOW);
  delayMicroseconds(1500);
  //stepper 2
  digitalWrite(11,HIGH);
  delayMicroseconds(1500);
  digitalWrite(11,LOW);
  delayMicroseconds(1500);
  //Groen lampje sturen
  //digitalWrite(1,HIGH);
}

void scherm()
{
  lcd.begin(16,2);
  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
  lcd.setBacklight(LED_ON);
  //Hier worden de eigen symbolen benoemd
  lcd.createChar(1, battery_1);
  lcd.createChar(2, battery_2);
  lcd.createChar(3, battery_3);
  lcd.createChar(4, battery_4);
  lcd.createChar(5, battery_5);
  lcd.createChar(6, battery_6);
  lcd.createChar(7, battery_7);
  lcd.home();
  lcd.print("Batterij Status");
  lcd.setCursor(0, 1);
  //Schrijf de batterij icoontjes naar het LCD
  lcd.write(1);
  lcd.write(2);
  lcd.write(3);
  lcd.write(4);
  lcd.write(5);
  lcd.write(6);
  lcd.write(7);
}

Try removing your serial print statement. It's detrimental to performance. And then read up on how to use interrupts, which you could use in combination with a competitor.

You could use a driver for stepper motors, so you can control the motors using PWM. You call the PWM from Arduino using analogWrite(). After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (Read this link from the Arduino page). This will help you in your project, and maybe find the solution to your problems when reading the sensor at the same time. An advantage of using PWM is that you can also made smoother movement for your robot when it is crossing or finding its way.
I also recommend using two sensors (I suppose you're using IR), so if you want to track the black surface and there is a turn, one of the sensors will be detecting the line, and the other one wont. That way you can assume which way should the robot turn, making it more efficient.

Thanks for the comment, I am currently using 2 line tracking sensors which are working fine. My code is also finished but the problem with the laggy steppers persists. I am going to try using two arduinos.

Well, using two arduinos would be a waste if you plan to do a simple function as a line tracker with two microcontrollers like the ATmega328P. Since the driver use MOSFETs to control your robot, you will be saving a redundancy in your circuit. Just a recommendation. If you don't have any problem with it, just go ahead.

Also, buying a driver should be cheaper than other Arduino link

I am using a drivers, It is the polulu drv8825

But the problem still persists, Am I doing something wrong in the coding?

@Jordakoes please can you update the new code? If you haven't you should be using analogWrite() for PWM control.

Sorry for the very late response, I had a long christmas holiday. Anyways, I was wondering how do I implement PWM in my current code? (I have updated my code in the post above.)

is there a way to program the line tracker without having it interfere on my stepper motors?

you are simply generating a pwm signal to drive your steppers. So make that generation in the background, through a timer isr for example.
Thus your main loop() will just be doing the low priority stuff.

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


text:
Help avoiding floating point math
I'm using a Texas Instruments DRV2605 haptic controller in my project to drive a LRA vibration motor. I would like to calculate the LRA rated voltage during run time using the formula below as provided in the datasheet:

I'm successfully calculating the rated voltage, but the calculation requires floating point calculations and I would like to avoid that because I'm low on available flash space on my ATTiny85 micro controller. Here is how I'm currently calculating the rated voltage value:
uint8_t LRA_closed_loop_rated_voltage( uint16_t voltage ) {
   float RatedVoltage;
   uint16_t SampleTime = 300;
   uint16_t frequency = 175;

   RatedVoltage = ( (float) voltage ) * sqrt( 1 - ( ( 4 * SampleTime + 300 ) * 0.000001 ) * frequency );
   RatedVoltage = ( RatedVoltage * 255 ) / 5300;

   return RatedVoltage;
}

The function above is just a simplified version showing the calculation and the SampleTime and frequency variables are set to their defaults values here. The voltage argument is the actuator's rated voltage in millivolt.
EDIT: Even though SampleTime and frequency have fixed values in the function above, their values will be determined by reading the relevant registers in the final implementation. SampleTime may have one of the following values: 150, 200, 250, 300 and the frequency will depend on the manufacturers specifications for the actuator.
It was easy to overcome the floating point issue on the other calculations by simply scaling up the values by 1000 (fixed point arithmetic):

ODClamp = ( Vpeak * 255) / 5.6 /* Vpeak in volts */

TO:

ODClamp = ( Vpeak * 255) / 5600 /* Vpeak in millivolts */

How can I do the calculation in question without having to use floating point?

The only difficulty seems to be evaluating the function f(x) = sqrt(1 − x). There are many ways to compute fixed-point approximations of this function, and there is no universal solution. The “right” approximation for your application depends on: 1) what is the possible range for x? 2) what level of accuracy do you require?

Calculate values off-line and generate a table in PROGMEM. See the Adafruit examples.

Or use a polynomial approximation. If sampleTime and frequency are close to their default values, a Taylor expansion around those values might be good enough. E.g. at order 2 you have f(x) ≈ 0.99801 − x (0.47861 + x 0.19736).

As I said in my comment, it is all about computing an approximation of
sqrt(1-x). Assuming the typical resonance frequency is between 175
and 235 Hz, then we have

(4 × 150 µs + 300 µs) 175 Hz ≤ x ≤ (4 × 300 µs + 300 µs) 235 Hz

i.e.

0.1575 ≤ x ≤ 0.3525

This range is small enough to try a simple polynomial approximation. A
linear approximation is just a bit too crude for 8 bit resolution.
Playing with quadratic polynomials, I found this approximation which is
good to 3.1e-5 in the relevant range:

√(1−x) ≈ 0.9983795 − x (0.480515 + x 0.1955)

This can be easily implemented in fixed point by scaling everything by a
factor 216 = 65536. One has to take care that any
product of two such fixed point numbers must be computed in
32 bits, and the result subsequently divided by 65536. Which gives
the following implementation:
/*
 * Compute a fixed point approximation of f(x) = sqrt(1-x).
 * Valid for x in [.1575, .3525].
 * Argument and result scaled by 2^16.
 */
uint16_t f(uint16_t x)
{
    return 65430 - x * (31491 + x * 12812UL / 65536) / 65536;
}


text:
ESP8266 ISO 8601 string to tm struct
I have a web service that returns timestamps in ISO 8601 format, e.g., "2021-06-25T12:00:00"
I'm trying to turn the timestamp string into a tm type struct from the ESP8266 library <time.h>, to perform time calculations using the difftime() function.
I've been referring to the Redhat time functions https://sourceware.org/newlib/libc.html#time, as it seem to be compatible with the ESP library, though all i can find are functions converting tm structs to timestamp strings. Are there any functions to convert a string timestamp into a tm struct and then back into epoch? Or what would be the best way to approach this kind of conversion on the ESP8266 platform?

Does this answer your question? How to parse 20180810T143000Z to time_t

Thank you! This method works too, though i find the answer below to be more useful.

sorry yes, there is a different format. strptime can't parse a timestamp without delimiters.

Try strptime from the time.h.
void setup()
{

  struct tm tm = {0};
  char buf[100];

  // Convert to tm struct
  strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);

  // Can convert to any other format
  strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);
  Serial.printf("%s", buf);
}

void loop()
{
    yield();
}

Thank you. The method above works. I just formatted my string as "%Y-%m-%dT%H:%M:%S",instead.


text:
Code works in Arduino Web editor but not in PlatformIO IDE or Arduino IDE with board Nicla Sense ME
Here is the verbose for the Arduino IDE:
Flashing with command:/Users/hakan/.arduino-create/arduino/openocd/0.11.0-arduino2/bin/openocd -d2 -s /Users/hakan/.arduino-create/arduino/openocd/0.11.0-arduino2/share/openocd/scripts/ -f interface/cmsis-dap.cfg -c transport select swd; adapter speed 1000 -f target/nrf52.cfg -c telnet_port disabled; init; reset init; halt; adapter speed 10000; program {/var/folders/dy/qqk78q1956s1pb94hc4y_x5m0000gn/T/arduino-create-agent511362936/sketch_mar22a.elf}; reset run; shutdown

Open On-Chip Debugger 0.11.0+dev-gab95bac57-dirty (2021-05-11-10:57)

Licensed under GNU GPL v2

For bug reports, read

http://openocd.org/doc/doxygen/bugs.html

debug_level: 2

adapter speed: 1000 kHz

Info : CMSIS-DAP: SWD Supported

Info : CMSIS-DAP: FW Version = v1.0

Info : CMSIS-DAP: Serial# = AA7EAA93

Info : CMSIS-DAP: Interface Initialised (SWD)

Info : SWCLK/TCK = 1 SWDIO/TMS = 1 TDI = 0 TDO = 0 nTRST = 0 nRESET = 1

Info : CMSIS-DAP: Interface ready

Info : clock speed 1000 kHz

Info : SWD DPIDR 0x2ba01477

Info : nrf52.cpu: hardware has 6 breakpoints, 4 watchpoints

Info : starting gdb server for nrf52.cpu on 3333

Info : Listening on port 3333 for gdb connections

target halted due to debug-request, current mode: Thread

xPSR: 0x01000000 pc: 0x00006dc4 msp: 0x20010000

target halted due to debug-request, current mode: Thread

xPSR: 0x01000000 pc: 0x00006dc4 msp: 0x20010000

** Programming Started **

Info : nRF52832-CIAA(build code: E0) 512kB Flash, 64kB RAM

Warn : Adding extra erase range, 0x0001d8f8 .. 0x0001dfff

** Programming Finished **

shutdown command invoked

Here is the one for PlatformIO:
AVAILABLE: blackmagic, cmsis-dap, jlink, nrfjprog, nrfutil, sam-ba
CURRENT: upload_protocol = cmsis-dap
openocd -d2 -s /Users/hakan/.platformio/packages/tool-openocd/scripts -f interface/cmsis-dap.cfg -f target/nrf52.cfg -c "transport select swd;" -c "adapter speed 1000" -c "program {.pio/build/nicla_sense_me/firmware.hex}  verify reset; shutdown;"
xPack OpenOCD x86_64 Open On-Chip Debugger 0.11.0+dev (2021-10-17-00:18)
Licensed under GNU GPL v2
For bug reports, read
        http://openocd.org/doc/doxygen/bugs.html
debug_level: 2

Info : auto-selecting first available session transport "swd". To override use 'transport select <transport>'.
Warn : Transport "swd" was already selected
swd
adapter speed: 1000 kHz

Info : CMSIS-DAP: SWD  supported
Info : CMSIS-DAP: FW Version = v1.0
Info : CMSIS-DAP: Serial# = AA7EAA93
Info : CMSIS-DAP: Interface Initialised (SWD)
Info : SWCLK/TCK = 1 SWDIO/TMS = 1 TDI = 0 TDO = 0 nTRST = 0 nRESET = 1
Info : CMSIS-DAP: Interface ready
Info : clock speed 1000 kHz
Info : SWD DPIDR 0x2ba01477
Info : nrf52.cpu: Cortex-M4 r0p1 processor detected
Info : nrf52.cpu: target has 6 breakpoints, 4 watchpoints
Info : starting gdb server for nrf52.cpu on 3333
Info : Listening on port 3333 for gdb connections
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x000008e4 msp: 0x20000400
** Programming Started **
Info : nRF52832-CIAA(build code: E0) 512kB Flash, 64kB RAM
Warn : Adding extra erase range, 0x00052738 .. 0x00052fff
** Programming Finished **
** Verify Started **
** Verified OK **
** Resetting Target **
shutdown command invoked

Platform.ini content:
[env:nicla_sense_me]
platform = nordicnrf52
board = nicla_sense_me
framework = arduino
monitor_speed = 115200
debug_speed = 1000
upload_protocol = cmsis-dap

lib_deps =
    Wire
    /Users/marcopolo/Documents/PlatformIO/Projects/C1/include/Arduino_BHY2
    /Users/marcopolo/Documents/PlatformIO/Projects/C1/include/ArduinoBLE-master

The code is a very basic blink example.
Edit: Here is the error:
++ MbedOS Fault Handler ++

FaultType: HardFault

Context:
R   0: 20010000
R   1: 0001BB1C
R   2: 00000005
R   3: 00000000
R   4: 20010000
R   5: 20010000
R   6: 0001BB1C
R   7: 00000000
R   8: 00000000
R   9: 00000000
R  10: 00000000
R  11: 00000000
R  12: FFFFFFFF
SP   : 20002CA0
LR   : 00010CB7
PC   : 00013B3E
xPSR : A1070000
PSP  : 20002C80
MSP  : 2000FFC0
CPUID: 410FC241
HFSR : 40000000
MMFSR: 00000000
BFSR : 00000082
UFSR : 00000000
DFSR : 00000000
AFSR : 00000000
BFAR : 20010000
Mode : Thread
Priv : Privileged
Stack: PSP

-- MbedOS Fault Handler --

++ MbedOS Error Info ++
Error Status: 0x80FF013D Code: 317 Module: 255
Error Message: Fault exception
Location: 0x13B3E
Error Value: 0x2000303C
Current Thread: main Id: 0x20001A78 Entry: 0x13057 StackSize: 0xC00 StackMem: 0x200020D0 SP: 0x20002CA0
For more info, visit: https://mbed.com/s/error?error=0x80FF013D&tgt=NICLA
-- MbedOS Error Info --

Edit: Same board works pretty fine in Windows OS.

Verbose compilation and compare parameters. For example micro:bit had issue with -DNRF52 (second port wasn't available - but for 52832 it's valid define) and -DUSE_LFXO used external 32k crystal configuration for millis(), but there is none on the board and so on...

I appreciate if you can elaborate.

I'm reading about that board and you might be able to run it in debugger - you can just step through the program and what is causing that hard fault. (micro:bit has 1-click debug too same this board)

@KIIV, I have just found out that the board works fine in Windows. Regarding the cause, the program is a very simple blink.


text:
How to program Arduino manually via STK500?
I am trying to program an Arduino Nano (with an ATmega328P) from an ESP32 that is attached to its UART and the reset pin. I have to do this via the ESP, because the Arduino is supposed to run on its own, detached from a PC (where I could use an existing programmer for it). But its program should be changable, hence, it is attached to the ESP, which is accessible from a web server via Wifi, so that the Arduino can be reprogrammed on request. I almost got the whole setup figured out: The server is running, files can be sent to the ESP, and the ESP can talk with the Arduino Bootloader. The only problem is that I cannot get the Arduino to execute new programs.
The whole procedure goes like this: The server communicates with the ESP, sends the HEX file of the Arduino sketch (which is successfully verified by a checksum, so this part is working properly). Then, the ESP pulls the reset pin of the Arduino and waits for a while before it attempts to talk to its bootloader. Then, it basically does the same sequence of STK500 commands as avrdude.
I really just copied the commands from the avrdude log after executing
avrdude -c arduino -vvvvv -p m328p -b 57600 -P /dev/ttyUSB0 -U flash:w:sketch.hex:i

and skipping query commands like which firmware version it uses etc. So, basically: enter programming mode, erase chip, re-enter programming mode, write the hex file to flash, starting from address 0, moving in steps of 128 bytes (using 1's to pad the last message to the full size of 128 bytes). Then afterwards reading back the file from the Arduino and veryfing that all bytes match (which they do!) and leaving the programming mode (which is the very last thing that happens in the avrdude log). Afterwards, I trigger the reset. I am using exactly the same type of file which I gave to avrdude, and all the responses of the Arduino bootloader exactly match the values from the avrdude log.
But whereas the Arduino just starts executing the sketch after this procedure when using avrdude, in my own implementation it just blinks its LED in a regular interval (when the test sketch should make it blink short, long, short, long etc.). I don't get what's going wrong here. I thought that the blinking might represent an error code, but I couldn't find any documentation about that. I feel like I've searched the whole Internet (including arduino stackexchange), and I even looked at the avrdude source code to check if there's something else done after the last STK500 command, that is not listed in its log. I feel (hope) that I'm very close to having it work and this whole thing just needs like a one-line fix, but I don't know what else to try anymore and would greatly appreciate a second opinion from someone more experienced.

In your stated programming sequence, I don't see where you are resetting the AVR chip.

You should reset the chip after programming.

Sorry, I forgot to mention that. I tried to reset it via the ESP, as well as manually via button. But it doesn't seem to make a difference.

@programonkey In that case I think the only remaining possibility is that you are not properly programming the AVR code using your ESP32.  At this point you are giving us a high-level description of what you are doing, and that sounds correct, but you are asking for detailed evaluation of your problem but not providing that level of detail.  I think your next step to get help here is to post your schematic and your code.

Are you using some kind of level shifter? Rememeber the Arduino is 5v and the ESP32 is 3v3, I dont think this should be the problem tho, but can be :-)

No, I'm not using a level shifter, but thanks for the hint. :)

Bridging an existing programmer via network is an interesting idea, but my application requires a certain level of decentrality, which would be destroyed by this solution.

Okay, by comparing the data packets my implementation sends with those from the avrdude log for the same sketch, I finally found the cause of trouble. I was sending the hex file byte-by-byte exactly as it is read from storage. But of course, the metadata needs to be skipped (i.e. the addresses at the beginning of each line, the magic bytes at the end of each line, and the newline). I added this simple fix, and now it works fine.
EDIT: Here is the preprocessing code from my Python3 script:
import codecs

program = b''
for line in open('sketch.hex', 'rb'):
    program += codecs.decode(line[9:-4], 'hex')

so a question without code, an answer without code. nobody could answer your question if the problem was in the code you didn't show. how should this be useful as Q&A? add the code or delete the question please

The reason why I didn't post code with my question is that I thought that the error was on the conceptual level, and so I saw no point in posting kilobytes of code before clarifying whether the underlying procedure is actually correct. I did add the code that fixed my implementation to my answer now, though. I do think that this question might be of relevance for someone facing a similar undertaking, if only to compare and verify his approach.

now I understand what you do. it would be simpler to work with a binary of the sketch, not with hex file. https://github.com/jandrassy/ArduinoOTA/blob/2a591d028c5384849cdaf4ee7398b97b528bc054/extras/avr/platform.local.txt#L4

Yeah, that would've been better. But since initially, I didn't know how to go about, I just followed some online examples and tried to mimic the resulting behavior of avrdude as closely as possible. I am smarter now.