text:
Buzzer+Push button+arduino
I want to stop the sound of a buzzer after I push the push button. I tried a code, but when the button is not pushed, the buzzer continue to make sound. How can I fixed it?
const int pin_contact= 6;
const int buzzer = 9; //buzzer to arduino pin 9

void setup(){
  pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output
  pinMode(pin_contact, INPUT);
  Serial.begin(9600);
}

void loop() {
  tone(buzzer, 200);

  int stare_contact = digitalRead(pin_contact);
  if (stare_contact == HIGH) {
    noTone(buzzer);
  }
}

i tried with screen capture, but I couldn't upload in the comment, this is why i used a link. But in the end, I succeeded, using the first code and added 2 resistors in the circuit. Thank you!

If one of the answers helped you, you can vote it up.  If neither helped you and you think you can provide an answer that someone else would find useful, you can answer your own question.  If the question is both unanswered and unanswerable, then it's probably better off deleted.

It is good to know. Right know I was trying to vote the answer, but i have to earn 15 reputation to upvote posts.

Ah, well, there's 10 for you.

You restart the buzzer sound on every iteration of loop() so as soon as you stop pushing the button, the sound starts again. The simplest solution would be to move the tone (buzzer, 200); command out of loop() and place it at the end of setup(). Also make sure your button actually reads “HIGH” when pressed. Many buttons are active “LOW”.

Try this
int LEDState = 1;
int SwitchPin = 6;
int LEDPIN = 9;

void setup()
{
  pinMode(LEDPIN,OUTPUT);
  pinMode(SwitchPin,INPUT);
  digitalWrite(LEDPIN,LEDState);
}

void loop()
{

  int SwitchState = digitalRead(SwitchPin);

  if(LEDState==1 && SwitchState==HIGH){
   LEDState = 0;
  }

  digitalWrite(LEDPIN,LEDState);
    delay(10);
}

Sorry Jsotla, i have fixed it now...  @Biancaaa I have fixed the code and i tried with an led except a buzzer because at this time buzzer is not available in my collections, afterall, try this code, this code worked very well for me using the LED as an output indicator instead of a buzzer

Is your buzzer active low? try this code below.
it will toggle buzzer pin output.
const int buzzerPin = 9;
const int buttonPin = 6;
int buzzerState = 1;
int buttonState;
int buttonTemp = 0;

void setup() {
  pinMode(buzzerPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  digitalWrite(buzzerPin,buzzerState);
  if (buttonState == HIGH && buttonTemp == 0){
    Serial.print("Buzzer toggle to : ");
    if (buzzerState) {
        Serial.println("LOW");
        buzzerState = 0;
    } else {
        Serial.println("HIGH");
        buzzerState = 1;
    }
    buttonTemp = 1;
  } else if (buttonState == LOW) {
    buttonTemp = 0;
  }
}


text:
[SOLVED]SIM7600 Module Power up by Arduino Uno doesn't work
Am using SIM7600X 4G HAT with Arduino Uno
I follow to manual to Power up the module and it works well, The NET light flashing.

But when I connect to Arduino Uno and use DigitalPin 2 write (High -> Delay500ms -> Low) for "power on pulse" it doesn't work, The NET light still not flashing.

My code:
#include <Waveshare_SIM7600.h>
// Pin definition
int POWERKEY = 2;

char phone_number[] = "XXX";      //Store the phone number you want to call

void setup() {
  Serial.begin(9600);
  sim7600.PowerOn(POWERKEY);
  sim7600.PhoneCall(phone_number);
}

void loop() {

}

code from Waveshare (Waveshare_SIM7600.h):
/**************************Power on Sim7x00**************************/
void Sim7x00::PowerOn(int PowerKey = powerkey){
   uint8_t answer = 0;

  Serial.begin(9600);

  // checks if the module is started
  answer = sendATcommand("AT", "OK", 2000);
  if (answer == 0)
  {
    Serial.print("Starting up...\n");

    pinMode(PowerKey, OUTPUT);
    // power on pulse
    digitalWrite(PowerKey, HIGH);
    delay(500);
    digitalWrite(PowerKey, LOW);

    // Stuck in below loop because Send AT command and no response ///////
    // Becuase NET light not flashing (not connect) //////////////////////

    // waits for an answer from the module
    while (answer == 0) {     // Send AT every two seconds and wait for the answer
      answer = sendATcommand("AT", "OK", 2000);
      delay(1000);
    }

  }

  delay(5000);

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

How is everything powered? SIM modules can draw rather big current (I remember something in the range of 900mA, though I'm not sure). You don't want to draw that current through the Arduino. If you don't provide enough current, the module might brown out and thus fail to work.

I don't know much about schematics but i following this youtuber guy, my SIM7600 module is like him, and arduino board is similar but i stuck at 2:20 in the video. int the video it work well. https://www.youtube.com/watch?v=KOig5ndq2ek&ab_channel=cytrontech

The GSM module requires a 5V 2A source and my Arduino Uno cant draw for it, my solution is to use a power bank that can draw 5V 2A for powering the GSM module and jump PWR pin to GND (manual said) the NET led start flashing and module can working but TX, RX pin still there for comm.

source: Stack Exchange

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

sort: votes


text:
Atmega 328p at 3.3v : Internal vs external oscillator
I am currently working on a pcb that uses smd atmega 328p (au).
I will be powering it through a lipo battery and a ldo regulator for 3.3v input. I am using the multiwii flight controller code.
I know that atmega runs at 8mhz at 3.3v and 16mhz at 5v without overclocking the chip.
The question is that should I use the internal 8mhz oscillator or external 8mhz?
I will definitely make the chip more accurate as given in some forums but still does this effects anything or not?

How much accuracy do you need for your project and is the internal oscillator accurate enough for this goal?

I'm guessing you have an unstated concern. I doubt it's power usage, since you're talking about a flight controller.  If you say what it is you'll probably get more useful answers.

If the 8 MHz oscillator is off by a handful of percentage points, it will affect timing measurements you make using millis() and micros(). It could affect the baud-rates of Serial or SoftwareSerial. If these are not of any concern, the only remaining difference would be how fast your code can be executed. It's unlikely that the code pushes the chip runs so close to its maximum capability that it would matter, even at ~8 MHz.
Update:

... I just want to know if clock frequency effects the code and if I need
to change code a bit like for example blink sketch runs at different
time intervals on 8mhz and 16mhz(I tested it).

If you do nothing else, then yes, millis() will appear to run at half speed. You need to add a board definition to the IDE for an Arduino Uno running at 8 MHz. Then millis() and micros will be adjusted for the slower processor clock. How you do this depends on whether you choose the internal and less accurate 8 Mhz oscillator, or an external 16 MHz crystal.
For the internal oscillator, there is a board-definition on Github with instructions to load it into your IDE.
For an external oscillator, this article describes how to select the board type as "Arduino Pro or Pro Mini" and then be able to select the board frequency, using the Tools menu twice.

I don't know how much accuracy I need for this purpose but I know that the project will use i2c protocol  for mpu6050 accelerometer and communication through nrf24l01 . I m a noob at coding but I just want to know if clock frequency effects the code and if I need to change code a bit like for example blink sketch runs at different time intervals on 8mhz and 16mhz(I tested it).

Thanks Robert for the answer . I will look forward for both internal and external oscillator

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


text:
ESP8266 Repeated Crashing When Pulling JSON Information
I am trying to create a simple LCD device that pulls a random Jeopardy question from here: http://jservice.io/api/random, then cycles through the category/value, clue, and correct question at the push of a button. However, I am running into problems when I pull the clue. I am running this on an AdaFruit Feather Huzzah esp8266, but the board repeatedly crashes before returning the GetJeopardy function. In particular, I get errors like this:
--------------- CUT HERE FOR EXCEPTION DECODER ---------------

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 3584, room 16
tail 0
chksum 0xb0
csum 0xb0
v2843a5ac
~ld

The function is as follows:

typedef struct {
  const char* cat;
  int val;
  const char* clue;
  const char* corr;
} jeop_problem;

jeop_problem GetJeopardy(){
  jeop_problem JQ;
  const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) +
                            JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
  DynamicJsonDocument doc(bufferSize);
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("Pulling Jeopardy");
    HTTPClient http; // Object of class HTTPClient
    WiFiClient client;
    http.begin(client, "http://jservice.io/api/random");
    int httpCode = http.GET();
    deserializeJson(doc, http.getString());
    http.end(); // Close connection
    const char* cat = doc[0]["category"]["title"];
    JQ.cat = cat;
    Serial.println(cat);
    int val = doc[0]["value"];
    JQ.val = val;
    Serial.println(val);
    const char* clue = doc[0]["question"];
    JQ.clue = clue;
    Serial.println(clue);
    const char* corr = doc[0]["answer"];
    JQ.corr = corr;
    Serial.println(corr);
  }
  else {
    // We don't have a connection, return blank problem
    JQ = {"ERROR: RESET", -1, "ERROR: RESET",
                                    "ERROR: RESET"};
  }
  Serial.println("Pulled Jeopardy!");
  return JQ;
}

In particular, the board is always crashing before printing "Pulled Jeopardy" to the Serial console.
Thanks in advance!

I should have mentioned, it does get through all the Serial.println(corr); but does not get to Serial.println("Pulled Jeopardy");

To be sure any of them were reached, you'll want a following .flush() call.  Otherwise it may crash/reset immediately afterwards and you wouldn't know the difference.  Put differently, without a .flush() after, Serial.println("Pulled Jeopardy"); you can't be as sure that it didn't actually get to that line.

I don't know how your code relates to your reset cause.  It's possible that it doesn't at all.  But so long as you're providing information about where it hangs, it might as well be as accurate as possible.

the responses are over 1kb, how will that fit in such a small buffer? try a 4kb buffer (you have an 8266 here, not an UNO ;) )

I had the same issue caused by definition of StaticJsonDocument<200> jsonDoc inside a function. When I moved the definition as a global variable (out of the function) the problem was solved. I would suggest to try moving DynamicJsonDocument doc(bufferSize) out of the function.


text:
Any way a GSM sim 900 can still work (USA)?
so I’m pretty new to arduino and have been working for weeks on a GPS tracker using a sim 900 and a knock off neo 6M. All my code seemed to be working but for some reason I could not get the sim900 to establish a connection. Took me long enough to find out 2G carriers have been pretty much shut down. This is for a project and I don’t have time to start over with a 4G shield. Are there any cell carriers that still support 2G? What are my options? I don’t know what to do
Edit: more detail, I’m using the sim 900 to send an sms with a gps location

we don't either ... you did not say what you are doing, so it is impossible to guess any alternatives

Somehow I got a connection! I live in PA but when I went to Boston for school I got 2G service. Maybe carriers haven’t fully shut it down.


text:
How to receive commands to a running arduino program from a raspberry pi?
I have looked all over for a solution to this. I'm a noob in the arduino space and am really just getting my feet wet. It's possible that I am interpreting what I am reading wrongly. If so I apologize. Here is my problem/question. I want to create an autonomous driving small land drone. It would connect to some drive sensors, dc motors and do some stuff all by itself. In addition to this I want a raspberry pi with a camera surveying the scenery. Because it is unknown if/when the raspberry PI will see something that is interesting i want this default behavior to occur. The reason I want to do it like this is that I read it is better performance to drive from the Arduino because a linux based computer has so much stuff running on it there could be more lag in the response. In addition the python program will be making HTTP requests, doing image processing, and potentially doing even more. If the image processing software on the PI picks up something interesting then I want this functionality to override the Arduino default program. I was thinking to create a program in Arduino for the basic drive functionality but then be listening to a python process that is running on the PI. If it hears a command to go do something, then of course it will drop the default program, go complete the python generated task and once it is done then it will continue with the arduino default program.
How do I in effect listen to a python process from the Arduino? Or would the proper solution be to not even use the Arduino but drive it all from python on the PI? Any suggestions for how to solve this would be great to hear. I feel like there is an obvious best practice way to do this that I am not aware of. Thanks in advance!

You can connect the Arduino via USB to the Pi
The Arduino should show up as a serial device; and thus you'd be able to communicate from Pi to Arduino and vice versa.
But you may want to try and get it working on your PC first.
There should be plenty of comparable projects online, see if you can find one that looks a lot like what you're trying to achieve

What you are asking for is not completely trivial, and may be ill-suited
for a beginner's project. You will have to create a protocol for the
communication between the Raspberry Pi and the Arduino (your own
“command language” of sorts), and then implement on the Arduino a
command interpreter that understands this protocol and acts accordingly.
I highly recommend you use a text-based protocol, as this will be way
easier to debug than a binary protocol.
For the Arduino side of the project, you first have to learn how to
read the serial port from the Arduino. Then, you can take a
look at this very basic command line interpreter for
inspiration. Or you can search for Arduino libraries that provide
similar interpreters.
On the Python side, you have to open the serial port (/dev/ttyACM0)
and send your commands through it. The details on how to do that
would be a Python question, which is are out of scope here.

Thank you Edgar you clearly don’t know me very well as “not suitable beginner project” is my middle name


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

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

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

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

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

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

int screenWidth = 16;
int screenHeight = 2;

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

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

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

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

}

void loop() {

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

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

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

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

    if (mapX > 200) {

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

  } else if (mapX < -200) {

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

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

Any help would be great.

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

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

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

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

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


text:
[SOLVED]how to send command to Gsm module from Arduino via serial port
Am using SIM7600X 4G HAT module (GSM) and Arduino Uno
after I start the module and Arduino, I receive data from Gsm module but I can't send any command to it.
On my Arduino board when I get data RX led flashing, and when I send command TX led flashing.
#include <SoftwareSerial.h>
SoftwareSerial myserial(3, 4); // gsm_TX, gsm_RX

void setup(){
  myserial.begin(9600); //Initialize GSM serial port
  Serial.begin(9600); //Initialize Arduino default serial port
}

void loop(){
  while(1){
    while (myserial.available()) {
      //Serial received data, output via mySerial.
      Serial.write(myserial.read());
    }
    while(Serial.available()) {
      //myserial received data, output it via Serial.
      myserial.write(Serial.read());
    }
  }
}

As the picture I send "AT" command or any command it no response.
it show only module start up command.

My circuit

I solved my problem, On my circuit GSM module use an external source and my Arduino Uno use serial port source, So it cant communicate via pin because both ground of them did not connect to each other then the answer is connected GSM module GND to Arduino Uno GND.


text:
How to improve the sampling rate of Arduino due ADC?
I am now working on a project, which needs a cheap analog acquisition device with a sampling rate of no less than 5MHz. Before, I only used Arduino, and rarely operated the registers on Arduino. I hope to use Arduino due to complete it. I spent a lot of time researching and querying solutions, but it didn't succeed. I hope someone can help me.

Or is there any other solution?

To help us come up with a possible solution, please tell us exactly what you are trying to do. Why 5 MHz?  That's rather a lot.  How many bits of resolution?  Also, at that sample rate you will be getting a flood of data; what will you do with it?

I want to collect the pulse signal of the scintillator detector. The duration of this pulse is less than 1 us. In order to maintain the accuracy, the sampling rate must be higher than 5 MHz. The more data bits, the better. I will temporarily store the obtained data in Arduino, stop sampling after accumulating a certain amount, and then start analysis. After the analysis, I will discard the sampling data.

I haven't used the Due, but I understand its ADC is rated for 1 MHz sampling.  If that's its absolute limit then you can't expect 5 MHz.  However, judging by the Unos which I have used, you may be able to push things by limiting the number of bits.  This gives a speed boost two ways, by shortening the time the ADC uses to acquire the data, and if you limit to 8 bits you have half as many bytes to move into memory.
Do not try to use more than one channel, since then you have multiplexer delays as well.
Also, you may want to skip interrupts and just sample in a tight loop. Using this loop trick doubles the useful ADC rate of the Uno, from 50 kHz to over 100 kHz. (You'll need to figure out the actual sample rate by reading the timer before and after the loop, then divide by the loop size and take the reciprocal.)

Thank you very much for your reply. After your reminding, I have turned off my interrupt. It's really effective, but it's still far from enough. I think 12 digits are offline to ensure accuracy.，so It seems that I may have to find another way.


text:
AVRdude does not read the FUSE byte values correctly
I am exploring the ATmega328p MCU via a standard Arduino UNO, with the help of avr-gcc toolchain and AVRdude (All in the WINAVR package). I have successfully programmed the board a few times with it. However, when I try to read the fuse values via AVRdude, I get 0x0 for lfuse, hfuse and efuse.
I am using the following command (or its variants) to read:
avrdude -c arduino -p ATMEGA328p -P com3 -b 115200 -v -F -U hfuse:r:hi_fuse_val.hex:h
Following is the output I get:
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0

The file hi_fuse_val.hex also has 0 written to it.What am I doing wrong?

A couple of things.  That you can't change fuses from the bootloader and that optiboot can't report fuse values correctly, even if you change them.
No self-programming of fuses
A bootloader can't write fuses, at all.  The chip just doesn't allow self-programming of fuses.  If you want to change fuses, you'd need to resort to external programming (usually using the ISP protocol) with an AVR programmer (or another Arduino set up to behave as one).
Optiboot and reading fuses
Optiboot doesn't report fuses, at least not as compiled for UNO.
The "arduino" bootloader protocol used by the avrdude -c arduino option is a modified version of the STK500(v1) protocol.  The are two commands there that would need to be implemented to read fuses, Cmnd_STK_READ_FUSE and Cmnd_STK_READ_FUSE_EXT.  They have corresponding definitions in the AVR Arduino core's copy of optiboot source.  But the places where they would be implemented in the series of if-elses are absent.  Unlike writing fuses, reading fuses is possible from AVR code.  So it's not a limitation of the chip, the code to do it just isn't there.
Sidenote: You may notice that there are also definitions for commands that write FUSES.  These exist for STK500v1 programmers rather than bootloaders, which can implement these to support writing fuses.
For what it's worth optiboot doesn't actually read the signature of the chip either.  It just reports whatever values have been baked in at compile time.  Both this and the not-reading-fuses above are probably done to keep optiboot as small as possible, which is its goal.
In any case, if you do change your fuses using a programmer, expect optiboot to continue reporting them as zero.
Current fuse values
If you're curious about your actual fuses values, you run sketch that reads them and prints them over serial by using #include <avr/boot.h> and
Serial.print('E');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS), HEX);

Serial.print('H');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS), HEX);

Serial.print('L');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS), HEX);

Thanks a lot for the detailed response. Much appreciated.


text:
How can I share one power supply between an arduino and servos?
I'm trying to power an arduino and a few modules (RF receiver, two servos, and a laser diode) through one power supply.
I get jittery/unresponsive servos when hooked up in the following configuration:

power supply goes to usb breakout, joins with top + and - rails, powers everything (tried
all grounds go to top - rail
black/grey/white wires going off right side are power/ground for the servos
red, green, yellow wires going off left/top side are signals to the servos/laser
purple wire going off left/top is ground for the laser

If I remove the orange wire (usb breakout to + rail) and plug another power supply into the Arduino, the poor performance disappears and everything works nicely.
Since my power supply is 2.5A, I doubt that I don't have enough power for this setup. This leads me to believe that the Arduino/receiver side of the circuit is making the voltage unstable so the servos misbehave. Is there a way I can isolate these two parts of the circuit (diode, capacitor?) so that I can power the whole setup with one cable?
Components:

Arduino pro micro (5v)
RF Link Receiver (WRL-10532, 434 MHz)
Servo (ROB-09065, sub-micro)
Laser diode (5V, 20mA)
Micro USB breakout (1A)
USB Micro power supply (5.1V, 2.5A)

Sorry, that image does not show up. And when I follow its link, I'm required to log into google. If you save the image on your PC and then drag and drop it into the image field, the image will be uploaded correctly.

What USB breakout board do you have exactly? It might not be able to provide the needed current.

Interesting--I tested in incognito and the picture still loaded.. guess there's some interesting access caching going on. Should be visible now?

Good call--it looks like the breakout says 1A (edited it into the post). That still feels high enough for these components, but maybe they are trying to pull more than this?

Yes, I can see the image now. How are you powering the Arduino? I don't see a wire from the USB breakout Vcc to the red rail (where Vcc of the Arduino is connected)

My mistake, ended up with the wrong photo. Corrected now.

You're not feeding the +5V into the USB port of the Arduino, are you, and then trying to power everything through the Arduino's +5V lines?

You need to figure out your total current requirements. Don't guess, figure it out. What is the peak current draw of the servos? of the other components? Add everything up. If the total is within 20% of your power supply current, that may be the problem.
Also, servos tend to draw spikes of current. You might need to add a filter capacitor to the +5V rail on the Arduino to even out dips as the servos cause sags in current before the voltage regulator in your power supply can compensate. (Put the cap between +5V and ground right at the Arduino.)

Fair. I estimated 0.2 + 0.25 * 2 ≈ 0.7A peak, but I'll measure to confirm. I wasn't considering that large a margin either. I'll also try the filter capacitor. Thanks!

The closer you get to the power supply's limits, the more its voltage is likely to "bobble" as the load varies, and motors loads are usually quite "spiky".

I too have found the servo driving of the Arduino ie UNO to be jittery. The problem is that the Arduino uses a timer, interrupts and software to terminate the pulse so if the processor is busy servicing another interrupt then the pulse gets extended by up to 10us. Modern servos, even the cheap ones, respond to this delay as if it were noise.
The servo library was dependent on clock frequency, and limited to pins 9 & 10, at one point in time, although that might have been fixed in updated versions. out of curiosity, what pins are you attaching your servos to? (9 or 10?)
you might try updating your version of the ardunio IDE/Libraries.
another thought, is that many servos are rated at 6V (not 5v), and while they will work, they may also be jittery. you might find it best to use a separate power supply. Be sure to connect the grounds of the Arduino and external power supply together.
From Servo.h:
...
    //attach(pin )  - Attaches a servo motor to an i/o pin.
    //attach(pin, min, max  ) - Attaches to a pin setting min and max values in microseconds
    //default min is 544, max is 2400
...

#define MIN_PULSE_WIDTH       544     // the shortest pulse sent to a servo
#define MAX_PULSE_WIDTH      2400     // the longest pulse sent to a servo
#define DEFAULT_PULSE_WIDTH  1500     // default pulse width when servo is attached
#define REFRESH_INTERVAL    20000     // minumim time to refresh servos in microseconds
...

you might try tweaking the min, max, and default settings, or check your code against the settings provided by Servo.h.


text:
How to adjust Partition Scheme Wemos D1 mini pro?
I bought myself a WEMOS D1 mini PRO (16MB) for creating a quite large project.
As I'm writing code, my memory is starting to grow.
When I looked at the Flash size in Arduino IDE, the only options I have are

FS 14MB, OTA: 1019KB
FS 15MB, OTA: 512KB

The only things I need in the project is OTA and EEPROM. (no need for SPIFFS)
I looked around on the internet and came on a couple of sites that manipulate the filesystem.
https://robotzero.one/arduino-ide-partitions/
Also on other forums I read that you could modify the LD scripts that Arduino uses.
But I'm not sure how to define the addresses and what to do.
Here is a visual of the config I want.
ORIGINAL

ADJUSTED

Can someone push me into the right direction ?
Thanks in advance.

the maximum size of application code on esp8266 is 1MB

I know but it is possible to adjust the 1 MB. But I don't know how to adjust the addresses.

adjust how? 1 MB is the limit of the CPU on addressing instructions. why is your code so big? put large strings or data in FS files.

@JensVanhulst What Juraj is saying is that the CPU cannot cope with any more than 1MB. Regardless of the size of the flash. That is why there are no settings where the code size is more than 1MB - it's the absolute maximum that you can have. No amount of fiddling with config files can change that, it's a physical property of the chip.


text:
How to completely clear everything from an arduino and print something new?
I'm in progress of making a stickman rush game, Until I hit a bug that I have been stuck on. I want to make a if statement that states "If the stickman and the object are in the same place, clear everything and print "Game over." But when i do this, the object is still there. I tried using "lcd.clear()" but it doesnt seem to affect anything. Is there another way to fix this?
Code:
#include <LiquidCrystal.h>

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

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

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

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

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

int screenWidth = 16;
int screenHeight = 2;

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

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

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

  lcd.createChar(1, gameObstical);

}

void loop() {

  int stickManPosition = 0;
  int obsticalPosition = 0;
  int stickManRow = 0;
  int obsticalRow = 0;

  int obsticalPosition2 = 0;
  int obsticalRow2 = 0;

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

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

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

    if (mapX > 200) {

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

    } else if (mapX < -200) {

      stickManRow = 1;

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

    if (stickManPosition == obsticalPosition) {
      if (stickManRow == obsticalRow) {

        lcd.clear()
        lcd.print("Game Over...");
        delay(150);

      }

      if (obsticalPosition == 12) {

        for (obsticalPosition2 = 11; obsticalPosition2 >= 0; obsticalPosition2--) {
          obsticalRow2 = 1;

          lcd.setCursor(obsticalPosition2, obsticalRow2);
          lcd.write(byte(1));
          lcd.print(" ");
          delay(150);
        }
      }
    }
  }
}

Any ideas? Thanks for reading.

You could just make setCursor(0,0);, print sixteen spaces and repeat it for the second row... But I'm sure there's a better way.

I've not intensively looked over your sketch. But, is it possible that the screen is really cleared with lcd.clear(). "Game over" is visible for less than 150 milliseconds and then other code in the loop function overwrites it with the stickman again. 150 ms is a very short time. Would you please change the delay(150) after the clear to let's say delay(3000);. To see if my guess is true?

You need to distinguish between someone actively playing a game and the game being over. You really need to implement a finite state machine.

you should create a condition to write objects, If game is over then dont draw objects else draw objects. or after your game is over create an infinite loop and get button push for break loop.


text:
Problem getting data from Arduino pro mini
I am currently working on a drone project using multiwii.
I m using mpu6050 as gyro and accelerometer sensor with i2c protocol. I was able to read data coming from mpu6050 while using Arduino Uno through multiwii but can't get it work with Arduino pro mini. I was able to get data with pro mini while using i2c scanner and mpu6050 test codes available on web but can't see any data from sensor on multiwii platform though it shows that Arduino is connected. I tried using pull up resistors and try with another pro mini but with no luck. One note is that because I will be using this with a 1s lipo battery ,I bootloaded both pro mini with 8mhz internal oscillator at 3.3v and even tried using external oscillator 8mhz but with no luck (I actually modified both of them cause 3.3v Mini's are not available in my country). I am using Arduino Uno without ic to program the pro mini board and its having no problem while programing or while reading data on serial monitor but only with multiwii. I tried multiwii with my Uno and nano and both worked just fine so right now I m wondering if on board programmer effects this but I have seen some people using pro mini with multiwii
My connections are not lose at all cause I soldered them directly to the Uno board.


text:
int array passed through function has wrong values only after multiple passes
I have this code:
for(int i = 0; i < its; i++) {
    x1 = random(0,4);
    y1 = random(0,4);
    multiLamp(new int[2] {3,1}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {2,0}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    x2 = random(0,4);
    y2 = random(0,4);
    multiLamp(new int[2] {1,3}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {0,2}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
}

which calls the function "multiLamp" and passes 3 int arrays with 2 values each. Here is the function:
void multiLamp(int epos[], int xpos[], int ypos[], int del, int len) {
  for(int it = 0; it < del; it++) {
    for(int i = 0; i < len; i++) {
      lamp(epos[i],xpos[i],ypos[i],2);
    }
  }
}

This function is supposed to call some function "lamp" with a few integers from the arrays. In the beginning this works fine but after more than 50 calls of the "multiLamp" function the values in the arrays become {0,128,128} and {3,3,3} or something similar even though the values passed into it from my main code are equally valid as before (they are somehow changed after being passed to the "multiLamp" function).
I can't seem to find the issue here. Any help is appreciated!
UPDATE:
Here is the full code, although I don't know if it will be of any use because I wrote it to control some LEDs and if you don't have the setup it's difficult to see if the code is working or not.
int e[] = {12,13,11,10};
int xy[] = {2,3,4,9,6,7,8,5,1,A0,A1,0,A3,A4,A5,A2};

void setup() {
  for(int a=0;a < 4;a++){
         pinMode(e[a], OUTPUT);
         digitalWrite(e[a], LOW);
  }
  for(int b=0;b < 16;b++){
         pinMode(xy[b], OUTPUT);
         digitalWrite(xy[b], HIGH);
  }
}

void loop() {
  bigCubes(100);
  rain(20, 30);
  miniCubes(15);
  every(80);
}

void lamp(int epos, int xpos, int ypos, int del) {
  int xypos = 4*xpos+ypos;
  digitalWrite(e[epos], HIGH);
  digitalWrite(xy[xypos], LOW);
  delay(del);
  digitalWrite(e[epos], LOW);
  digitalWrite(xy[xypos], HIGH);
}

void multiLamp(int epos[], int xpos[], int ypos[], int del, int len) {
  for(int it = 0; it < del; it++) {
    for(int i = 0; i < len; i++) {
      lamp(epos[i],xpos[i],ypos[i],1);
    }
  }
}

void every(int wait) {
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      for(int k = 0; k < 4; k++) {
        lamp(i,j,k,wait);
      }
    }
  }
}

void miniCubes(int wait) {
  int cube[8][3] = {{0,0,0},{0,0,1},{0,1,1},{0,1,0},{1,1,0},{1,1,1},{1,0,1},{1,0,0}};
  for(int c = 0; c < 8; c++) {
    for(int it = 0; it < wait; it++) {
      for(int i = 0; i < 8; i++) {
        lamp(cube[i][0]+2*cube[c][0],cube[i][1]+2*cube[c][1],cube[i][2]+2*cube[c][2],2);
      }
    }
  }
}

void bigCubes(int wait) {
  multiLamp(new int[32] {0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3}, new int[32] {0,0,0,0,1,1,2,2,3,3,3,3,0,0,3,3,0,0,3,3,0,0,0,0,1,1,2,2,3,3,3,3}, new int[32] {0,1,2,3,0,3,0,3,0,1,2,3,0,3,0,3,0,3,0,3,0,1,2,3,0,3,0,3,0,1,2,3}, wait, 32);
}

void rain(int its, int wait) {
  int x2 = random(0,4);
  int y2 = random(0,4);
  int x1;
  int y1;
  for(int i = 0; i < its; i++) {
    x1 = random(0,4);
    y1 = random(0,4);
    multiLamp(new int[2] {3,1}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {2,0}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    x2 = random(0,4);
    y2 = random(0,4);
    multiLamp(new int[2] {1,3}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {0,2}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
  }
}

Mhh, I see you creating 3 new arrays on each call of multiLamp(), but I never see you freeing them again. Beside the fact, that dynamic memory allocation is bad on an AVR board like the Uno, you need to actually free the allocated memory again, when you don't need it anymore, or you will rather fast fill up the RAM. If no memory is left, the Arduino behavior is undefined (though mostly they just reset). That seems the best candidate for the problem reason. Can you please provide a full compilable example sketch, which shows your problem? (not just a snippet)

The part that's actually a problem is really a general programming problem.

@chrisl I added the full code although I don't know if it's of any use to you.

@chrisl Do I have to free them up manually? I thought the arrays would free up if the function ends?

You are wrongly using the new operator for your arrays. That will dynamically allocate these arrays. They are put on the heap (not the stack like local variables) and thus don't get freed automatically, when the function exits. That has to be done by your code with the delete keyword. Your code just eats up all the available memory. Thats called a memory leak.
That you need to free your dynamically created variables is not an Arduino thing; this is correct for all C/C++ code. But the limited memory on AVR based Arduinos like the Uno makes it worse.
If you do the math, one iteration of void loop() will block 432 bytes of memory (216 array elements, each of type int thus 2 byte). The 2KB of memory (which is also needed for local and global variables) is eaten up rather fast.
I don't see, why you even would use dynamically created arrays. Why not just using locally defined arrays, like in the miniCubes() function?

That said, it is also a generally bad idea to use dynamic memory allocation microcontrollers, especially those with small memory. When creating and deleting objects of different sizes (which is the main advantage of dynamic allocation), you will leave small holes in your RAM, which are too small for one of your objects to fit. At some point your RAM is completely filled with these holes, so that no more memory can be allocated for your objects to save. Thats called memory fragmentation.
On your PC that isn't a problem because of 2 reasons:

The PC has loads of RAM available, and
the OS manages the RAM, defragmenting it, if necessary.

Since microcontrollers don't have an OS managing the RAM and often very limited RAM, you need to make sure, that your RAM doesn't get fragmented too much in the runtime of your code.

Many thanks! I did it as you told me and did it like in the miniCubes() function. That worked great.


text:
DS3218MG Servo - Not working with power supply
I'm trying to run my DS3218MG Servo Motor with an external power supply and my arduino nano.
I'm using the following code:
#include<Servo.h>
Servo Myservo;
int pos;
void setup()
{
Myservo.attach(3);
}

void loop()
{

for(pos=0;pos<=180;pos++){
Myservo.write(pos);
delay(15);
}
  delay(1000);

  for(pos=180;pos>=0;pos--){
Myservo.write(pos);
delay(15);
}
  delay(1000);

}
According to the datasheet the servo needs a DC 4.8-6.8 voltage. My first attempt was to only use the arduino and no external power supply. So did the following connections:

servo's ground to arduino's ground
servo's + to arduino's 5V
servo's data to arduino's GPIO pin 3

Using this connection works fine and the servo rotatates to the desired positions. However, because the arduino does not supply enough current, i bought a power supply with the following specs:

With that, i did the following connections:

connect the ground of the power supply to arduino's ground (and servo)
keep the data pin
connect + of power supply to servo's +

Unfortunately, the servo does not move with the external power supply. IMO, it should have the right voltage and also supply enough current (at least as much as the Arduino).
Do you see the problem?

How are you powering the Arduino in the new setup?

regular usb cable for powering arduino

I would set the external power supply to 5V (your photo shows 6V) and try to measure the voltage of the servo while the Arduino is attempting to move it. Your servo is a high current device, which is not really suitable for connecting to a breadboard.

but 6 V should be fine since the servo allows DC 4.8-6.8 shouldn't it? However, nothing happens with 5v either - also when i directly connect the power +  to the servo +  instead of using a breadboard. How do I measure voltage of servo while arduino is attempting to move it?

Except you're interfacing a 5V device to it, which might or might not cause problems when running the servo at 6V (probably not, but the servo works at 5V either way). Did you measure the voltage on the servo's pins when you're trying to move it?

how can i measure this? do you mean the voltage from the power supply?

I mean measure the supply voltage going into the servo, as close to the servo as possible, to see if the breadboard is causing an issue (bad contacts, high resistance).

but as I said before, I also tried to remove the breadboard and solder the connections directly i.e. solder the + of the power to + of the servo. Shouldn't it actually work with that?

@starcat,  regular  usb cable for  powering  arduino


text:
Arduino IDE 1.8.13 won't launch properly
Recently I have been trying to install Arduino IDE 1.8.13, and I have ran into according problem.
When trying to launch Arduino IDE with ./arduino command it shows according error:
./arduino: line 35: /home/wiktor/Downloads/arduino-1.8.13/java/bin/java: No such file or directory

I have checked and java file does indeed exist.
I am using 32 bit version of Arduino IDE and 32 bit version of Linux Alpine 3.13.3.
Thanks for all answers

Note: Below, technician 274 (the original poster) commented:

It ended up working, after following alpinelinux wiki and installing
the IDE using flatpak.

Part of the problem is how confusing the message is.
No such file or directory is not actually referring to the java file.  It's referring to the ld-linux.so interpreter specified in the elf file.
If you run the file command on the java executable, you'll see output that looks like:
./java/bin/java: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.9, not stripped

If you look for /lib/ld-linux.so.2, you're going to find that you don't have one, and that's the file it's complaining about.
Alpine Linux apparently uses Musl and the java binaries were compiled for glibc, which is normal for desktop Linux.  On a typical desktop Linux system, that the java that ships with the Arduino IDE was compiled for, all kinds of executables make use of ld-linux.so.2.  On your Alpine system, you'll find they're referring to /lib/ld-musl-i386.so.1 instead.  From this vantage point, it's more of a Linux problem than an Arduino one, but I thought it might as well have something of an answer to point people toward relevant looking resources:

https://wiki.alpinelinux.org/wiki/Running_glibc_programs
https://github.com/sgerrand/alpine-pkg-glibc

You may find it's easier to replace the java interpreter, but that won't be enough, because the Avrdude and GCC binaries will also expect ld-linux.so.2.
In the end, it may be easier to just not use Alpine Linux.

It ended up working, after following alpinelinux wiki and installing the IDE using flatpak.


text:
How to build and run AUnit tests
I found this example on how to create a project with AUnit tests: https://www.thecoderscorner.com/electronics/microcontrollers/embedded-testing/getting-started-unittesting-arduino/
According to it and projects I have found on github my project structure should look like this:
Application
    src
        SomeComponent.cpp
        SomeComponent.h
    tests
        TestSomeComponent
            TestSomeComponent.ino
    Application.ino

But when I try to run TestSomeComponent.ino with Arduino IDE or VSC with Arduino plugin it does not see contents of src folder. I am assuming that it is treated as a separate sketch. What is a proper way to build and run tests?
[edit]
Some context (not sure what matters):

Our target board is ESP32 DevKit v1
Optimally if our developers could run tests on Windows and Linux machines
I have not gotten yet to continuous integration. I will start automating once I have any test building and running

[edit 2]
I have tried command line tools. Got AUniter running and tried like this (hoping for some automagic done by tools):
me@mypc:~/workspace/Application/Application/tests$ auniter.sh test esp32:/dev/ttyUSB0 TestSomeComponent/

I have tried any sane path combination in include path directive, for example:
#include "SomeComponent.h"
#include "app/SomeComponent.h"
#include "../../src/app/SomeComponent.h"
#include <SomeComponent.h>
#include <app/SomeComponent.h>
#include <../../src/app/SomeComponent.h>

But I keep getting this:
TestSomeComponent:4:42: fatal error: ../../src/app/SomeComponent.h: No such file or directory

I never came up with an acceptable solution to this, either. Closest I got was mkdir ~/Documents/Arduino/libraries/SomeComponent cp -R src/* ~/Documents/Arduino/libraries/SomeComponent/ and then include <SomeComponent.h> in the test .ino files. That rankles because it means you can't actually unit test a library before installing it. I suspect that's how AUnit/AUniter's author was doing it, though, before they switched away from Arduino IDE/arduino-cli to EpoxyDuino - given all of the AUnit examples use the #include <Foo.h> style.

I eventually switched to PlatformIO. It took me less than half an hour to rearrange sources, fix some compiler issues, build and flash my device.
Tests work really well. You just need to keep tested sources in lib folder. I even got GoogleTest package so I can use gmock in my tests.


text:
Alternative to a delay so it can be interrupted
I have task which includes a 30s delay in the void loop. During this delay I want to be able to press a key on a keypad and have a message displayed on the serial monitor as an emergency stop. Since delays block code until they are done I thought I would be able to break them down into smaller sections so I could still press the emergency stop key in between them but of course that doesn't work. I've read through how to use the milis() function but from what I can gather it seems like it wouldn't work for my system as I need user input for it so the time from the start of the Arduino to me pressing the emergency stop button is different every time. Is there a way that isn't too complicated and would allow me to press the button during that 30s?
The delay is in if (key == '2') and the last part of the sketch is the emergency stop.
const int greenLED = 13;  //Declares greenLED as being connected to D13
const int redLED = 12;    //Declares redLED as being connected to D12
//
const int ButtonT1 = 11;    //Declare pin number for ButtonT1 as D11
int ButtonT1State = 0;      //Variable for reading ButtonT1 state
const int ButtonT2 = 10;    //Declare pin number for ButtonT2 as D10
int ButtonT2State = 0;      //Variable for reading ButtonT2 state
//
int count_value1 = 0;       //Variable for storing counter value for turnstile 1
int count_value2 = 0;       //Variable for storing counter value for turnstile 2
//
const byte ROWS = 4;        //Four row matrix
const byte COLS = 4;        //Four columns matrix
char keys [ROWS] [COLS] = { //Defines symbols on buttons of keypad
  {'1','2','3','A'},        //Defines ROW 1
  {'4','5','6','B'},        //Defines ROW 2
  {'7','8','9','C'},        //Defines ROW 3
  {'*','0','#','D'}};       //Defines ROW 4
  byte rowPins[ROWS] = {9, 8, 7, 6};  //Pin numbres of row pinouts of the keypad
  byte colPins[COLS] = {5, 4, 3, 2};  //Pin numbers of column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
//
void setup() { //Begin void setup, code runs once
 Serial.begin(9600);      //Begin serial transmission
 Wire.begin();            //Begin I2C wire communication protocol
 lcd.begin(16,2);         //Begin LCD with 16 columns and 2 rows
//
 pinMode(greenLED, OUTPUT);  //Set greenLED as an OUTPUT
 pinMode(redLED, OUTPUT);    //Set redLED as an OUTPUT
 pinMode(ButtonT1, INPUT);   //Set ButtonT1 as an INPUT
 pinMode(ButtonT2, INPUT);   //Set ButtonT2 as an INPUT
}
//
void loop() {                               //Begin void loop
   char key = keypad.getKey();              //Get a character key from the keypad
//
   //counter 1
    ButtonT1State = digitalRead(ButtonT1);  //Read the state of ButtonT1 -
    if (ButtonT1State == HIGH){             //Begin IF ButtonT1State is HIGH
      count_value1++;                       //IF buttonT1 pressed, increase count value
      Serial.println(count_value1);         //Print count_value1 on serial monitor
      delay(200);                           //Delay for 200ms, 0.2s
      digitalWrite(greenLED,HIGH);          //Set greenLED to HIGH,ON
      digitalWrite(redLED,LOW);             //Set redLED to LOW, OFF
 //
     if (key == '1'){                         //Wait until key '1' is pressed
    }                                         //End IF key == '1'
    ButtonT2State = digitalRead(ButtonT2);   //Read ButtonT2 state
    if (ButtonT2State == HIGH){              //Check if ButtonT2State is == HIGH
      count_value2++;                        //IF buttonT1 pressed, increase count value
      Serial.println(count_value2);          //Print count_value2 on serial monitor
      delay(500);                            //Delay for 500ms, 0.5s
//
    if(key == '2'){                            //Wait untill key '2' is pressed - confirm ride is ready
      Serial.println("Ride starting - 30s");   //Print message in brackets on serial monitor
//30s delay, broken into smaller delays
      delay(10000);
     Serial.println("20s left");
      delay(10000);
      Serial.println("10s left");
      delay(10000);
      Serial.println("Ride finished");        //Print message in brackets on serial monitor
      delay(100);                             //Delay for 1000ms, 1s
    }                                         //End if key == '2'
//
    if (key == '4'){                        //Wait until key '4' is pressed - emergency stop
      Serial.println("Emergency stop");     //Print message in brackets on serial monitor
      digitalWrite(redLED,HIGH);            //Set redLED to HIGH,ON
      digitalWrite(greenLED,LOW);           //Set greenLED to LOW,OFF
      lcd.clear();                          //Clear i2c LCD
      lcd.setCursor(0,0);                   //Set cursor to column 0, row 0
      lcd.print("Emergency stop");          //Print message in brackets on i2c LCD
      count_value2 = 0;                     //Set count_value2 to 0
      delay(1000);                          //Delay for 1000ms, 1s
    }                                       //End IF key == '4'
}

Three words: "Finite State Machine". Don't have any delays. Instead use millis() to decide when to do different actions.

@Majenko How do I use millis() to create a 30s delay without making it in intevals? I want the delay to start once a key on the keypad is pressed. Can I set the value to 0 when i press the key and then do the 30s interval?

Record the time when the button is pressed. Then look at the difference between the current time and that time to find how much time has passed. Like you would when boiling an egg. You don't sit staring at the clock, you look at it once and then glance at it regularly while doing other things until the 5 minutes has passed.

Make a statemachine.
Take a piece of paper and draw out the order of operation and each time you are waiting you specify what each button will do.
So for example each time button 1 is pushed you increment the counter and change the display.
When waiting for a timeout you check if(startTimestamp - millis() > timeout) for the next step.
Then give each waiting state a number and put a big switch on a global at the start of the loop() and update the global each time the state needs to change.


text:
arduino will not save data after receiving from serial communication
I'm new to Arduino and what I'm trying to do is change the variable by sending it from php to the Arduino.
I've added the delay as stated by other questions but it has not worked so far. The pin 13 LED so
Arduino Code
float val;
void setup() {

  Serial.begin(9600);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
  val=29.1;

  Serial.println("Start!");
}

void loop() {

  if(Serial.available()){
    String temp = Serial.readStringUntil('\n'); //read string
    val = temp.toFloat(); //convert string to float
  }

  if(val==62.10){
    digitalWrite(13,HIGH);
  }else{
    digitalWrite(13,LOW);
  }

  Serial.println(val);
  delay(1000);

}

PHP Code
<?php
$port = fopen("COM3", "w");
sleep(2);
fwrite($port, "62.1");
fclose($port);
?>

Any tips would be much appreciated. Thank you for reading.

Comparing floats like that is never a good idea. There's no such thing as 62.1 as a floating point - the closest is 62.09999847412109375. Floats are only ever an approximation.

I see. Luckily for me, the comparison is only used for debugging. @Majenko

You typically use abs(val - 62.1) < 0.05 where 0.05 is the 'accuracy you accept, so values between 62.05 and 62.15 are resulting in true

You are writing "62.1" but you are trying to read up until a \n, which you never send.
You need to ensure that you send the end-of-line character that you subsequently check for,
fwrite($port, "62.1\n");

Also it's worth noting that floating point values are only ever an approximation. They're great for doing calculations, but very poor at doing comparisons. Your test value of 62.1 cannot be represented precisely as a floating point value, the closest being about 62.099. If you do need to do a comparison then you should check it's within a small range, not a precise value.

Your "problem" seems to stem from you opening the serial port with one program, sending a value, then closing the serial port and opening it again in something else and expecting to see that value being echoed back to you.
That can't happen on a stock Arduino UNO. Every time you open the serial port the DTR line toggles the RESET pin to enter the bootloader - which is why you need the 2 second delay after opening the serial port.
In doing so the sketch then runs fresh every time you open the serial port.
There are a number of ways of disabling that reset, from cutting a trace on the Arduino, to adding a large-ish (10µF +) capacitor between RESET and GND - both of which will interfere with your ability to program the board. The capacitor is the easier to reverse.
Ideally you'd use a different serial channel to communicate so it never interferes with the reset or programming. You could use SoftwareSerial and an external USB to UART adaptor instead of the Serial connection, or use a board with a native USB connection that doesn't reset when you open the serial port, such as a Leonardo.

I have added the \n to the fwrite and applied the changes. It seems that Arduino resets and is unable to read the previously sent value.

Every time you open the serial port the Arduino resets, yes. That's what it does. There's plenty of writeups about that functionality and how to avoid it. Mostly they involve hardware changes.


text:
Are there any Arduino libraries that allow you to upload data directly to PostgreSQL?
Are there any Arduino libraries that allow you to upload data directly to PostgreSQL?
I have been turning the internet upside down to answer this question but most of the information is several years old.

The only solution to this question that I could find is a GitHub repository that hasn't been touched in several years called, SimplePgSQL. Feel free to add a better answer if you are able to find something more current. More current information would be useful!
https://github.com/ethanak/SimplePgSQL

Looks like the other alternative is to use a Raspberry Pi to easily upload sensor data to a Postgresql database.


text:
SPI Arduino slave not recieving data correctly
Using an STM32L476RG Nucleo microcontroller board as the SPI master and an Arduino mega as a slave with pin 52 for SCLK, pin 53 for SS and pin 51 for MOSI on the Arduino. There is no issue with the STM32 transmission as the USB logic analyzer I'm using (parallel to the arduino) shows a correct output on the master side so this is an Arduino issue:

The problem is the Arduino isn't recieving properly. The arduino code:
    #include <SPI.h>
#include<stdint.h>
#define SPI_SCK 52
#define SPI_MISO 50
#define SPI_MOSI 51
#define SPI_SS 53
char dataBuff[500];

//Initialize SPI slave.
void SPI_SlaveInit(void)
{
  // Initialize SPI pins.
  pinMode(SCK, INPUT);
  pinMode(MOSI, INPUT);
  pinMode(MISO, OUTPUT);
  pinMode(SS, INPUT);
  //make SPI as slave

  // Enable SPI as slave.
  SPCR = (1 << SPE);
}

//This function returns SPDR Contents
uint8_t SPI_SlaveReceive(void)
{
  /* Wait for reception complete */
  while(!(SPSR & (1<<SPIF)));
  /* Return Data Register */
  return SPDR;
}

//sends one byte of data
void SPI_SlaveTransmit(char data)
{
  /* Start transmission */
  SPDR = data;
  /* Wait for transmission complete */
  while(!(SPSR & (1<<SPIF)));
}

// The setup() function runs right after reset.
void setup()
{
  // Initialize serial communication
  Serial.begin(9600);
  // Initialize SPI Slave.
  SPI_SlaveInit();
  Serial.println("Slave Initialized");
}

// The loop function runs continuously after setup().
void loop()
{
  uint32_t i;
  uint16_t dataLen = 0;
  Serial.println("Slave waiting for ss to go low");
  while(digitalRead(SS));

  i = 0;
  dataLen = SPI_SlaveReceive();
  for(i = 0 ; i < dataLen ; i++ )
  {
    dataBuff[i] =  SPI_SlaveReceive();
  }

  //  Serial.println(String(i,HEX));
  dataBuff[i] = '\0';

  Serial.println("Rcvd:");
  Serial.println(dataBuff);
  Serial.print("Length:");
  Serial.println(dataLen);
}

The message i'm transmitting is my full name and is 12 characters long. The master first sends the length of the message (12 in this case) so the arduino knows how many characters to recieve and then the message is transmitted. On the logic analyzer output everything looks fine and I can see the message. However I keep getting results like this in the Arduino serial monitor:

I should also note I'm using a sparkfun logic level converter between the master and slave to step the STM32 3.3v signal to 5v for the arduino input: (Imagine the arduino is not uno but master in the following image with the pins changed to the ones I've listed above)

I'm seeing no message next to 'Rcvd:' and a length of 0 most of the time, if not than a number much larger than 12. What seems to be the issue?

Your logic analyzer decodes a bunch of NUL bytes between the letters, the first of which would be interpreted by Serial.println() as an end of string. If you want to know what the Arduino receives, you should instead print all the bytes (in hex) in a loop. Also note that receiving in an ISR would be more robust than relying in the received byte count and busy-waiting.

Slave code is quite rare, you can take a look at nick gammon's implementation here: https://forum.arduino.cc/index.php?topic=52111.0 . The thread is quite old, but this is how a slave would be implemented.


text:
UART between arduino UNO and pc via USB not in sync
I connected my arduino uno to my system and then using serial tried writing and reading data but there is a problem which I found when I tried giving arduino crafted messages.
My arduino code is pretty simple.
void setup() {
  Serial.begin(115200);

}

void loop() {
  if (Serial.available() > 0) {
    String data = Serial.readStringUntil('\n');
    Serial.print(" You sent me: ");
    Serial.println(data);
  }
}

and my python code on my system
#!/usr/bin/env python3
import serial
import time

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1)
    ser.flush()

    while True:
        string=input("Enter the string: ")
        ser.write(str.encode(string))
        line = ser.readline().decode('utf-8').rstrip()
        print(line)
        time.sleep(0.01)

Now this gives me ability to write instructions to my arduino but following sequences of communication occur
└──╼ $python3 serial_communication.py
Enter the string: a

Enter the string: v

Enter the string: v
 You sent me: v
Enter the string: s
 You sent me: v
Enter the string: d

Enter the string: r
 You sent me: sd
Enter the string: d
 You sent me: r
Enter the string: s

Enter the string: e
 You sent me: ds
Enter the string: r
 You sent me: e
Enter the string:

Looking at them I understand that this might be a problem with my code or I am using the wrong protocol.

please format your code

Does this answer your question? Python - Arduino communication not reliable

I don't know Python, but from the behavior you show I am willing to bet that the input() function does not preserve the terminating \n.

using the serial monitor solves the issue but still why arduino gives delayed message of redundant data

There's a number of things going on here that combined give you the results you're seeing.
First off there's the delay at the start:
Enter the string: a

Enter the string: v

Enter the string: v
 You sent me: v
Enter the string: s
 You sent me: v

This is because when you first open the serial port the Arduino resets and enters the bootloader. Thus the first few things that get sent are discarded, and nothing is sent back from the Arduino - your sketch just isn't running at that point.
Next is the format of what you're sending compared to how you're receiving it.
You input a string and then send that string verbatim.  But on the Arduino you are reading all data up until a terminating newline character, which you are not sending.
But the reading function also has a timeout in it so it will return whatever it has managed to read in that time even if the terminator hasn't arrived. That timeout is 1 second by default.
So everything that gets sent within a 1 second window gets grouped together, which is what you see here:
Enter the string: d
 You sent me: r
Enter the string: s

Enter the string: e
 You sent me: ds

The "out of sync" appearance is because of that 1 second timeout - you are seeing what was sent a second ago.
The fix is simple enough: make sure that you send the terminating newline character from Python:
ser.write(str.encode(string + "\n"))

And wait a few seconds after starting your program and opening the serial port before asking for anything to be sent. Maybe add a time.sleep(2) after opening the port to enforce that delay.

Thank you for the answer.
This really helps as my target was something else to get to work but as this is the starting point I did not want my concepts to get messed up.


text:
WS2812B Led Digital Panel Matrix Flexible Screen 8*8. Some LEDs that are not supposed to, switch on
My project is composed of an ESP32, a level converter and two WS2812B Led Digital Panel Matrix Flexible Screen 8*8 (from Aliexpress) interconnected with the provided cable. My objective is to show a score, no scrolling or any other animation.
The main functionality works ok, I can display any decimal number between 00 to 99 (one digit in each 8x8 panel).
My problem is that apart from the digits printed, some not so aleatory LEDs switch on, not necessarily on the same color as the intended number, nor on the selected luminosity. Changing the number changes this undesirable pattern that seems to repeat for the same number on the same 8x8 matrix. Problem patters does not follow a specific 8x8 matrix, the problem does not seem to be in the hardware.
The level converter converts the ESP32 3.3v to 5v required by the Matrix but even before I connected the level converter the problem was the same.
The code I am using is as below:
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

// Which pin on the Arduino is connected to the NeoPixels?
#define PIN            14

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      128

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int delayval = 10; // delay for half a second

void setup() {
  pixels.begin(); // This initializes the NeoPixel library.
}

void loop() {

  // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
  pixels.clear();
  pixels.setBrightness(1);

  boolean N0[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,1,1,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,1,1,1,1,0},{0,0,1,1,1,1,0,0}};
  boolean N1[8][8] PROGMEM = {{0,0,0,1,1,0,0,0},{0,0,1,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,1,1,1,1,1,1,0},{0,1,1,1,1,1,1,0}};
  boolean N2[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,0,1,0},{0,1,1,1,1,1,1,0},{0,1,1,1,1,1,1,0}};
  boolean N3[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,1,1,1,0,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
  boolean N4[8][8] PROGMEM = {{0,0,1,1,1,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,1,0,1,1,0},{1,1,0,0,1,1,0,0},{0,1,1,1,1,1,1,1},{0,0,0,0,1,1,0,0},{0,1,1,1,1,0,0,0},{0,0,0,1,1,1,1,0}};
  boolean N5[8][8] PROGMEM = {{0,0,1,1,1,1,1,0},{0,1,1,1,1,1,1,0},{0,0,0,0,0,1,1,0},{0,1,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
  boolean N6[8][8] PROGMEM = {{0,0,1,1,1,0,0,0},{0,0,1,1,0,0,1,0},{0,0,0,0,0,1,1,0},{0,1,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0},{0,0,0,1,1,0,0,0}};
  boolean N7[8][8] PROGMEM = {{0,1,1,1,1,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,0,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,0,1,1,0,0},{0,0,1,1,0,0,0,0},{0,0,0,0,1,1,0,0},{0,0,1,1,0,0,0,0}};
  boolean N8[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
  boolean N9[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,1,0},{0,1,1,0,0,0,0,0},{0,0,0,0,0,1,1,0},{0,1,1,1,0,0,1,0},{0,0,1,1,1,1,0,0}};

  int counter = 0;
  for(int line=0;line<8;line++){
    for(int column=0;column<8;column++){
      if(N2[line][column]==1){
        pixels.setPixelColor(counter, pixels.Color(0,255,0));
        pixels.show();
        delay(delayval);
      }

      if(N1[line][column]==1){
        pixels.setPixelColor(counter+64, pixels.Color(255,33,255));
        pixels.show();
        delay(delayval);
      }

      counter++;
    }
  }
  while(1){};
}

This is a non optimized code for testing purposes only.
What am I doing wrong?

How are you providing power to the LED matrices?

Computer USB. That is why I set brightness to 1 but even if I set it to 10 the problem remains the same, or, the unwanted leds that switch on are the same.

Just to add, say number 5 when printed comes along two LEDs I did not order on. Say I print a green 5. Then I get this blue faint one in a certain position and a bright red one somewhere else. This pattern will repeat no matter what I do, even if I print the 5 on pink for instance, the faint blue and the bright red will be there, even if I change the 8x8 tile.

If instead of 5 I print one other number, foreign LEDs will be different and curiously number one comes out clean. changing brightness from 10 to 1 makes no difference except for the brightness of those I control.

Found the Adafruit NeoPixel is the reason for the problem (or the way it is implemented above is not the best).
Solved with the fastLED library as below:
#include "FastLED.h"
#define NUM_LEDS 128
#define DATA_PIN 14
#define BRIGHTNESS 10
CRGB leds[NUM_LEDS];
int delayval = 10; // delay for half a second

boolean N0[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,1,1,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,1,1,1,1,0},{0,0,1,1,1,1,0,0}};
boolean N1[8][8] PROGMEM = {{0,0,0,1,1,0,0,0},{0,0,1,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,1,1,1,1,1,1,0},{0,1,1,1,1,1,1,0}};
boolean N2[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,0,1,0},{0,1,1,1,1,1,1,0},{0,1,1,1,1,1,1,0}};
boolean N3[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,1,1,1,0,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
boolean N4[8][8] PROGMEM = {{0,0,1,1,1,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,1,0,1,1,0},{1,1,0,0,1,1,0,0},{0,1,1,1,1,1,1,1},{0,0,0,0,1,1,0,0},{0,1,1,1,1,0,0,0},{0,0,0,1,1,1,1,0}};
boolean N5[8][8] PROGMEM = {{0,0,1,1,1,1,1,0},{0,1,1,1,1,1,1,0},{0,0,0,0,0,1,1,0},{0,1,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
boolean N6[8][8] PROGMEM = {{0,0,1,1,1,0,0,0},{0,0,1,1,0,0,1,0},{0,0,0,0,0,1,1,0},{0,1,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0},{0,0,0,1,1,0,0,0}};
boolean N7[8][8] PROGMEM = {{0,1,1,1,1,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,0,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,0,1,1,0,0},{0,0,1,1,0,0,0,0},{0,0,0,0,1,1,0,0},{0,0,1,1,0,0,0,0}};
boolean N8[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
boolean N9[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,1,0},{0,1,1,0,0,0,0,0},{0,0,0,0,0,1,1,0},{0,1,1,1,0,0,1,0},{0,0,1,1,1,1,0,0}};

void setup() {
  FastLED.setBrightness( BRIGHTNESS );
  FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
}

void loop() {
  int counter = 0;
  for(int line=0;line<8;line++){
    for(int column=0;column<8;column++){
      if(N2[line][column]==1){
        leds[counter] = CRGB::Yellow;
        FastLED.show();
        delay(delayval);
      }

      if(N1[line][column]==1){
        leds[counter+64] = CRGB::Green;
        FastLED.show();
        delay(delayval);
      }

      counter++;
    }
  }
  while(1){};
}

Well done finding this out by yourself and for answering your own question ;-) FastLED is a very well developed library.


text:
it just gets too hot . any way of cooling it?
there i just got started with the arduino mega2560 . i tried 8x8 matrix tube and after ~30secs i found the atmega2560 a bit hot that i can melt a small amount wax on it ! is there any sort of heatsink or a better way to use the matrix tube ? what i have done is to turn on a led is to turn on the positive side and turn off the negative side . i just tried that method because in my 1st beginner kit , the manual said this should be done incase of a common anode rgb led .
thanks alot

An Atmega should never get that hot. You are definitely going something wrong. Please provide a schematic or wiring diagram of your project. Are you providing the LEDs with power through the IO ports? Or do you use any kind of driver?

well that is just a phrase . i really don't know if it can melt wax .

Doesn't really matter. An Atmega should never get warm by itself. It doesn't incorporate powerful hardware like the ESP (which geta a bit warm, when using wifi). If it gets warm, you are doing something wrong. For example the outputs are only do provide signal, not power. Each pin can only provide 20mA of current. And as I remember the overall IO current is limited to 100mA. With 8x8=64 LEDs you can easily exceed that

@Raj interesting how different parts of the world have different expressions ... it is you could fry an egg on it here


text:
Arduino unable to wake up using interrupt after sending SMS
my use case is that I am building a distance sensor using Arduino Uno. The idea is when the distance is between a threshold, an SMS is sent from the device.
I am using DS3231, SIM800L, and HCSR04 for my needs.
I want to save power consumption too so I am trying to put my Arduino into a deep sleep and then wake up using RTC interrupt.
The code below works fine when the distance is NOT in the threshold. Meaning Arduino is waking up by the interrupt and then doing what it needs to do. However, if the distance is in between the threshold the SMS is sent and received but after that Arduino never wakes up again. I checked out the SQW pin DS3231, using a multimeter and the signal indeed is going LOW, but Arduino does not wake up again.
Libraries that I am using,
ds3231, Sim800l, NewPing
Here is the code that I am using,
#include <Arduino.h>
#include <avr/sleep.h>
#include <wire.h>
#include <ds3231.h>
#include <NewPing.h>
#include <Sim800L.h>

#define WAKEUP_PIN 2  // when low, makes 328P wake up, must be an interrupt pin (2 or 3 on ATMEGA328P)
#define LED_PIN 13  // output pin for the LED (to show it is awake)

#define TRIGGER_PIN 7
#define ECHO_PIN 6
#define MAX_DISTANCE 200 //max distance we want to measure in cm
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

// DS3231 alarm time
uint8_t wake_HOUR;
uint8_t wake_MINUTE;
uint8_t wake_SECOND;

static boolean goToSleep = false; //to track the when to go to sleep and when to get data and do stuff

#define SIM_MODULE_RX 10
#define SIM_MODULE_TX 11
Sim800L gsmModule(SIM_MODULE_RX, SIM_MODULE_TX);

///* A struct is a structure of logical variables used as a complete unit
// struct ts {
//    uint8_t sec;         /* seconds */
//    uint8_t min;         /* minutes */
//    uint8_t hour;        /* hours */
//    uint8_t mday;        /* day of the month */
//    uint8_t mon;         /* month */
//    int16_t year;        /* year */
//    uint8_t wday;        /* day of the week */
//    uint8_t yday;        /* day in the year */
//    uint8_t isdst;       /* daylight saving time */
//    uint8_t year_s;      /* year in short notation*/
//#ifdef CONFIG_UNIXTIME
//    uint32_t unixtime;   /* seconds since 01.01.1970 00:00:00 UTC*/
//#endif
//};
struct ts t;

// When WAKEUP_PIN is brought LOW this interrupt is triggered FIRST (even in PWR_DOWN sleep)
void sleepISR()
{
    // Prevent sleep mode, so we don't enter it again, except deliberately, by code
    sleep_disable();

    // Detach the interrupt that brought us out of sleep
    detachInterrupt(digitalPinToInterrupt(WAKEUP_PIN));

    // Now we continue running the main Loop() just after we went to sleep
}

// Double blink just to show we are running. Note that we do NOT
// use the delay for the final delay here, this is done by checking
// millis instead (non-blocking)
void doBlink()
{
    static unsigned long lastMillis = 0;

    if (millis() > lastMillis + 1000)
    {
        digitalWrite(LED_PIN, HIGH);
        delay(10);
        digitalWrite(LED_PIN, LOW);
        delay(200);
        digitalWrite(LED_PIN, HIGH);
        delay(10);
        digitalWrite(LED_PIN, LOW);
        lastMillis = millis();
    }
}

// Set the next alarm
void setNextAlarm(void)
{
    // flags define what calendar component to be checked against the current time in order
    // to trigger the alarm - see datasheet
    // A1M1 (seconds) (0 to enable, 1 to disable)
    // A1M2 (minutes) (0 to enable, 1 to disable)
    // A1M3 (hour)    (0 to enable, 1 to disable)
    // A1M4 (day)     (0 to enable, 1 to disable)
    // DY/DT          (dayofweek == 1/dayofmonth == 0)
    uint8_t flags[5] = {0, 0, 0, 1, 1};

    // get current time so we can calc the next alarm
    DS3231_get(&t);

    wake_SECOND = t.sec;
    wake_MINUTE = t.min;
    wake_HOUR = t.hour;

    // Add a some seconds to current time. If overflow increment minutes etc.
    wake_SECOND = wake_SECOND + 10;
    if (wake_SECOND > 59)
    {
        wake_MINUTE++;
        wake_SECOND = wake_SECOND - 60;

        if (wake_MINUTE > 59)
        {
            wake_HOUR++;
            wake_MINUTE -= 60;
        }
    }

    // Set the alarm time (but not yet activated)
    DS3231_set_a1(wake_SECOND, wake_MINUTE, wake_HOUR, 0, flags);

    // Turn the alarm on
    DS3231_set_creg(DS3231_CONTROL_INTCN | DS3231_CONTROL_A1IE);
}

void getDistance(){

    // Send ping, get distance in cm
    float distance = sonar.ping_cm();

    // Send results to Serial Monitor
    Serial.print("Distance = ");

    Serial.print(distance);
    Serial.println(" cm");
    delay(500);

    if (distance < 10.00)
    {
        //Setup Sim800 for sms sending
        gsmModule.begin(9600);
        bool err = gsmModule.sendSms("+91790xxxxxxx", "CLose");
        Serial.println(err);
        gsmModule.end();
        delay(3000);
    }

    //sleep arduino after the above operation
    goToSleep = true;
}

// Standard setup( ) function
void setup()
{
    Serial.begin(9600);

    // Keep pins high until we ground them
    pinMode(WAKEUP_PIN, INPUT_PULLUP);

    // Flashing LED just to show the µController is running
    digitalWrite(LED_PIN, LOW);
    pinMode(LED_PIN, OUTPUT);

    // Clear the current alarm (puts DS3231 INT high)
    Wire.begin();
    DS3231_init(DS3231_CONTROL_INTCN);
    DS3231_clear_a1f();

    Serial.println("Setup completed.");
}

// The loop blinks an LED when not in sleep mode
void loop()
{

    // Just blink LED twice to show we're running
    doBlink();

    // Is the "go to sleep" pin now LOW?
    if (goToSleep == true)
    {
        // Set the DS3231 alarm to wake up in X seconds
        setNextAlarm();

        // Disable the ADC (Analog to digital converter, pins A0 [14] to A5 [19])
        static byte prevADCSRA = ADCSRA;
        ADCSRA = 0;

        /* Set the type of sleep mode we want. Can be one of (in order of power saving):
         SLEEP_MODE_IDLE (Timer 0 will wake up every millisecond to keep millis running)
         SLEEP_MODE_ADC
         SLEEP_MODE_PWR_SAVE (TIMER 2 keeps running)
         SLEEP_MODE_EXT_STANDBY
         SLEEP_MODE_STANDBY (Oscillator keeps running, makes for faster wake-up)
         SLEEP_MODE_PWR_DOWN (Deep sleep)
         */
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_enable();

        // Turn of Brown Out Detection (low voltage)
        // Thanks to Nick Gammon for how to do this (temporarily) in software rather than
        // permanently using an avrdude command line.
        //
        // Note: Microchip state: BODS and BODSE only available for picoPower devices ATmega48PA/88PA/168PA/328P
        //
        // BODS must be set to one and BODSE must be set to zero within four clock cycles. This sets
        // the MCU Control Register (MCUCR)
        MCUCR = bit(BODS) | bit(BODSE);

        // The BODS bit is automatically cleared after three clock cycles so we better get on with it
        MCUCR = bit(BODS);

        // Ensure we can wake up again by first disabling interupts (temporarily) so
        // the wakeISR does not run before we are asleep and then prevent interrupts,
        // and then defining the ISR (Interrupt Service Routine) to run when poked awake
        noInterrupts();
        attachInterrupt(digitalPinToInterrupt(WAKEUP_PIN), sleepISR, LOW);

        // Send a message just to show we are about to sleep
        Serial.println("Deep Sleep");
        Serial.flush();

        // Allow interrupts now
        interrupts();

        // And enter sleep mode as set above
        sleep_cpu();

        // --------------------------------------------------------
        // µController is now asleep until woken up by an interrupt
        // --------------------------------------------------------

        // Wakes up at this point when WAKEUP_PIN is brought LOW - interrupt routine is run first
        Serial.println("Awake");

        // Clear existing alarm so int pin goes high again
        DS3231_clear_a1f();

        // Re-enable ADC if it was previously running
        ADCSRA = prevADCSRA;

        goToSleep = false; //reset so that arduino does what it needs to do

    }
    else
    {

        //check if distance is less
        Serial.println("Checking");
        getDistance();
    }
}

I would first remove all that just-for-sure code like the interrupt handler, repeated attach and detach, interrupts disabling,  BOD

@Juraj  Not sure how that would help cause the moment I remove the if (distance < 10.00) block everything works as expected. (Arduino wakes up every 10 seconds, gets the distance and sleeps, the cycle continues)


text:
Updating mysql data using SIM900 and Arduino
Thanks in advance for your kind support.
I am not an expert but have little understanding of concepts and trying to integrate various things to get some useful projects for my purpose. I want to update the database (MySQL) on shared hosting using the SIM900A module and Arduino nano board. With help of examples shared on this platform and my understanding, I achieved a significant part of the same.  The following is the approach I have adopted and the current status:
I have put a PHP code on the server (shared hosting) to update the database once it received the GET request
I have also uploaded the code in the Arduino with proper connections for sending requests to the server.
Problems I am facing:
I am not able to update the data on my specific database, through the Arduino sent request. the same code is working with Thingspeak, My code is also working otherwise, as I have tested through web form request and URL request. I am not sure where is the problem.  I am also not getting any errors. The response to the AT request is "OK" only
Though I can update the Thingspeak channel, only till the command lesser than 61 characters, which are sent after the AT+CIPSEND command. There is no error, even if the request size increases, but data updated only till 61 characters (including \x1A character)
"I am wondering, is this the limit, that cannot be increased or there is some possibility to increase it."
I understand that the problem appears to be in approach and not in code, as the code is working in itself. However, please let me know, which code I need to share, as it is a multifile code on the web-editor

I have faced a similar issue. It happened due to an SSL issue. You can find all info about it here - https://stackoverflow.com/questions/62950561/sim800l-gsm-module-working-with-http-and-shows-error-with-https-why


text:
Getting a Wemos D1 Mini to work with a M1 Mac
The Wemos D1 mini won't show up on the new M1 Mac. I know it's related to the drivers but I just can't find a viable solution to the problem. Has anyone solved this?

The CH340s have always been a problem with macs even before the M1. You could use a better USB UART interface instead of the built-in CH340, although I am not sure what makes actually support the M1. Maybe FT232 or PL210x would be a good bet.

program it on a different computer, and include OTA so you can update it from the mac.

I just found a solution for my TTGO board which also uses the CH340 chip, perhaps it'll work for you as well https://arduino.stackexchange.com/a/85824/53182


text:
ESP32 millis not working properly
I have a program which measures temperatures every 30 minutes and sends them to a database. Immediately after running the program the first measurement is sent, however, the second (which should be sent after 30 min), is sent only after 1 hour. From then on the code works fine. The time is measured in millis. However, if I set the time difference to 28 minutes everything works fine from the beginning. What could be the reason for this? Is there a possibility that it goes to sleep mode? I don't understand why it works fine with 28 minutes and it stops working with 29 minutes?
Thanks in advance!
My code:
if (millis() - sendDataPrevMillis > 1740000)
  {
    sendDataPrevMillis = millis();

//other code

}

The only part I change, so it works is setting millis from 1740000 (29 minutes) to 1680000 (28 minutes).

Share your code with us.

Please provide a minimal compilable example code, that shows your problem, not just a super small code snippet

use unsigned long as data type of sendDataPrevMillis

Did you make sure that millis() returns 0 at startup? For debugging you could print the initial value and any following if the condition is met.

Although not strictly required, maybe use parentheses around millis() - sendDataPrevMillis for readability;
I guess you will have initialised sendDataPrevMillis to 0 but
the first time you assign sendDataPrevMillis to millis() some time will have elapsed since you evaluated. So calling millis() twice will give different results. That makes it less easy to see what is going on.

Suggestion to try:
long HALFHOUR = 30 * 60 * 1000L;

if ( (millis() % HALFHOUR ) == 0L ) {
    //measure and send
    //....
}

Hope this helps.
NB: % is what is called the 'modulo operator' see: https://www.geeksforgeeks.org/modulo-operator-in-c-cpp-with-examples/

I don't quite understand, what you mean with your second point. Calling millis() multiple times will give different results, when between the calls at least one millisecond passed. When initializing sendDataPrevMillis to zero, the time will be counted from startup (power cycle or reset). It is not very probable, that the code has run over half an hour before reaching the if statement the first time. So why should that matter?

The prob. of that will of course be very small indeed. what I was trying to say was about style: when the condition of the loop refers to the actual progressed millis (the first call) I would suggest to store exactly that value. Assignment within the condition
if ( (currentMillis = millis()) - sendDataPrevMillis > 1740000) {
sendDataPrevMillis = currentMillis;
in order to prevent that becomes a bit messy, don't you think?

You can do that with the assigment in if condition, but I don't think that this is better readable. Though that is subjective. In your second point you don't talk about style. As I now understand you say, that the millis() calls in the if condition and in the following inner statement give different results. I don't think that. The code runs way too fast for  that. Even if the code happens to accidentally hit the exact point, where millis() increments, that will mean a max error of 1ms. Not important, when in this time range and also when you are using millis().

what are the odds of hitting that at the exact ms out of thousands?

This has too much potential to go wrong in a real time environment and isn't better code than the one in the question. Besides, timers that depend  on millis() should always be unsigned long (or uint32_t).


text:
ESP32 ROS unable to sync
I am trying the example ros arduino publisher using an ESP32 Dev Module.
When I try to connect using rosserial I get "Uable to sync" error.
I have tried using different baud rates, 115200, 57600 and 9600
None of them worked. I clicked on the serial port monitor of the arduino IDE by mistake and saw this message:
Rebooting...
ets Jul 29 2019 12:21:46

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1100
load:0x40078000,len:9232
load:0x40080400,len:6400
entry 0x400806a8

Not sure what to make out of the above error.
What am I doing wrong?
Thanks in advance.

That's not an error. That's just the normal boot sequence.

This message keeps on repeating itself. Does this mean it keeps on rebooting?

Sounds like it, yes. It's a software reboot, so some code is telling it to reboot.

It's a standard code, what can go wrong with that?


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

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

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

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

What kind of ADC resolution are you aiming at?

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

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


text:
Get a specific item from comma separated text
I use bluetooth (works like serial monitor).
Let me say i send a text to my hc-05 (same as sending to serial monitor)
My current code is displaying text from serial monitor/HC-05 TO LCD
#include <LiquidCrystal.h>

LiquidCrystal lcd(4, 6, 10, 11, 12, 13);
String readString;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop() {
  while(Serial.available()){
    delay(50);
    char c=Serial.read();
    readString+=c;
  }
  if(readString.length()>0){
    Serial.println(readString);
      lcd.clear();
      lcd.print(readString);
    readString="";
  }
}

from serial monitor i type `a,b,c,d`

now my goal is to just get the a and display in lcd

or

in other words i want to get the value of a b c d in the text that is CSV to list or array and get value for index 1,2,3,4

OR

split string by delimiter

so how can i do it
details-ARUINO UNO

i searched in stack exchange Arduino but i dint get answer so i posted but when i searched in stack over flow i got link this is my final code
String part01;
String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }

  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

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

void loop()
{
  String part01 = getValue("523;524;525",';',1);
  Serial.println(part01);

}

Use the strtok function.
From Geeks for geeks (https://www.geeksforgeeks.org/strtok-strtok_r-functions-c-examples/):
arguments:

str: The string which is to be split
delim: The character on the basis of which the split will be done Return value

The function performs one split and returns a pointer to the token split up. A null pointer is returned if the string cannot be split.

Note that to use strtok() you would first have to migrate away from using String, which is a good thing in any case.

but the example is for c++ can you provide the example for Arduino

@hifitech Even though the Arduino/C++ string can be used, it's not a good idea because of the very low SRAM the Arduino Uno has. I assume with a default function and plenty of examples to be found on internet of using strtok it would not be a big problem to find a solution.