text:
Programming Arduino Uno R3 to trigger a relay once every 24 hours
I programmed an Arduino Uno R3 to trigger a relay once every 24 hours from the moment it is powered on.
I calculated milliseconds and used the function delay().
24 hours * 60 minutes each hour * 60 second every minute * 1000 milliseconds every second
so I used :
delay(86400000)

for 86 million and 400 thousands milliseconds.
Currently, I'm still testing it...
Will this work? If not, is there a better built-in function/library or even external library to do it?
The relay trigger doesn't have to be very accurate at the very exact time each day.
I don't need it to be very accurate, it can shift few minutes every few months or so, thats okay with me.
But how about after few months or years of use ? Will it shift the timing much?
I read somewhere about using millis() function
and others use an RTC (Real Time Clock) module.
I don't want to use anRTC module, I am looking for a programmatical solution.
OR will my previous method using delay() work for such a very high number of milliseconds?

“Few minutes every few months” is about 20 ppm. You can expect close to 1,000 ppm clock drift on the Uno. Even if you calibrate out the drift, frequency wander will likely defeat your calibration to worse than 20 ppm in a day or so. You really need an RTC for meeting your accuracy requirement. See Arduino clock frequency accuracy for a detailed experimental analysis on the frequency stability of the Arduino (the Uno has a resonator similar to the one on the Pro Mini).

So, No programmatical solution, it must be a hardware solution for this, by using an RTC external module or maybe by making my own pcb circuit installing a crystal oscillator on it and connecting it to the arduino digital pin output ?
And the link you posted is very useful thank you, I'm going to read it.
I don't want to use an RTC so i don't have to change the battery every while, Or can i just connect the battery socket to the arduino 3.3v dc power pin?
Thank you very much Edgar, Greatly Appreciated

The 3.3V pin of the Uno is a power output, you cannot power your Arduino through it. If you replace the Arduino by a bare ATmega on your own PCB, you can replace the resonator by a 16 MHz crystal oscillator. It may still drift too much, but the drift rate will be consistent and you can calibrate it out. Alternatively, clock the ATmega off its internal RC oscillator, and plug a clock crystal into the TOSC pins of its asynchronous timer. Used this way, the asynchronous timer is like an RTC built into the ATmega.

Thank you Edgar for your very informative inputs, contributions and your very kind help.
I will research your idea more deeply and try to apply it practically soon. and yes the 3.3 v arduino pin is power output i mean to use it to power the RTC module not to power the arduino, I found a local supply that have 3 different models of RTC modules, PCF8523, DS1307 and DS3231 and DS1302 IC only and DS1307 8 dip package IC, I made some research and found that DS3231 is the most accurate with high precision because it has temperature sensor that adjust any timing drift/shift periodically

Yes, the delay() will work, as will other methods based on the millis() counter. However, delay() will make it impossible to do something else in the meantime.
Look up Blink without delay for an example of how to accomplish such a delay while being able to do other things in your code while waiting.
Casting
When dealing with large numbers such as your 24-hour delay, make sure to explicitly cast those numbers as unsigned long, or expressing them with the "UL" extension (like for example 86400000UL). This explicitly tells C++ to expect an "unsigned long" (which in Arduino Uno terms is a 32-bit unsigned number).
In your case (with such an obviously large number), the compiler will automatically choose the right type. In other cases (for example, if you change the expression to 24*60*60*1000), the compiler will not automatically generate an unsigned long and you need to force it by changing the first part of the expression to an unsigned long: 24UL*60*60*1000 or, alternatively (unsigned long) 24*60*60*1000.
Accuracy
The accuracy of the timing will be dependent on the type of oscillator on your particular Arduino board. Many Arduinos or their clones use a Ceramic Oscillator that generally have an accuracy of about 0.1 to 0.5%, meaning a possible deviation of 43 seconds per day and as such maybe too inaccurate for your purposes. If your Arduino has a Crystal oscillator, it will be much more accurate (to something like 150ppm, meaning a maximum deviation of about 1 second per day under normal conditions).

Thank you very much StarCat
I have arduino uno R3 (revision three) and I see a rectangular crystal on the board, So I guess its as accurate as you described....1 second per day thats around 365 seconds ( 6 minutes) per year...so thats fine.
And I will use the UL Unsigned Long extension on my code..better, Even if it works with normal delay() without assigning this data type.
I Appreciate your input
And the article link you posted about doling multiple things at once while program wait is very helpful, Thank you very much

The "UL" suffix is not needed, as the compiler will pick a data type large enough to hold the value. It is needed though, at least for the first factor, if you want to write an expression like 24UL * 60 * 60 * 1000.

@EdgarBonet, That's true of course. My opinion is that explicitly casting, where appropriate, doesn't hurt and will prevent hard to find errors in cases where it's not so clear-cut (like in your example). I've expanded the explanation in the answer.

Update: I tested the project for a full 24 hours from 9:03 PM Wednesday evening since i powered the arduino on to the next day thursday evening and i noticed it shifted/delayed around 3 minutes, cause it triggered the relay at around 9:06 PM (so thats around 3 mins delay) so 3 mins shift * 30 days a month = 90 mins (an hour and a half timing shift each month) I'm going to test it for another 24 hours now and see...

delay() takes an unsigned long; I think what you do will work.
When in doubt, you could always do something like this:
for (int hours = 0; hours < 24; hours++) {
  for (int mins = 0; mins < 60; mins++) {
    for (int secs = 0; secs < 60; secs++) {
      delay(1000);
    }
  }
}

It will be wildly inaccurate though, because the clock is inaccurate and will also drift with temperature, made worse because a resonator is used instead of a crystal.
You will get nowhere near an accuracy of a few minutes per month this way, whatever "delaying" method you use; the hardware isn't up to it.

Thank you very much ocrdu
I have arduino uno R3 (revision three) and I see a rectangular crystal on the board, So I guess its more accurate?

As far as I know, the UNO R3 also has a resonator on the board for the CPU, and the crystal is used for the USB timing only. This may be different between revisions of the board. Still, even with a crystal, I doubt you will get the accuracy you want.

Hmm, Didn't know that, So the only solution is to use a different arduino board completely?
I just need the relay triggered once each day, thats all...doesn't have to be precise timing.

Well, what I would do is just try it with a time of, say, two hours (or however long you can be bothered to observe the thing), see if it is close enough, and if not, introduce a calibration factor in the code to compensate. Measuring equipment would make this an easier process.
If it turns out you can't properly adjust that way because of clock instability, you can always add a precise RTC module.
Primitive engineering, maybe, but worth a shot.

Re “I think what you do will work”: It will. delay() can handle up to ULONG_MAX milliseconds, which is about 49.7 days. 2. Re “introduce a calibration factor”: if the experiment is performed in just a few hours, this will likely work. But then frequency wander will defeat the calibration at longer time scales. You can expect the clock frequency to “random walk” with a typical √t law at time scales longer than a few seconds.

Hello Edgar, I tested the project for a full 24 hours from 9:03 PM Wednesday evening since i powered the arduino on to the next day thursday evening and i noticed it shifted/delayed around 3 minutes, cause it triggered the relay at around 9:06 PM (so thats around 3 mins delay) so 3 mins shift * 30 days a month = 90 mins (an hour and a half timing shift each month)
I'm going to test it for another 24 hours now and see...

@Felix0004: 3 minutes in one day is 3×60÷86400 ≈ 0.002, or 2,000 ppm. Kind of high, but still within the tolerance of a typical ceramic resonator.

@EdgarBonet, And after another 24 hours, there is another 3 minutes drift, it started @ 9:09 PM...so its kinda constant drift for 3 minutes each day, which equal an hour and a half each month, thats still alot yeah.

You could try enclosing the Uno in a temperature controlled "oven", say a plastic enclosure with a very low power heater (even a suitable resistor might do) and thermo sensor in with it. It should reduce some of the variation in the crystal frequency.

But i can't Apply the heat permanently to the uno, i wanted a permanent solution : )
Thank you JRobert


text:
Get client information on BLE
So I'm working on a personal project using bluetooth abilities to start a BLE server and want to automatically retrieve a client's information after it's connected: ID so I can keep track of clients, but brand/make, serial.. and other information would be good as well.
My ServerCallback class looks like this
class ServerCallbacks: public BLEServerCallbacks
{
  void onConnect(BLEServer* pServer)
  {
    deviceConnected = true;
    BLEDevice::startAdvertising();

    String deviceID = "XXXXX";

    Serial.print("new device ");
    Serial.print(deviceID);
    Serial.println(" connected");

  };

  void onDisconnect(BLEServer* pServer)
  {
    deviceConnected = false;

    String deviceID = "XXXXX";

    Serial.print("device ");
    Serial.print(deviceID);
    Serial.println(" disconnected");

    pServer->startAdvertising(); // restart advertising
  }
};

so, what is your actual problem and what is your question?

@jsotola How to retrieve client information after it's connected to the server. Multiple central devices will be querying this information and so I want to track who did and who did not

source: Stack Exchange

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

sort: votes


text:
Uploading doesn't work on MKR1000
I received the error bellow when I tried to upload any sketch on my MKR100. I uninstall/reinstall de COM drivers and the arduino IDE and nothing solve the problem. I bought another MKR1000 thinking the ahrdare was the problem , but I got the same errors.
Also If I try to open the serial monitor I got :
Error opening serial port 'ÇOM12'(Port not found)
Can someone help me?
Sketch uses 47444 bytes (18%) of program storage space. Maximum is 262144 bytes.
Forcing reset using 1200bps open/close on port COM12
processing.app.debug.RunnerException
at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
at processing.app.SketchController.upload(SketchController.java:732)
at processing.app.SketchController.exportApplet(SketchController.java:703)
at processing.app.Editor$UploadHandler.run(Editor.java:2055)
at java.lang.Thread.run(Thread.java:748)
Caused by: processing.app.SerialException: Error touching serial port 'COM12'.
at processing.app.Serial.touchForCDCReset(Serial.java:107)
at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
... 5 more
Caused by: jssc.SerialPortException: Port name - COM12; Method name - openPort(); Exception type - Port not found.
at jssc.SerialPort.openPort(SerialPort.java:167)
at processing.app.Serial.touchForCDCReset(Serial.java:101)
... 6 more

did you select the correct port?

Thank for you answer. No, the IDE can find the board and port but I got those errs anyway.

read the answer, not the question. did you try the double reset mentioned in the answer?

I'm sorry my mistake, I tried the double tap on reset button and it works!!. Thanks for your help.

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


text:
Connect k-type termocouple using o-amp
first of all I have to say that this is my first Arduino thing. I'm trying to connect a k-type termocouple to my Arduino using an LM2904 Oamp, Yes I know that this is not the best solution but is the only that I have right now due to the pandemic situation, that I can't get a dedicated module as an MAX6675
This is what I have done:

note: The Grnd symbol next to 2.6k resistor is a handwritten error, its not connected in the circuit
my problem is that with this circuit I'm having 3.7V on the arduino analog input even before connect the termocouple. After connect it, the read is about 2.6V and it starts to increase as expected when heat is applied.
My problem is if I have 2.6V for 32°C for temperatures over 200°C I will have more than 5V. Any help with this?

Do you need to measure temperatures over 200°C? If not, thats ok. The opamp cannot output a higher voltage than its supply voltage, thus it cannot exceed 5V in your circuit. If you need to measure also that range, you need to change the amplification of your circuit by changing the resistor values

The MAX6675 is obsolete. You should be considering the MAX31855 or MAX31856 instead.

@chrisl, thanks for yours suggestions, I know that I wold have to change the values of my resistors, but, its normal to have 3.7V in the output even with no inputs? with my current setup I have expect to have near .5V not 2.6V I dont know what is wrong here

Why do you think, that you get 0.5V without anything connected? The pin would be floating then, so the opamp will be amplifying the noise, thats flying around.

@chrisl no I spect to have near 0.5V for on 32°C which is 1.2mV on the K thermocouple table


text:
A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header
rst:0x10 (RTCWDT_RTC_RESET),boot:0x1f (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
I am getting this error in my esp32 devkit v1
How to solve it?
I am using arduino IDE for programming the esp32

google the error ... you really need to do research first, post a question if research fails to resolve your problem

do you have the right com port selected? or CH340 driver si missing? the error in title is from console, the message in text is from Serial Monitor?

@Juraj the error is in serial monitor of arduino IDE


text:
Ardunio wireless voice transmission
I made a project based on calling with gsm module and arduino and  now i want to transmit to voice wirelessly to my bluetooth earphone which module should i use for this purpose.

google "arduino bluetooth sound module"

An ESP32 could to that


text:
The Pfieffer Vacuum Protocol for RS485
i am working on a control Interface for serveral Components including turbo Pumps from the company Pfeiffer.
The communication will be done according to the The Pfieffer Vacuum Protocol for RS485.
Does any one have experience with this Protokoll or is there a library that can be used for this art of communication.
I will use a MAXCHIPRS485 for the communication between Arduino (SerialPorts) and the Pumps RS485 Port.
the Wiring is clear .
I want to ask if someone already has done a similar Code that sends and reads from the Pump continuously.
Thanks in advance

please ask a question that is about an Arduino


text:
Unable to allocate memory
I'm trying to send a SMS and read data from Firebase with my NodeMCU Amica V2. The  code works fine when I either only send a SMS or only read data from Firebase. However, when I combine this two codes SMS isn't sent. This is the error I get:
+ Connected.
+ Post an HTTP send SMS request.
+ Connection is closed.
+ Response:

31.0630+ Using fingerprint 'BC B0 1A 32 80 5D E6 E4 A2 29 66 2B 08 C8 E0 4C 45 29 3F D0'
+ Connecting to api.twilio.com
- Connection failed.
Last SSL error was:
Unable to allocate memory for SSL structures and buffers.
ERRCODE: -1000

And here is my code:
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <base64.h>
#include "OneWire.h"
#include "DallasTemperature.h"
#include <ArduinoJson.h>
#include <string>
using namespace std;
#include <sstream>
#include <iostream>
#include "FirebaseArduino.h"

// Your network SSID and password
const char* ssid = "*****";
const char* password = "*****";

const char* account_sid = "*****";
const char* auth_token = "*****";
String to_number    = "+*****";
String from_number = "+*****";
String message_body    = "Hello from Twilio and the ESP8266!";

// Find the api.twilio.com SHA1 fingerprint using,
//  echo | openssl s_client -connect api.twilio.com:443 | openssl x509 -fingerprint
const char fingerprint[] = "BC B0 1A 32 80 5D E6 E4 A2 29 66 2B 08 C8 E0 4C 45 29 3F D0";

#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

#define FIREBASE_HOST "***.firebaseio.com"
#define FIREBASE_AUTH "*****"

float temp1 = 0;
//float temp2 = 0;
String b;
int c;

String urlencode(String str) {
  String encodedString = "";
  char c;
  char code0;
  char code1;
  char code2;
  for (int i = 0; i < str.length(); i++) {
    c = str.charAt(i);
    if (c == ' ') {
      encodedString += '+';
    } else if (isalnum(c)) {
      encodedString += c;
    } else {
      code1 = (c & 0xf) + '0';
      if ((c & 0xf) > 9) {
        code1 = (c & 0xf) - 10 + 'A';
      }
      c = (c >> 4) & 0xf;
      code0 = c + '0';
      if (c > 9) {
        code0 = c - 10 + 'A';
      }
      code2 = '\0';
      encodedString += '%';
      encodedString += code0;
      encodedString += code1;
    }
    yield();
  }
  return encodedString;
}

String get_auth_header(const String& user, const String& password) {
  size_t toencodeLen = user.length() + password.length() + 2;
  char toencode[toencodeLen];
  memset(toencode, 0, toencodeLen);
  snprintf(toencode, toencodeLen, "%s:%s", user.c_str(), password.c_str());
  String encoded = base64::encode((uint8_t*)toencode, toencodeLen - 1);
  String encoded_string = String(encoded);
  std::string::size_type i = 0;
  // Strip newlines (after every 72 characters in spec)
  while (i < encoded_string.length()) {
    i = encoded_string.indexOf('\n', i);
    if (i == -1) {
      break;
    }
    encoded_string.remove(i, 1);
  }
  return "Authorization: Basic " + encoded_string;
}

void setup() {
  Serial.begin(115200); // 115200 or 9600
  delay(1000);        // Give the serial connection time to start before the first print.
  Serial.println(""); // Newline after garbage characters.
  Serial.println(F("+++ Setup."));

  // ----------------------------------------------------
  Serial.println("+ Connect to WiFi. ");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("+ Connected to WiFi, IP address: ");
  Serial.println(WiFi.localIP());

// ----------------------------------------------------
sensors.begin();
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}

void loop() {
      sensors.requestTemperatures();
  temp1 = sensors.getTempCByIndex(0);
  Serial.print(temp1);
  b = Firebase.getString("002/alarm");
    c = b.toInt();
    Serial.print(c);
      if (temp1 > c) {
      // Use WiFiClientSecure to create a TLS 1.2 connection.
  //  Note, using a cert fingerprint is required.
  WiFiClientSecure client;
  client.setFingerprint(fingerprint);
  Serial.printf("+ Using fingerprint '%s'\n", fingerprint);
  const char* host = "api.twilio.com";
  const int   httpsPort = 443;
  Serial.print("+ Connecting to ");
  Serial.println(host);
  if (!client.connect(host, httpsPort)) {
    Serial.println("- Connection failed.");
    char buf[200];
                int err = client.getLastSSLError(buf, 199);

                buf[199] = '\0';

                Serial.println("Last SSL error was:");

                Serial.println(buf);

                Serial.print("ERRCODE: ");
                Serial.println(err);
///* END snippet from pushdata-io project */
//              return false;
  }
  Serial.println("+ Connected.");
    Serial.println("+ Post an HTTP send SMS request.");
  String post_data = "To=" + urlencode(to_number)
                     + "&From=" + urlencode(from_number)
                     + "&Body=" + urlencode(message_body);
  String auth_header = get_auth_header(account_sid, auth_token);
  String http_request = "POST /2010-04-01/Accounts/" + String(account_sid) + "/Messages HTTP/1.1\r\n"
                        + auth_header + "\r\n"
                        + "Host: " + host + "\r\n"
                        + "Cache-control: no-cache\r\n"
                        + "User-Agent: ESP8266 Twilio Example\r\n"
                        + "Content-Type: application/x-www-form-urlencoded\r\n"
                        + "Content-Length: " + post_data.length() + "\r\n"
                        + "Connection: close\r\n"
                        + "\r\n"
                        + post_data
                        + "\r\n";
  client.println(http_request);
  // Read the response.
  String response = "";
  while (client.connected()) {
    String line = client.readStringUntil('\n');
    response += (line);
    response += ("\r\n");
  }
  Serial.println("+ Connection is closed.");
  Serial.println("+ Response:");
  Serial.println(response);
      }
  delay(5000);
}

Does that mean that the NodeMCU doesn't have enough memory? I also tried changing delay() to milis(), but that didn't solve the problem.
Any help would be appreciated!

There should be enough memory, but all that String concatenation you're doing isn't going to help matters.

Thanks for your reply. Do you have any suggestions on how to modify the code? Sorry, I'm new to Arduino.

Just print each line or part of line separately. You don't need to have it all in one string.

So if I understand you correcly, I should use empty println(" ") between each println() that has a value.


text:
Cannot successfully implement singleton
I have spent the better part of today trying to figure out why I can't get this to work...
I have this project where, because of previous design considerations, have implemented a singleton class that initializes a bunch of separate sensors in this system that I am running.
The system was originally built for the Particle Boron, but now I am trying to make it work with the Adafruit Feather M0, so I have had to refactor several things and omit lots of lines of Particle RTOS specific things.
However, in doing this, I find that my singleton class no longer works.
Sensors.h:
.
.
.

class Sensors{

    static Sensors *instance;

public:
    static Sensors *getInstance() {
        if (!instance) {
            instance = new Sensors;
        }
        return instance;
    }

}

private:
    Sensors();

.
.
.

Sensors.cpp:
.
.
.

Sensors::Sensors() : dht22(DHTPIN, DHTTYPE) {
#ifdef PLATFORM_ID
    sensorLog("app.Sensors");
#endif
}

.
.
.

main.ino:
.
.
.

// Sensors
Sensors *Sensors::instance = nullptr;
Sensors *allSensors = allSensors->getInstance();

void setup(){

.
.
.

As I try to compile this with ArduinoISP, no matter what I try, I get the following error:
sketch/main.ino.cpp.o: in function `Sensors::getInstance()':
sketch/lib/Sensors/src/Sensors.h:23: undefined reference to `Sensors::Sensors()'
collect2: error: ld returned 1 exit status
exit status 1
[Error] Exit with code=1

I have tried things like changing the line
instance = new Sensor;

to
instance = new Sensor();

making the instance public, changing the Sensor constructor, but all of this to no avail. Could this be a compiler issue? Why would this work on a Particle board, but not an Adafruit Feather M0?

is the cpp in the same folders as the ino?

Unlike RTOS, Arduino is single threat and no OS, there is really not have any benefit to implement singleton in Arduino environment...

private: Sensors() is outside your class - and your class lacks the required ; at the end of it. Your code is uncompilable as it stands.

@Majenko, the constructor is used only in getInstance. it can be private and is declared there. the compiler founds it. the error is at linking

I had the same problem when referencing classes from multiple files, remember to put at the top of your header file (ending in .h) #pragma once on files that get referenced more than once!
Edit1: Also after you declare your class you need to specify where your static variable will be stored.
After the class declaration write:
type *Class::variable;
To declare the static variable.
For example:
#pragma once
//#includes

class Screen
{
protected:
  static void (*StateMachineStep)(int);
  static SSOLED *oled;
  static Player *player;

public:
  Screen() {}

};

void (*Screen::StateMachineStep)(int);
SSOLED *Screen::oled;
Player *Screen::player;

Edit2: formatting

Singletons aren't a thing in Arduino. Sure, you could do it, but in general you'd make a class then instantiate a global object for that class. Most often that global object is instantiated in the library itself, not the sketch.
Unless you're using an advanced chip with an RTOS (such as ESP32) and making use of the threads of that RTOS heavily there is no benefit to having a singleton.
But to answer your actual question: it's probably because you are trying to use the Sensors() constructor at a time before the compiler knows what the Sensors() constructor is. You would have to add some form of forward declaration so that the compiler knows what you mean when you talk about the Sensors() constructor.  In general a simple:
class Sensors;

at near the top of your header before the class is actually defined can help in these situations;

Or the OP can simply move the private contructor from the private section to above the public section. Then it should be private (because there is no modifier above and private is the default) and declared before its usage.

@PeterPaulKiefer, ordering of class members in the class declaration doesn't matter

@Juraj You are right. Please, forget what I said. I'll leave the comment as an example of ignorance ;-) and to help other not to have the same misconception. Now, I think the main problem is that the getInstance method is implemented in the class definition and the constructor is not (just declared). So, probably it helps also if we move the implementation of thegetInstance() into the cpp file an leave only the signatur declaration in the hpp file. Or is there a reason why this would not work?

@PeterPaulKiefer, I think the cpp is not compiled, because it is in some folder ignored by IDE

@christopolise Are you still with us?  What Juraj mentioned in the answer of my last comment sounds good.  The CPP file might not be compiled. Did you investigate in that direction? Juraj mentioned that in a comment for the OP, but I have to apollogize for not having recognized it.

@Juraj Yes, I agree with you. Your idea is also underlined by the fact that, the code worked on a RTOS system, but not after using the ADUINO IDE. I hope the OP is still here, as I'm interested in the final answer ;-)


text:
circuit breaker/fuse necessary for IoT home monitor?
In most 12v CCTV power supplies, each power cable is behind a glass fuse.  I haven't seen fuses or circuit breakers used when distributing 5v power used in IoT projects.  Is there a reason overcurrent protection is not needed in these projects?
edit:
I'm thinking specifically about fire safety.  e.g. the risk of a short circuit overheating 22awg wire run through the house?

Is there a reason overcurrent protection is not needed in these projects?

You're comparing apples and oranges.
The two systems are completely different and have different concerns.
Case in point:

You want to burgle somewhere with CCTV installed. You can creep up on one camera unobserved.
You know a little about electronics and figure if you cut the feed to the camera you can short out the power and blow the whole system, thus letting you wander in unobserved.

But there's fuses on each feed, so all you do is disable the one camera and everything else is fine, catching you red handed.
Go directly to jail. Do not pass go. Do not collect £200.
Now... do you really care that much if all your home temperature sensors lose power because of a fault in one? Probably not. And the chances of there being a fault other than from human negligence is slim. Sure, you could add fuses, but why add the expense? It's really not needed for such a non-critical system.

edit: I'm thinking specifically about fire safety. e.g. the risk of a short circuit overheating 22awg wire run through the house?

22AWG wire has a resistance of about 53Ω per km. Say you have a loop of cable 20m long (10m there and 10m back again) and it shorted out at the far end. That's round about 1Ω.
At 5V you'd be drawing 5A of current.
If you have a really powerful power supply then it would try and supply that, and the wire would warm up - giving off about 25W of heat over the entire length. You might feel a bit of warmth from it.
Of course, most people would be using a smaller power supply than that for simple IoT things, so the power supply would just go "No. You're not having that!" and would die, or its internal fuse would blow. Or it would drop the voltage and get hot itself.
The chance of being able to start a fire from 5V over 22AWG from a normal power supply is pretty much zero. You're more likely going to start a fire from using a low quality power supply that itself melts and catches fire (i.e., a counterfeit Chinese phone charger).
With a very powerful power supply (tens of amps or more) and a short circuit close to the source (so low resistance) the wire will melt. Just that. It'll melt. Once melted there's no circuit, so nothing else happens. There's your fuse right there.
Once a wire has melted it doesn't continue to burn. And you don't get arcs at low voltages. It takes a lot of work to start a fire from low voltages. A lot of work and a lot of current.

thanks for the response.  I didn't even think about that aspect of it.  I'm wondering more about fire-safety (please see edit).  Thanks!

@zwiebelspaetzle See my edit too.

interesting, thanks!


text:
Trouble programming custom ATMEGA2560 board
I need some help. I copied the heart of MEGA2560 design into a new project. I have the new PCBs with blank MCUs and now I need to get things programmed. (I have an existing project that runs on a MEGA2560)
I was able to get the MEGA16U2 programmed using the procedure here: https://www.arduino.cc/en/Hacking/DFUProgramming8U2, (I loaded "Arduino-usbserial-atmega16u2-Mega2560-Rev3.hex") and it shows up in the Arduino IDE.
I got the ATMEGA2560 bootloader loaded using the Arduino-as-ISP instructions here: https://www.arduino.cc/en/Tutorial/ArduinoISP
But, now when I try to program my board with the with Arduino IDE (through the USB connection of the MEGA16U2), I just get:
avrdude: stk500v2_ReceiveMessage(): timeout

The full output of the IDE is:
Sketch uses 30056 bytes (11%) of program storage space. Maximum is 253952 bytes.
Global variables use 1280 bytes (15%) of dynamic memory, leaving 6912 bytes for local variables. Maximum is 8192 bytes.
/home/xxxxx/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude -C/home/xxxxx/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf -v -patmega2560 -cwiring -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/arduino_build_464802/yyyyy.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/xxxxx/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf"
         User configuration file is "/home/xxxxx/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

An error occurred while uploading the sketch

I can see the RX led of the MEGA16U2 flashing, and the data at the RX pin of the ATMEGA2560 IC, indicating that data is getting to the MCU from the IDE, but there is no corresponding  TX activity.
The IDE and USB cable can program an Elegoo MEGA2560 clone with no problem.
Is this a baud rate problem? A protocol problem? What should be my next debugging step?
Thanks!

EDIT: Per Nick Gammon's comment, I have run his chip detector script. Here is the output:

Atmega chip detector.
Written by Nick Gammon.
Version 1.20
Compiled on Sep  5 2020 at 07:17:55 with Arduino IDE 10812.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x98 0x01
Processor = ATmega2560
Flash memory size = 262144 bytes.
LFuse = 0xFF
HFuse = 0xD8
EFuse = 0xFD
Lock byte = 0xCF
Clock calibration = 0x88
Bootloader in use: Yes
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 8192 bytes starting at 3E000

Bootloader:

3E000: 0x0D 0x94 0x89 0xF1 0x0D 0x94 0xB2 0xF1 0x0D 0x94 0xB2 0xF1 0x0D 0x94 0xB2 0xF1

<....snipped for length....>

3FFF0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

MD5 sum of bootloader = 0xD9 0xE6 0x6B 0x4E 0xD1 0xA6 0x11 0x2C 0x61 0x8F 0x9B 0xD5 0x5D 0x24 0xE2 0x13
Bootloader MD5 sum not known.

First 256 bytes of program memory:

00: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
10: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
20: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
30: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
40: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
50: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
60: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
70: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
80: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
90: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
A0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
B0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
C0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
D0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
E0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
F0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

Programming mode off.

I assume you have a few Arduinos lying around. Can you please run my chip detector sketch and report the results? (Amend the question).

Do you have the right fuse settings on the 2560 for your clock?

Have you built a 16Mhz external clock (e.g. a crystal oscillator)? When I tried something similar with a ATMega-328P (home design based upon an UNO) , I noticed that when I first uploaded my program it ran super slow (because the default fuses are to run on the internal RC oscillator / 8 = 1 MHz). Reloading the bootloader onto my design resulted in it running at normal speed - because it seems that this activity reset the fuses to use an external clock. Check out this post for reading and writing the fuses https://www.instructables.com/id/How-to-change-fuse-bits-of-AVR-Atmega328p-8bit-mic/

does the auto-reset circuit work? try a manual reset while avrdude attempts the upload

@NickGammon, I ran your program. See updated question. Thanks!

From the output, the LFuse = 0xff means that the MCU is expecting an 8-16MHz external crystal oscillator (the low 4 bits of the LFuse). Refer to sections 30.2 and chapter 10 of the Mega2560 data sheet (you can easily find this online). Do you have an external clock (crystal + supporting capacitors - section 10.4 of the data sheet) included in your hardware design?

@GMc Yes, there is a 16 MHz crystal on the board that appears to be oscillating correctly.

How is this going? Have you resolved it yet? If not, Have you tried uploading a simple program (e.g blink) via ICSP and see if that runs on your h/w?

@GMc Yes, I've been pushing ahead. I got the FW loaded into the 2560 using the "Upload Using Programmer" option in the Arduino IDE. So with that I have been able to verify much of the board...
Interestingly, I did notice today when trying to dump some debug text out of the serial port into the IDE, I was just getting garbage. It was not a baud rate issue, as that was the first thing I checked. I suspect that its related to the downloading issue.
Next I'll run a simple sketch to print "Hello world" and see if I can capture the TX data on my scope.
I'm open to any other debug ideas!

That is great news, I can't offer any further suggestions, but when you work it out, it would be really great if you could answer your own question and ideally post a circuit diagram (before and after if that is relevant). Hopefully you can work it out soon, but this sounds like significant progress. One thought though, how are you clocking the MEGA16U2 and what are the fuse settings for it?

As per the comments your output shows that the chip is working "normally" in that it reacts to the chip detector sketch. Thus the bulk of the design/implementation is OK.
Referring to Engbedded Atmel AVR® Fuse Calculator your fuse settings means the processor is expecting an external crystal oscillator. The bootloader expects (I think) a 16 MHz crystal (with appropriate capacitors). If you have not provided this then the bootloader will be running at the wrong baud rate (so to speak) — or not at all — and not react to attempts to download it by serial programming.
If you have a different frequency crystal then you may be able to work around this by adjusting the baud rate in the boards.txt file by an appropriate scaling factor.
The chip detector sketch worked because that uses ICSP programming, which provides its own clock.

Thus the bulk of the design/implementation is OK.
Great news!

I do indeed have a 16 MHz crystal on the board, and it looks like this oscillating correctly. I'll look into the baud rate issue.
Thanks again for your help, Nick!

Nick, apologies for the messages.
I have played around with various baud rates (via the boards.txt file), and nothing is working.
In the output of your program, also says
'''
Bootloader MD5 sum not known.
'''
Is that anything to be concerned with? I used the procedure outlined here: https://www.arduino.cc/en/Tutorial/ArduinoISP

That sketch, written quite a while ago, stored some MD5 sums of known bootloaders (at the time). There may well have been updates released since then. So that is no particular concern.

I suggest you get yourself a cheap logic analyser (say, around $100). Then you can see what is going on when the sketch starts to upload.

I use the Saleae ones - however the price seems more than I remember it. :(

There seem to be some on eBay which are very cheap - however I can't vouch for them. I think $100 to $200 (USD) would be a reasonable price to pay.

Nick, I greatly appreciate your help. Can I compensate your time for you to help me track down this issue? I feel like its something simple, but it's taking too much of my time. Please send me a message at infosavoyengineeringcom. Thanks!

I am not doing private consulting at present (paid or unpaid). My support for the Arduino community is through Stack Exchange, plus the (read only) articles on my web site. To problem-solve this issue you might be better off with the Arduino Forum - perhaps the Microcontrollers section. That might be more suitable for the "have you tried this? have you tried that?" style of working on your issue.


text:
Arduino Keyboard starts lower case (but it shouldn't)
So I flashed the KeyboardMessage example to my Arduino SS Micro ATmega32U4.
When I open an editor and push the button, I would assume the output to be

Zou pressed the button XX times.

(The "Z" is because I use a German keyboard)
In some editors (Arduino IDE, LibreOffice) this assumption is fulfilled.
However, in several other editors (Linux Shell, gedit), most of the times the output is

zou pressed the button 1 times.

starting with a lower case "z".
I use a Debian Testing computer. The only thing I changed in the sketch was the buttonPin as my button is soldered to pin 11.
I noticed, that this problem doesn't occur when the button is pressed a second time shortly after the first message. To investigate this, I coded a little sketch to find the threshold.
This is what I got (in gedit)

As line 8 shows, even after 70 millis, the upper case start is not reliable, however, somewhere after 250 millis, the error occurs every time.
My questions are:

What could be the cause for this issue?
How can it be fixed (if necessary, I also welcome a workaround)?

Please tell me if you need any additional information.
[edit]
After slightly altering the script, I noticed, that the problem doesn't only occur on the start of a line, but also (although less often) later in the output. See lines 24, 31 and 52 for example

Probable a long shot, but do you have any gedit plugins (e.g. ChangeCase plugin) enabled? Also, I hate to be pedantic, but are you sure the "little sketch" matches the output? The "little sketch" has a space between the number and millis (i.e. should produce "90 millis", not "90millis" as shown above). Also, the "little sketch" outputs a capital M in Message - which are all lower case in the above example.

Thanks for your comment! I indeed do have some gedit plugins enabled, however, they shouldn't change the case. I tried in the Linux shell as well and had the same result. About the changes in the sketch: you are right - I changed these two things after running the sketch. However, I didn't want to run it again as this takes quite some time.

yes, i just reread and saw the comment about linux shell. Oh, well it was a long shot :-)

Without any knowledge in this area, i assume that "slow editors" work better than "fast editors" and that somehow the shift key is swallowed somewhere between the arduino and the computer.

What happens if you unplug your normal keyboard while it's running?

@Majenko just tried: it's exactly the same.

As a debugging aid, you may try to use xev to see the keyboards events. When I press Shift-Y on my keyboard, xev shows four distinct events: KeyPress(Shift_L), KeyPress(Y), KeyRelease(Y), KeyRelease(Shift_L). Do you see the same events in the same order? See also Keyboard input in the Arch Linux Wiki (instructive even if you are not using Arch).

use keyboard.press() and keyboard.release() to send the shift key states at the correct time

Sorry for the late response. @EdgarBonet thanks for the xev tip. I coded a small sketch that should print "ON" when I push a button on the Arduino. This is the output in xev: https://nopaste.xyz/?b4efb9869c386975#22qZaCvBxQ2HfuTxEGszxdxnLbf18qTNuuCToR9JfwpA . In an editor like gedit this reads like "oN"

@jsotola this would be a possible workaround. However, like this I would need to distinguish between those characters that need a shift button and those that don't. Something I hoped the keyboard library would do for me.

I am not sure I have the answer to your problem, just a collection of
observations that hopefully steer you in the right direction.
According to your nopaste link, when you send "ON", the first four
keyboard events received by xev are: press(Shift_L), press(O),
release(Shift_L), release(o). One may notice that there is no point in
releasing the Shift key if it's going to be pressed again right away,
but let's assume that simply holding Shift is not such a useful
optimization. The detail that strikes me is that the last two events
look backwards: you usually release the letter before releasing Shift.
As a result of releasing Shift first, the release event for the O key
reports lowercase "o" as a keysym. I tried this backward way of
releasing the keys on a real keyboard, but both gnome-terminal and gedit
correctly registered the uppercase letters.
Another detail apparent in the xev dump is that the two key presses
(Shit and O) happen at the exact same time. Ditto for the corresponding
key releases. Looking at the source of the Keyboard library, it appears
that both key presses are sent to the PC as a single "key report". Same
for the key releases. This is contrary to what a real keyboard does:
actuations on the Shift keys are reported immediately, irrespective of
whether other keys are actuated.
You may try to modify the Keyboard library so that the actuations on
Shift are sent in their own reports. Maybe something like this
(warning: completely untested):
diff --git a/src/Keyboard.cpp b/src/Keyboard.cpp
index 4a948f6..9fbf7b6 100644
--- a/src/Keyboard.cpp
+++ b/src/Keyboard.cpp
@@ -239,6 +239,7 @@ size_t Keyboard_::press(uint8_t k)
        }
        if (k & 0x80) {                     // it's a capital letter or other character reached with shift
            _keyReport.modifiers |= 0x02;   // the left shift modifier
+           sendReport(&_keyReport);        // send the shift key by itself
            k &= 0x7F;
        }
    }
@@ -270,6 +271,7 @@ size_t Keyboard_::press(uint8_t k)
 size_t Keyboard_::release(uint8_t k)
 {
    uint8_t i;
+   bool has_shift = false;
    if (k >= 136) {         // it's a non-printing key (not a modifier)
        k = k - 136;
    } else if (k >= 128) {  // it's a modifier key
@@ -281,7 +283,7 @@ size_t Keyboard_::release(uint8_t k)
            return 0;
        }
        if (k & 0x80) {                         // it's a capital letter or other character reached with shift
-           _keyReport.modifiers &= ~(0x02);    // the left shift modifier
+           has_shift = true;
            k &= 0x7F;
        }
    }
@@ -295,6 +297,10 @@ size_t Keyboard_::release(uint8_t k)
    }

    sendReport(&_keyReport);
+   if (has_shift) {
+       _keyReport.modifiers &= ~(0x02);    // the left shift modifier
+       sendReport(&_keyReport);            // release shift after releasing the letter
+   }
    return 1;
 }

Alternatively, as suggested by @jstola in a comment, you may try to
press the Shift key by itself. Maybe you don't need to care about the
key release, or about any character but the first one (as it is the only
one that seems to cause problems). A minimal workaround to try would be:
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.println("ON");

Thanks, @EdgarBonet! I can confirm, that your solution works on my computer. However, this raises the question if the "original" Arduino implementation is faulty. I would encourage you to file a pull request on their implementation.

by the way, the problem doesn't only occur in the first character but also sometimes on later ones.

@speendo: I am reluctant to submit a pull request, as I do not have a 32U4-based Arduino to test it. I would do it, though, if you are willing to help with the testing: provide a minimal test sketch, run it, and report the results on the pull request page.

Of course I am willing to help. Using this library (https://github.com/NicoHood/HID) you could also use test your code with another Arduino board (this is the library where I first experienced the error) But I would also fund you a cheap Pro Micro board as a little recognition for your work. Just tell me what solution(s) you like best :)


text:
Which pin triggered MCP23017 interrupt
This is my first post here, so apologies in advance if I've done something against any forum guidelines!
I have a project where I am monitoring multiple switch states with an Arduino using multiple MCP23017 ICs. I found a fantastic article by Nick Gammon which pretty much does what I want for the first element of the project at least. There are 2 small errors in his expanderWriteBoth and expanderRead routines - swap "send" for "write", and "receive" for "read" and the code works out of the box.
However - Nick's code will only display which pin has triggered the interrupt when the input pin is grounded. If you remove the ground to return the pin to the previous state, it will not state that this pin has changed state.
Can anybody see why this is the case? I have been through the datasheet for the MCP over and over again with no clues...
Any help appreciated,
Thanks.

i think that there were no 2 small errors in 2011 ... libraries change over time

He's not storing previous state, so it's hard to figure out which buttons were released.

The datasheet for the MCP23017 shows that the inturrupt condition can be compared with the previous state - the IC stores the previous state internally. If you set DEFVAL to clear, and INTCON to clear, it should compare with previous state.


text:
Powering an esp32cam by a battery
I have an esp32cam that I've programmed and powered via an FTDI connected to a computer's USB. Now that this stage is over, I'd like to run it portably, using some sort of battery.
The esp32cam has a 5V input (also a 3.3V input which word is should be avoided because it causes brownout). I'm wondering if it's possible to power it (for a short period) using a 7.3V, 9V or 12.3V battery. All the datasheets I've seen seem to specify the input range is 5V, but, for the esp32 (non-cam version), unregulated 5V-12V seems to permissible. Is this true for the esp32cam? Also, what is the right way to search for this?

I'm researching the same topic. Could you please share any links about why 3.3V should be avoided?

The official ESP32-CAM has a AMS1117 voltage regulator that creates the 3.3V for the ESP.
The AMS1117 has an Absolute Maximum Input Voltage of 15V. It has a Dropout Voltage of 1.1-1.3V.
So you should stay above 4.6V to be on the safe side.
Since it's a linear voltage regulator, using a higher voltage battery has no advantage, as the "excess voltage" is converted to heat. It could even damage the regulator if too much heat is created.
You should pick the battery with the lowest voltage that still produces 4.6V when almost empty. So you could use the 7.3V battery you indicated. I'm assuming this is a 2-cell Li-ion battery, that has a voltage of 8.4V when full, and around 6V when empty. Which nicely fits your requirements.

This is awesome, thanks! I wish I knew how to find out these things on my own, but am not there yet. For example, how could I find it's an AMS1117?

Check schematics, and lookup datasheets for parts. Look through the entire datasheet. You'll see a lot of things you don't understand. Don't worry about that. In time you'll start seeing connections; know what things mean; know which parts are important, and which aren't. Some parts of datasheets I still don't (fully) understand, so don't beat yourself up. Learn Ohms law, and try to apply it everywhere. I found that electronics has quite a steep learning curve (coming from software development). So it may feel a bit overwhelming at first. Best of luck.


text:
Problems using SIM808 with Pro Mini
I'm having problems with my setup.
I'm trying to create a wind-speed system when you send an SMS to retrieve the correct wind speed as an SMS response.
I'm using a pro mini, connected by USB via FTDI, and a SIM808 module.
The SIM808 is connected to a mains supply and the LED status suggests it is connected to the network.
The SIM808 pins are as follows:
TX > Pin 9
RX > Pin 10
VMCU V IN > Power supply +
GND (the one under VMCU) > Power supply -
GND (under Li-on) > GND on the Arduino

I've tried lots of source code examples but nothing much seems to happen, this is the latest code I'm testing (the top part of the loop at least). In the serial monitor, it reports back the "Sim808 init error" over and over.
include <DFRobot_sim808.h>
include <SoftwareSerial.h>
define MESSAGE_LENGTH 160
char message[MESSAGE_LENGTH];
int messageIndex = 0;
char MESSAGE[300];
char lat[12];
char lon[12];
char wspeed[12];

char phone[16];
char datetime[24];

define PIN_TX 9
define PIN_RX 10
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

void sendSMS(); void getGPS(); void readSMS();

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

//******** Initialize sim808 module *************
while(!sim808.init()) {
  Serial.print("Sim808 init error\r\n");
  delay(1000);
}
delay(3000);

Serial.println("SIM Init success");

I hope someone can help as I've spent ages on this and had no luck.

Are you sure this is the code you are running? You code won't compile, e.g. it should be #define instead of define...

Your connection doesn't make any sense, how do you power the pro mini? It will be better for you to provide the drawing or picture of your connection.


text:
How to break out the due power supply and USB connectors?
I am planning a build with my own enclosure for the arduino due. As an alternative i would like to bypass the power jack and usb port that are factory soldered onto the board, in order to use jacks mounted on the enclosure, along with a power switch.
I've looked at the info regarding the boards pin configuration at https://www.arduino.cc/en/pmwiki.php?n=Main/arduinoBoardDue, and would appreciate if someone could confirm or correct this:

Can i use an external 9V adapter through a jack connected to the Vin and GND pins, respectively?

According to This question, you can't connect an alternative programming USB port to Serial 0 TX/RX pins (Mega board). If this applies to the due as well, what do i need to break out the programming USB port?

Edit: Perhaps one of these puppies is the least complicated solution?

You can't connect a USB socket or USB cable - but you can connect an FT232 adapter cable / board.

your Edit is the answer ... use pigtails for all connections ... insert a switch into the power pigtail

you could reprogram the ATmega16U2 to existing programming port and release the serial0 pins for your use ... or use the ATmega16U2 as a serial port gateway between JP5 and serial0

@jsotola Thanks for your input!

the first part of my comment sounds like nonsense ... i did not proofread it ... it should say something like you could reprogram the ATmega16U2 to stop being the programming port and release the serial0 pins for your use

so 1 - yes. the VIN pin has a common trace with the barrel jack, you can verify with a multimeter in continuity/beep mode. ive actually put power out through the barrel jack on a mega.
2- i cant find a clear schematic for the due at the moment, but on the mega the rx/tx pins are also common with the usb pins, thus they are not usable while plugged into usb


text:
Play sound on top of background music using arduino uno tmrpcm library
We designed a big piano with 15 buttons on it. Every button has a proximity sensor. Whenever users interact with the sensor a specific sound plays for that button. My code is working fine for this purpose but now I want to add background music. Our piano button sound should play on top of that background music. I am using tmrpcm library, and I already added a bg music but when I interact with the sensor, bg music stops and starts from the beginning right after the piano button sound stops. Is there a way to play a sound without interrupting a bg music. Any help will be appreciated.

use two arduinos

Assuming you are using an Arduino Uno, You didn't say. As there are many Arduino platforms these days.
As the tmrpcm library is using the PWM  (Pulse Width Modulator) HW (Hard Ware) to recreate the sound waves from the WAV file on the SDCard, the PWM is not available for creating the sounds from your piano application (you didn't say what piano application you were using).  That said, it is not impossible to re-write both applications to SUM the two wave forms together mathematically before resampling the SUM and writing that sample value to the PWM HW to simulate the SUM of the two wave forms.  However, this is likely not trivial and it is also likely the Arduino Uno processor (an Atmel ATmega328P) will not be powerful enough (perform the math fast enough) to keep up with normal sound playback.
It would likely be much simpler to use 2 Arduino Uno boards and sum the sound from the sound file application and the piano application using analog techniques external from the Arduno Uno boards.

I think a single Uno could be made to do it, but if expediency is an issue, one should just use two Arduino Unos.

Perhaps you are right @GabrielStaples.  But there may be more problems to solve than the OP (or anyone) may want to deal with.  Can the tmrpcm library deal with WAV files of different sampling rates?  If so, then the piano application would have to be adjusted to create the same note at these new sampling rates.  Or the Arduino Uno would have to deal with the differences in sampling rates by re-sampling either the WAV file data or the piano data.

Yeah, it would take a lot of effort no doubt and require a lot of advanced skills and problem-solving. Could be a fun project for those who like to really push the limits of the Arduino, but just a nightmare for those who just want to get the desired results as soon as possible. And if one doesn't have the required skills up-front, and can only work on this nights and weekends, this could be a 3 yr project. I've had many of those: I start something I have no idea how to do, so it has taken me 3 yrs to eventually learn all the pieces and study the datasheet and figure it out.


text:
How to implement a tilt compensated compass?
So i was trying to implement a tilt compensated compass, using HMC5883L and MPU6050. The problem i am facing is, there are 2 equations for tilt compensation
Tilt Compensated X:   X,Y,Z are compass output (raw output)
new_X =  X*cos(pitch) + Y*sin(roll)*sin(pitch) – Z*cos(roll)*sin(pitch)
Tilt Compensated Y:
new Y =  Y*cos(roll) + Z*sin(roll)
Final Heading :
Azimuth =  atan2(Y, X) * RAD_TO_DEG
The angles which i am getting from the mpu are gyro-drift corrected angles which are coming through a kalman filter. Those angles are fed to these above equations and after atan2 i get the tilt compensated heading. But the issue/observation here is, when i rotate the body(on which the compass and mpu are) along the Z axis (YAW axis) the heading doesn't change(sort of locked on), but changes when i tilt the body in X/Y.
I searched for thorough references, but wasn't able to find any!
Here is my code snippet (uses compass part form adafruit library):
double HEADING(double r, double p){
  sensors_event_t event;
  mag.getEvent(&event);
  r = r * (PI/180);
  p = p * (PI/180);
  double x = (event.magnetic.x)*cos(p) + (event.magnetic.y)*sin(r)*sin(p) - (event.magnetic.z)*cos(r)*sin(p);
  double y = (event.magnetic.y)*cos(r) + (event.magnetic.z)*sin(r);

  float heading = atan2(y,x);

  float declinationAngle = 0.366667 * (PI/180);// (0°22')positve declination
  heading += declinationAngle;

  if(heading < 0)
    heading += 2*PI;

  if(heading > 2*PI)
    heading -= 2*PI;

  heading = heading * 180/PI;

  return heading;
}

The HMC5883L data acquisition I wrote :
// i just need a direction reference not actual heading, just to keep my drone
// steady on yaw axis with reference to that direction reference but it shall be Tilt compensated
#include<Wire.h>

#define MAG 0x1E

#define R 0
#define P 1
#define Y 2

float mag_raw[3],h;
float CMP_DEC = 0.36667 * (PI/180);

void setup(){
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(400000);

  Wire.beginTransmission(MAG);
  Wire.write(0x02);
  Wire.write(0x00);
  Wire.endTransmission(true);

}

void loop(){
  Wire.beginTransmission(MAG);
  Wire.write(0x03);
  Wire.endTransmission(false);
  Wire.requestFrom(MAG,6,true);

  mag_raw[R] = Wire.read() << 8 | Wire.read();
  mag_raw[P] = Wire.read() << 8 | Wire.read();
  mag_raw[Y] = Wire.read() << 8 | Wire.read();

  h = atan2(mag_raw[P],mag_raw[R]);

//  h += CMP_DEC;

  if(h < 0) h+= (2*PI);
  if(h > (2*PI)) h -= (2*PI);
  h *= (180/PI);

//  Serial.print("X : ");
//  Serial.print(mag_raw[R]);
//  Serial.print(" Y : ");
//  Serial.print(mag_raw[P]);
//  Serial.print(" Z : ");
//  Serial.print(mag_raw[Y]);

  Serial.print(" H : ");
  Serial.println(h);

}

Some guidance will be very helpful!

Are you writing all the code?  (Not using libraries?)  I ask as you did not mention how you were compensating the magnetometer's output for hard and soft iron errors.
Creating a tilt compass is hard enough.  But I find it better, if writing most or all of the code from scratch, to create a normal (use it flat on a table) compass 1st.

@st2000 I tried writing my own code (the general approach for i2C Wire lib). Sometimes i got a solid output (no change in data even if i move in different axis), sometimes data came but the range remained almost around 170 for X , 65000 for Y and 56 for Z axes. I didn't understand what was going on so i started using libraries :(    can you give me some relevant references ?

Are the pitch and roll angles small when the body sits flat on a table? Do the raw values of the magnetic field components change when you rotate it?

@EdgarBonet i'll answer according to what i understood; So the R&P angles coming from the MPU are 0±0.1° when kept on the flat surface. Now when I rotate the compass along Z axis, there is no change in the values(actually it is there but it changed about 3 points when i rotated it 90°!). For X,Y axes, the values change a lot !almost ±120 units. ill just add my from scratch written code in the question. Have a look to it, maybe something wrong can be seen...

@Sajil, start simple!  Just stick to getting the magnetometer working.  Forget about the accelerometer. That said, I have yet to see a magnetometer output useful information with out compensating for range (add or subtract a number so that the maximum and minimum of a given axis is the same) and magnitude (multiply by a number so that the maximum and minimum of all 3 axes are the same).  Until you do that, performing math on the output of a magnetometer will give you garbage.

@st2000 yeah let me work more on magnetometer thoroughly. Can you send me some references for it ? Possibly not using the libraries (I find it easy without libraries ).

Inspecting your code, it does not appear you are compensating the raw magnetometer values for soft and hard iron effects.  These terms roughly refer to adjusting the range and magnitude of each of the individual magnetometers (X, Y and Z).  Some magnetometer manufactures allow writing these compensation values into the chip.  Even then the developer and user will still need to perform some form of calibration as the magnetometer can not predict under what conditions the magnetometer will be used.  Here is another explanation using matrices of hard and soft iron compensation.
Once the compass produces expected results on a flat surface parallel to the surface of the earth (in a place on earth where the magnetic lines roughly align with true north).  Consider adding tilt compensation.  Accelerometers usually do not need to be compensated as extensively as magnetometers.
This can be done using trigonometric math and Euler angles.  However, as with physical gambles, this can lead to a situation similar to gimbal lock.  Where the trigonometric math goes to infinity.
To avoid a gimbal lock like situation, most tilt compensated compasses use quaternions.  Quaternions use imaginary numbers and matrix math to describe 3 dimensional rotation.


text:
Serial Monitor Not Displaying
I am using BMP 280 for an altimeter to measure the altitude. Once all connected and uploaded the BMP280test code from Adafruit, the serial monitor says busy. But still, when I switch the port in tools, nothing shows on the serial monitor. How do I get the monitor to start displaying data?
Thanks
Code:
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>

#define BMP_SCK  (13)
#define BMP_MISO (12)
#define BMP_MOSI (11)
#define BMP_CS   (10)

Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

void setup() {
  Serial.begin(9600);
  Serial.println(F("BMP280 test"));

  if (!bmp.begin()) {
    Serial.println(F("Could not find a valid BMP280 sensor, check wiring!"));
    while (1);
  }

  /* Default settings from datasheet. */
  bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */
                  Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */
                  Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */
                  Adafruit_BMP280::FILTER_X16,      /* Filtering. */
                  Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */
}

void loop() {
    Serial.print(F("Temperature = "));
    Serial.print(bmp.readTemperature());
    Serial.println(" *C");

    Serial.print(F("Pressure = "));
    Serial.print(bmp.readPressure());
    Serial.println(" Pa");

    Serial.print(F("Approx altitude = "));
    Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */
    Serial.println(" m");

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

Start simple.  Assuming you are using an Arduino Uno and running on a Win10 machine.  Since you are having problems with talking to the Arduino over the serial port forget about the pressure sensor and this pressure sensor application.  Start with a simpler Arduino program which only talks over the serial port.  Try this or this.

"the serial monitor says busy" - what does that mean? And what do you mean with switching ports?

@chrisl, being sarcastic? It's pretty clear he is talking about com ports. "The serial monitor says" is talking about the serial monitor in Arduino ide (ctrl + shift + m). He obviously has multiple com ports available on his PC and doesn't know what com port represents the usb-serial on his uno. Sounds to me either something else is holding up the com port, or maybe he doesn't have the right drivers loaded: maybe a clone with the ch340 usb-serial chip?

@TimStewart Nope, not being sarcastic. While the topic is clear, I wanted a detailed description of what the OP did exactly. Of course you can write an answer to this question. Me finding the question not clear enough is just a subjective view.


text:
WS2812B Power Supply
I have a WS2812b addressable RGB led ribbon that is 5m (150 RGB leds). I purchased a 5v 10amp power supply to power it; however, whenever I try to use it to power the LED strip the leds start flashing colors like crazy. Is there a reason I would be seeing this behavior or is this a sign of a bad power supply?
The setup is very simple, the data line is coming from an Arduino Uno, the voltage and ground are from the power supply. The program is just one of the sample ones with FastLED library and works "fine" when just powered by the arudino's 5V pin.
Thank you

Are the ground of the power supply and of the Uno connected?

No, the Arduino is powered by a separate source and no grounds are shared. Would that cause the issue?

That seems to have fixed it. Thank you!

The strip and the Arduino need to share the same ground connection. They are communicating through voltage and voltage is always a difference between two points. The power supply sets the supply voltage as the difference between + and ground. The chips in the strip will then try to measure the voltage on the data line relative to their ground. When the grounds are not connected, the Arduinos output pin is floating somewhere else, depending on external factors. By connecting the grounds, both devices (Arduino and strip) use the same ground value to measure voltages. Only this enables communication between the devices.


text:
Getting the I2C Address from a Max9744 amplifier
I just bought 2 Max9744 amplifiers that I wish to scan the I2C addresses, just to check against what is said in documentation. I have the amplifier powered with a 12 v supply and the Arduino powered via usb. I run an I2Cscanner it says Devices found: in the serial monitor but doesn't say the address. The wiring is correct and the 5 v supply is giving 5 V. So what gives?
Thank you
Andrew

Please show exactly, what the Serial Monitor shows (copy and paste it into the question and then format it as text). Also provide a link to the scanner sketch, that you used (or also put it into your question). And please show, how you have connected the Max9744, as it seems to be possible to deactivate I2C by setting the address pins to low.

The Serial Monitor exactly says "Devices Found: " but then nothing else. Link to I2C scanner https://www.elithecomputerguy.com/2019/07/find-i2c-addresses-on-arduino-i2c-scanner. I will add the images in a second

Link to datasheet for the Max9744 amplifier?

https://cdn-shop.adafruit.com/datasheets/MAX9744.pdf


text:
Arduino offline commands
I wanted to know if there is a way for my arduino to keep the last command I sent to it before I disconnected it from my computer. Thanks.

Huh? I think you need to provide a little more detail as to what you are trying to achieve? What do you mean by the last command? Can you provide an example of your work flow? What command, what does the command cause to happen, and what do you mean "keep the last command" before you disconnect. As your question stands, I think that the answer is to just use an external power supply (e.g. a 9 Volt power supply or a battery) plugged into the barrel power connector on the Arduino before you unplug the it from your computer.

what does this mean? ... disconnected it from my computer ... there is more than one possible meaning

You mean the last sketch (i.e. program) you uploaded? It's already kept in the Arduino.

It's even posssible to store something in the Arduino while switching power off and on again, using the EEPROM. (But that's more complicated).

Arduino always store the last sketch you have uploaded. Even if you disconnect your board and then replug it then it follow the same commands that you gave earlier.


text:
I have three load cells can I sum all the three into Arduino to be one output? If yes how?
I am doing stand thrust and I have three load cells to measure the force. I would like to know if I can sum them to gather into the Arduino or I should use a junction box.

Arithmetics is easier than mechanics and electronics. But perhaps that's just because I do not know load cells nor junction boxes.

Do you really want to sum them (the total of the forces applied to each), or do you really want to average them (the average load applied across the whole surface)...? The answer is "yes" in both cases, but you will have to build the right kind of circuit to perform the operation you want - and that will take multiple op-amps to do the job. Simpler to connect each direct with a HX711 each and do maths in code.


text:
How to clear SoftwareSerial values?
I'm using software serial on my weather station. The way it's supposed to work is that you send an SMS to the device and it replies with the wind speed, etc.
At the moment, The wind speed is detected, waiting for an incoming SMS. The SMS arrives and it sends a response but the response SMS is sent over and over infinitely.
I'm guessing the problem is due to the:
 if (mySerial.available()>0){

As this is what I'm using to test whether the SMS has arrived and presumably, it's then always set to available.
Does anyone know how to basically reset the software serial after the message has been sent?
 #include <SoftwareSerial.h>
 #include <ADSWeather.h>

SoftwareSerial mySerial(9, 10);

#define ANEMOMETER_PIN 2
#define VANE_PIN 0
#define RAIN_PIN 3

#define CALC_INTERVAL 1000

unsigned long nextCalc;
unsigned long timer;

int windDir;
int windSpeed;
int rainAmmount;

ADSWeather ws1(RAIN_PIN, VANE_PIN, ANEMOMETER_PIN); //This should configure all pins correctly

void setup()
{
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(RAIN_PIN), ws1.countRain, FALLING); //ws1.countRain is the ISR for the rain gauge.
  attachInterrupt(digitalPinToInterrupt(ANEMOMETER_PIN), ws1.countAnemometer, FALLING); //ws1.countAnemometer is the ISR for the anemometer.
  nextCalc = millis() + CALC_INTERVAL;

  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  delay(100);
}

void loop()
{
  timer = millis();

  int rainAmmount;
  long windSpeed;
  long windDirection;
  int windGust;
  int sent;

  ws1.update(); //Call this every cycle in your main loop to update all the sensor values

  if(timer > nextCalc)
  {

    nextCalc = timer + CALC_INTERVAL;
    rainAmmount = ws1.getRain();
    windSpeed = ws1.getWindSpeed();
    windDirection = ws1.getWindDirection();
    windGust = ws1.getWindGust();

//     windSpeed / 10 will give the interger component of the wind speed
//     windSpeed % 10 will give the fractional component of the wind speed
    Serial.print("Wind speed: ");
    Serial.print(windSpeed / 10);
    Serial.print('.');
    Serial.print(windSpeed % 10);
    Serial.print(" ");

    Serial.print("Gusting at: ");
    Serial.print(windGust / 10);
    Serial.print('.');
    Serial.print(windGust % 10);
    Serial.println("");

  }

  if (Serial.available()>0)
  {
      RecieveMessage();
  }

  //If an message comes in
 if (mySerial.available()>0){
  // Serial.write(mySerial.read());
  Serial.write("Message received");

  //Send the wind speed response.
  SendMessage();

  //At this point the SendMessage() repeats and the message is sent over and over.
}
}

 void SendMessage()
{
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"NUMRemoved\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("I am SMS from GSM Module");// The SMS text you want to send
  delay(100);
   mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
}

 void RecieveMessage()
{
  mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  delay(1000);
 }

 void serialFlush(){
  while(mySerial.available() > 0) {
    char t = mySerial.read();
  }
}

You need to read the stuff from SoftwareSerial.  Use mySerial.read() until available is false.  If you don’t care what was sent then simply use read and ignore the value that was read.

you have a serialFlush() function in the sketch. use it.

@Juraj It doesn't work. The SMS messages keep coming.

change the sketch in question so we can see how do you use serialFlush();

For the hardware serial port, the buffer is 64 and I was reading at least 100 times. Every read will clear one byte of data from the serial buffer at a time.
For the software serial port, you do a dummy read and then check whether the buffer is empty or not using
    while(mySerial.available()>0)  {
       dummy = mySerial.read();
    }

So, in summary, you have to read the buffer until it is empty.
Useful notes:

You should be knowing when to expect actual data and when not to
have a way to identify the valid messages (some fixed header bytes)
have a way to validate the contents (checksum)

Leave a comment if you have any questions

I've tried using this loop to flush the serial port, it's even in the code I posted above but it does not work. The SMS messages keep coming. Am I calling it in the wrong place?

You never call it.

 if (mySerial.available()>0){

You are checking if any serial data has arrived. Then you never read it. So naturally it is always available. You have a serialFlush function which does read it, however that function is never called.
You need, however, to read more than one byte. Otherwise you will send an SMS for every byte in the input message.

if (mySerial.available() > 0) {
  // Serial.write(mySerial.read());
  Serial.write("Message received");

  //Send the wind speed response.
  SendMessage();

  mySerial.begin(9600);   // Reset myserial buffer

  //At this point the SendMessage() repeats and the message is sent over and over.
}


text:
Read two HX711 load cell amps
I need to read two values from hx711 load cells connected to strain guages. Ive found the code below that reads one guage, but being self taught and with little experience I have no idea how to adapt it to work with two, is anyone able to help?
I need two individual readings not a combined one
Thanks in advance, and credit to sparkfun who wrote this code.
#include "HX711.h"

#define calibration_factor -7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch

#define DOUT  3
#define CLK  2

HX711 scale;

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 scale demo");

  scale.begin(DOUT, CLK);
  scale.set_scale(calibration_factor); //This value is obtained by using the SparkFun_HX711_Calibration sketch
  scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0

  Serial.println("Readings:");
}

void loop() {
  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1); //scale.get_units() returns a float
  Serial.print(" lbs"); //You can change this to kg but you'll need to refactor the calibration_factor
  Serial.println();
}

Create a second instance of the HX711 class and begin it with two different IO pins.

make it so that you have something like these two in your code ... scale1.begin(DOUT1, CLK1); and scale2.begin(DOUT2, CLK2);  .... start by renaming scale. to scale1. ... then duplicate all of the scale1. lines

@jsotola, Ive tried that, but when I then try to read it, it tells me that scale2 was not declared in this scope

look at every line in your code above, that contains the word scale ... make two lines out of each one of those lines

The line:
HX711 scale;

is called the "instantiation of the object". It creates a new object called scale which is an instance of the HX711 class. It is this "object" that is your interface to the HX711 physical device.
To use two of them you first need to have two objects - one for each HX711. You can name them whatever you like.  For example:
HX711 scale1;
HX711 scale2;

The line:
scale.begin(DOUT, CLK);

is where it tells the HX711 object which pins the HX711 chip is connected to. In this case DOUT and CLK which you have defined as 3 and 2 respectively.  You could just as well have written:
scale.begin(3, 2);

Each object has to be "begun", so you would need a begin for each object you instantiate:
scale1.begin(3, 2); // DOUT = 3, CLK = 2
scale2.begin(5, 4); // DOUT = 5, CLK = 4

Now for every operation that you did on scale you would instead do on your two new objects:
scale1.set_scale(calibration_factor);
scale2.set_scale(calibration_factor);

etc.
And when you want to take a measurement you just select which object to read from:
Serial.print(scale1.get_units(), 1);

or
Serial.print(scale2.get_units(), 1);

You can add a third by creating and using scale3 in exactly the same way as scale1 and scale2.


text:
Adafruit IO + Esp-Now
So i am using adafruit io and esp-now on an esp32 to recieve voice commands from the internet and sensor values from another esp32. Independently, they both work quite fast but together the esp-now recieving speed slows down greatly with more packets lost. Any reason for that?


text:
I get an error saying, "exit status 1 expected initializer before 'void'."
I will be wiring a switch to the Arduino that controls the voltage. When the I turn the switch it can adjust the voltage from 0 to 5. The overall task is to print the output voltage. The print is to be a multiplication table of the voltage.
I created this code:
void setup()

void loop(){

  int (n,i,j,result);

  printf("enter N Value");

  scanf ("%d", &n);

  for (i=1; i<=n; i++);

  {
    for (j=1; j<=n;j++);

    {
      result= (i*j);

      printf("%d", result);

    }
    printf("\n");

  }
  return 0;

}

But i get the error exit status 1
expected initializer before 'void' when I try to verify it. what does it mean. How do you fix it?

Your setup() function has no body.

@Majenko what do you recommend for the set up? I though it could run off the loop

If you don't need any setup code then give it an empty body.

@Majenko im not sure if anything needs to go in the setup. this is my second day of trying this, that's why im asking for assistance.  What do you recommend for ?

I think you should start by learning basic c syntax.

@Majenko well I am trying to learn at the moment. But that doesn't help me get this working.

Functions must have a body. So instead of:
void setup()

You need:
void setup()
  {
  // do nothing
  }

You have other issues, for example this is not C++:
  int (n,i,j,result);

That should be:
  int n,i,j,result;

Also you are returning 0, when void functions don't return a value.
Also, here:
  printf("enter N Value");

  scanf ("%d", &n);

Where is this value coming from? There isn't a keyboard on the Arduino.
See: scanf

The C library function int scanf(const char *format, ...) reads formatted input from stdin.

The Arduino is a microprocessor. It doesn't have stdin.

Nick, Im under the impression that most of my issues remain in the fact that i have nothing in the setup body. that's why im getting errors like n, i, and j was not declared in this scope. How do you recommend I address this?

No, they are two different issues. I showed in my first paragraph how to fix setup.

with the corrections you gave me the code was verified. Im going to have to work on it doing what i need.   Also you asked we i got these, I pulled them from other forums and tried to piece together something. I know its not proper but its the second day for me learning this.

OK, you are progressing. :) You might want to read up on Serial because that lets you work with the Serial Monitor (something you can activate in the IDE), and (using the USB interface) you could indeed show text, and receive text. However printf and scanf are not the exact functions you need for that.

Great, thank you so much. I will look into them now.


text:
LCD Custom Character
I am experimenting the write((byte)num) function, and I stumble upon a pre-made custom character. Usually it's on above ((byte)200) or and below ((byte)10000). If anyone else know this, where could I find the list for a specific character?

Post the code and the output.  You're talking nonsense with a byte with a value of 10000.  A byte can't have a value that high.

@Delta_G  I think that (byte) 10000 is a cast of integer to byte ... it is equal to 16

https://www.sparkfun.com/datasheets/LCD/HD44780.pdf pages 17 and 18 (depending on what ROM your LCD has). And the range is 128-255 - the "high bit set" on ASCII.

Yes, @jstola, that was exactly my point.  There is no character at 10000, he needs to be thinking of what number is actually being used there.

Hi Welcome to Arduino StackExchange
You can build your own LCD characters if you spend some time with the datasheet and user manuals available
Arduino has a dedicated function here
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

byte smiley[8] = {
  B00000,
  B10001,
  B00000,
  B00000,
  B10001,
  B01110,
  B00000,
};

void setup() {
  lcd.createChar(0, smiley);
  lcd.begin(16, 2);
  lcd.write(byte(0));
}

void loop() {}

here is one example:  from our tool here

From the datasheet:

here is one example where a Heart symbol is created using the built-in Arduino LCD library:
You can play here at our LCD1602 simulator to get a hang of it.  Please leave a message or comment if you have any questions :)


text:
About maximum length of matrix can be use for matrix invertsion on atmega32
what is the maximum length for matrix can be used for matrix inversion on atmega32,for example,can we implement matrix inversion for 15x15 matrix on atmega32? And if  it can be done on atmega32..does this will make the atmega32 to be slower?
I want to implement kalamn filter 15 states for euler angles estimation...the data of the matrix will be floating point..

This is not a very well defined question. Did you have a particular application in mind (so it can be optimized) or do you need a general matrix inversion algorithm? What do you mean by “would this make the ATMega32 slower”? No, the ATMega32 would remain just as fast. Your code might become slower, but that depends on question #1: what do you need this for?

What data type do you store in the matrix? How is the matrix defined? Please show us some code.

I want to implement kalamn filter 15 states for euler angles estimation...the data of the matrix will be floating point..

I want to implement kalamn filter 15 states for euler angles estimation...the data of the matrix will be floating point..

does this will make the atmega32 to be slower? - slower than what? It would certainly be slower than not inverting any matrices, of course.

Floats in the Arduino IDE are normally 4 bytes. So you can work out with a calculator that your matrix will take at least 15 x 15 x 4 bytes (900 bytes). That is out of a total of 2048 bytes of RAM on the Atmega32.
That may seem to be enough RAM, but other things, like the libraries, will also take RAM. I did an answer to a question about RAM a while back. Even a very simple sketch (in this case) took 346 bytes.
Also, your library, or whatever-it-is you are using for matrix inversion, may require RAM for variables, etc.
My suggestion would be to make your code invert a very small matrix (eg. 1 x 1) and see how much RAM that uses. Then you can extrapolate out fairly simply to how much would be needed for a larger matrix.

To invert, you will need at least 2 arrays (src, dest), so 15x15 is very questionable.

Couldn't you do it in place? Not that the library they are proposing to use would necessarily do that.

I may well be wrong about that. After reading Inverse of a Matrix
using Elementary Row Operations it sounds like you may well need more memory for the inversion operation.


text:
How to get variable from callback function?
There is a library  davetcc / IoAbstraction. The only library working as expected with my rotary encoder. The problem that on rotation I can only see serial output with position data, but I cannot get these data as some variable value.
There is the swithch initialization and function definition in main.cpp
switches.addSwitch(spinwheelClickPin, onSpinwheelClicked);
void onSpinwheelClicked(uint8_t pin, bool heldDown) {
  Serial.print("Button pressed ");
  Serial.println(heldDown ? "Held" : "Pressed");
}

The definition from SwitchInput.cpp
bool SwitchInput::addSwitch(pinid_t pin, KeyCallbackFn callback,uint8_t repeat, bool invertLogic) {
    if(internalAddSwitch(pin, invertLogic)) {
        KeyboardItem item(pin, callback, repeat, invertLogic);
        return keys.add(item);
    }

    return false;
}

There is the callback function type definition from SwitchInput.h
typedef void(*KeyCallbackFn)(pinid_t key, bool heldDown);

I canon just change void to bool. So how can I get this heldDown variable value?
Sorry if the question is stupid.

Callback functions are usually void and don't return real data, because they are called by some type of event handling system, like the mentioned library. As this is calling the callback function, not you, it does not make much sense to return data from it. To get that return value, you would need to change the library for every bit of data, that you want. Thus return values of callback functions are either void or some message to the event handling system (for example to make the event system send down the event to the next possible handler).
But you can use global variables to get the data from the callback. Define a global variable for the value, that you want to extract, and inside the callback function set that variable. Then at other places in your code you can use that global variable.
The library, that you linked, seems to handle the event in the main code and not in interrupts. So you are safe to just use the global variables as you like.
Though to be complete: When interrupts are involved and you change global variables inside an interrupt service routine, you need to be very careful. Single byte variables are not problem, but with multi-byte variables you can get scrambled data, as the interrupt might occur in the middle of processing that variable. Then you need to introduce a critical section, where interrupts are disabled for a very short time.


text:
Setup/Debug affordable 9DOF IMU
I bought a 9 DOF IMU from AliExpress (pictures below), asking because this seems to be somewhat of a common issue (and I'm a bleeding noob). I tried setting up this board using example codes from Adafruit - presuming this would work and it's a compatible board (and it just looked exactly the same). However, surprise - several errors.

Using this guide I attempted to run the pitchrollheading example - it reports LSM303 not found. The wiring is according to this guide, A4 (SDA) and A5 (SCL) are connected, 5V in, Ground of IMU to Ground of Arduino (Arduino uno, like in the guide)

Next I debugged the lines on the board using the multimeter: 5V on line in vs ground, 5V on the SDA/SDC lines (seemed fine)

Then I debugged using the i2cdetect library, however it reported empty.
 0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
 00:          -- -- -- -- -- -- -- -- -- -- -- -- --
 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 70: -- -- -- -- -- -- -- --

Using analog read I can get values that seem to change with board movement, that would confirm that - in theory - the board works.

Questions

Making sense from debugging: What could be somre reasons the board not listed using the i2cdetect library (also tried a script)?
Is there an easy way (or would you recommend spending time to investigate) to use the rawdata from the arduino's analog in lines to compute pitch,roll and heading?
Would a project like this be typically orders of magnitude easier to set up with a raspberry pi (I have one setup and ready)? (more libraries?)
Are IMU's usually easy to setup, and is it likely this would be easier with a more expensive IMU (e.g. MPU9250/6500)?

Thank you in advance, and please remember: I'm a noob, I ask for your patience and advice.

You didn't mention connecting the ground of the board to the ground of the Arduino... did you?

yes, I did! :))

initially I tried this with an Arduino nano and phone otg cable. But then same results with pc and Arduino uno

@Majenko thanks, added it in the description

@jsotola because I want the advice from the community and proceed to acquiring data (which I'm looking forward to). Possibly there is a recommendable way to integrate the raw sensor values into a sensor fusion system, as stated, I'm a noob with this, advice is very welcome. On the other hand I'm unsure why asking 'why' is goal-oriented - unless you presume a gross misconception?

what, no, I can read the analog out, but can't properly connect any library... unclear to me why you want to shut this down. I also wanted help to properly debug and figure out if the device is broken in a way I don't understand yet

@jsotola you made an edit ('truck has no fuel', which I'm not even sure what it is supposed to be an analogy for) in your comment that makes your condescending attitude clear. I don't think that is what this community deserves... just point out how I can improve, or improve my understanding. This is literally what I'm asking for. It's not like it's hard to find condescending attitude rather than any helpful remarks nowadays

Let us continue this discussion in chat.

I re-soldered all connections and used new wires. Now the board is recognized by the i2cdetect library. Upon multimetering all connections using the continuous mode, I noticed my breadboard sometimes does not conduct properly. Cheap breadboards and/or cables are at fault here, as far as I can tell - a rookie mistake. I'm guessing the ground connection is the only one I have not measured before, will delete question in 24-48h unless objections

post that as an answer and accept it ... it may be useful for someone in the future

I re-soldered all connections and used new wires. Now the board is recognized by the i2cdetect library. Upon multimetering all connections using the continuous mode (the one that looks like a loudspeaker), I noticed my breadboard sometimes does not conduct properly. Cheap breadboards and/or cables are at fault here, as far as I can tell - a rookie mistake. I'm guessing the ground connection is the only one I have not measured before


text:
How to access Software Serial contents/value and extract some details?
I'm using SoftwareSerial with a SIM808 GSM modulde to detect incoming SMS messages.
The problem I'm currently having is that I need to access the phone number from the received SMS so I can send a reply back to that number.
I'm trying to access the contents of the SoftwareSerial and print it to the serial monitor, just so I can see its contents but for some reason, nothing at all is being output. The "Message received" string is being output to the monitor, along with everything else that's needed. It's just the mySerial.read() that won't show.
How can I access the incoming SMS message and get the phone number from it?
Excuse the messy code. It's a work in progress.
 #include <SoftwareSerial.h>
 #include <ADSWeather.h>

SoftwareSerial mySerial(9, 10);

#define ANEMOMETER_PIN 2
#define VANE_PIN 0
#define RAIN_PIN 3

#define CALC_INTERVAL 1000

unsigned long nextCalc;
unsigned long timer;

int windDir;
int windSpeed;
int rainAmmount;
const int switchpin =  7;

ADSWeather ws1(RAIN_PIN, VANE_PIN, ANEMOMETER_PIN); //This should configure all pins correctly

void setup()
{
  pinMode(switchpin, OUTPUT);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(ANEMOMETER_PIN), ws1.countAnemometer, FALLING); //ws1.countAnemometer is the ISR for the anemometer.
  nextCalc = millis() + CALC_INTERVAL;

  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  delay(100);

  digitalWrite(switchpin, HIGH);
  delay(3000);
  digitalWrite(switchpin, LOW);
        RecieveMessage();
      Serial.write("SMS set to recieve messages");
}

void loop()
{

  timer = millis();

  int rainAmmount;
  long windSpeed;
  long windDirection;
  int windGust;
  int sent;

  ws1.update(); //Call this every cycle in your main loop to update all the sensor values

  if(timer > nextCalc)
  {

    nextCalc = timer + CALC_INTERVAL;
    rainAmmount = ws1.getRain();
    windSpeed = ws1.getWindSpeed();
    windDirection = ws1.getWindDirection();
    windGust = ws1.getWindGust();

//     windSpeed / 10 will give the interger component of the wind speed
//     windSpeed % 10 will give the fractional component of the wind speed
    Serial.print("Wind speed: ");
    Serial.print(windSpeed);
    //Serial.print('.');
    //Serial.print(windSpeed % 10);
    //Serial.print(" ");

    Serial.print(" Gusting at: ");
    Serial.print(windGust);
    //Serial.print('.');
    //Serial.print(windGust % 10);
    Serial.println("");

  }

  //if (Serial.available()>0)
  //{
      //RecieveMessage();
     // Serial.write("SMS set to recieve messages");
  //}

//  mySerial.flush();
 // serialFlush();

  //If an message comes in
 if (mySerial.available()>0){

  Serial.write("Message received");
  Serial.write(mySerial.read());

  String stringSMSMessage;
  stringSMSMessage = String("Wind speed near St. John's lock: ");
  stringSMSMessage += windSpeed;
  stringSMSMessage += "MPH";
  //stringSMSMessage += '.';
 // stringSMSMessage += windSpeed & 10;
  stringSMSMessage += " Gusting at: ";
  stringSMSMessage += windGust;
    stringSMSMessage += "MPH";
 // stringSMSMessage += '.';
  //stringSMSMessage += windGust % 10;
  stringSMSMessage += ' ';

  //Send the wind speed response.
    mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"07769218312\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println(stringSMSMessage);// The SMS text you want to send
  delay(100);
   mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(10000);
  mySerial.flush();
  serialFlush();

}
}

 void SendMessage()
{
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"Phone Number Goes Here\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("I am SMS from GSM Module");// The SMS text you want to send
  delay(100);
   mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(10000);
  mySerial.flush();
  serialFlush();

}

 void RecieveMessage()
{
  mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  delay(1000);
 }

 void serialFlush(){
  while(mySerial.available()>0)  {
     mySerial.read();
    }
}

What are you expecting to show up? Serial.write(mySerial.read()); will just send exactly 1 byte/character from the mySerial buffer over Serial. Nothing more. Only 1 byte. You need to read the full message from mySerial. Then you can send that over Serial.

Why not digging more on AT commands....you can send At command and can get data.
https://www.electronicsforu.com/resources/cool-stuff-misc/gsm-at-commands Just send the commands and read the response then print to serial monitor.

Excuse the messy code. It's a work in progress. ... the look of the code is not important ... mostly, it is properly indented, which should keep you from adding code in wrong places .... there is a problem though, there is too much code for the problem you are trying to solve .... there is no reason to have any sendMessage code ... all you need, at this time, is SMS receive code and print received text code ... when that code works, add extract phone number code