# Question
Title: Can someone help me figure out why my menu gets stuck?
When I try to run my code so far with the menu and select buttons, it seems that it works, except that the main menu will not move past "Main Garden" to "Currants". There's also a problem with the submenu where after the first watering warning, pressing the select button makes it simply return to the main menu without lighting the LED on the LEDPower pin or running that watering routing for the whole watering interval.

The one guess I still haven't tried is that maybe I should change void MainMenu() to a Switch Case structure instead of If-Else?

.

edit:

```
.

```

# Answer
> 1 votes
Problem One (Menu not moving past `Main Garden` to `Currants`):

`MainOld` is used to increment `MenuState` but `MainOld` never gets incremented, which means it will never have a value greater than 0. Accordingly `MenuState` can never be greater than 0 + 1.

Problem Two (Sub Menu looping back to main):

'Checking' the state of `LEDPower` like in `Water1()` is not the best way to accomplish what you want to accomplish. It *may* work but is not technically correct as `LEDPower` is a pin state and you never actually read the state.

The other issue in `Water1` is that `previousWaterMillis` doesn't get updated anywhere in your code, which means that anytime `Water1` is called more than 10 seconds after boot your solenoid will activate and then immediately deactivate. I would recommend a `while` loop inside your `Water1` function. ex.

```
void Water1(){
  digitalWrite(Relay1, HIGH);
  unsigned long currentMillis = millis();
  previousWaterMillis = millis();
  int LEDPowerState = digitalRead(LEDPower);

  while(currentMillis - previousWaterMillis <= WateringInterval){
    digitalWrite(LEDPower, HIGH);
    Serial.println("Watering Garden with LED Lit");
    currentMillis = millis();
  }

  digitalWrite(Relay1, LOW);
  digitalWrite(LEDPower, LOW);
  SubMenuState = 0;
  SubMenuOld = 0;
}

^^ This will illuminate your LED and activate the solenoid for the 10 secs you wish to water.

```

---
Tags: arduino-uno
---


title: Non-blocking SoftwareSerial.Write

text:
# Question
Title: Non-blocking SoftwareSerial.Write
How to use `SoftwareSerial.Write` without blocking if buffer is full? `Serial.write` blocks if the buffer is full. So I need to check `Serial.availableforwrite` before calling write to prevent blocking. But there is no `SoftwareSerial.availableforwrite`. How can I use `SoftwareSerial.Write` without blocking?

# Answer
> 9 votes
In short, you don't.

The SoftwareSerial implementation for AVR doesn't have an outbound buffer at all.
It just turns the interrupts off during each character outbound and it sends them all immediately.

This means a call to SoftwareSerial's write simply **will** block until all of the data you've tried to send has in fact been sent. If you can't afford to wait for your data to go out on the TX line *now*, then it's up to you to send it later when you *can* afford to wait.

SoftwareSerial has no flow control. When you write(), the data is sent out on the TX pin regardless of whether anything is present on the other side of the connection. And when present, the data is still transmitted regardless of whether other side considers itself "ready" to receive. There's simply no feedback from the receiver to tell the sender to stop. So SoftwareSerial itself will never block owing to these things.

---
Tags: arduino-uno, serial, softwareserial
---


# Question
Title: Where is the positive and negative holes on the arduino mini breadboard?
I have the mini arduino breadboard. The pins go from A to J and 1 to 17. On the larger breadboard, there are symbols + and -. My breadboard doesn't have those two sections to put wires in. Does anyone know what to do?

# Answer
> Does anyone know what to do?

Do whatever you want to do.

There's nothing special about the +/- rails of a breadboard - they're just chunks of metal that go along instead of across, and are longer, with more holes, and someone has helpfully coloured them red/blue and added some symbols.

If you want a common place for + and - then just choose a common place for + and -.
> 6 votes

---
Tags: arduino-uno, breadboard
---


title: Adafruit_Arcada' does not name a type;

text:
# Question
Title: Adafruit_Arcada' does not name a type;
I am trying to program an adafruit pygamer (which says it's compatible with Arduino). I have added the ZIP folder for the library into the library folder om my PC where all of my folders are supposed to be stored, one thing I managed to find out for a start was that the library folder for the library itself that was installed from GitHub contained a dash in the filename so I replaced that for an underscore. The actual error message that seems to come up now is this:

```
'Adafruit_Arcada' does not name a type; did you mean 'Adafruit_SPITFT'?

```

This error comes up from when I try to use the:

```
#include "Adafruit_Arcada.h"

Adafruit_Arcada arcada;

```

lines

Within the library folder that I want to try and use there are the code examples within the library folder inside the examples sub-folder

I have tried following a step by step guide into one potential way of trying to solve this problem by looking at a tutorial by adafruit on how to step by step install zip folder libraries. Something tells me though that this error that I am getting is to do with one of the .h or .cpp files within the library itself.

The link for the library itself is here: https://github.com/adafruit/Adafruit\_Arcada

In addition, when I look in the `Adafruit_Arcada.h` file I can actually see that there is no `Adafruit_Arcada` class but there is an `Adafruit_SPITFT` one. I know this point might seem like a bit of a no-brainer but I just thought it would be useful to try and find out what could potentially be going on and provide evidence of what I have already tried to do.

When I changed the `Adafruit_Arcada arcada;` to `Adafruit_SPITFT arcada;` (thinking this could potentially resolve the issue because within the `Adafruit_Arcada.h` file there is a class called `Adafruit_SPITFT and not`Adafruit\_Arcada\`), this brought up another error which was the following:

```
simpletest:2:17: error: no matching function for call to 'Adafruit_SPITFT::Adafruit_SPITFT()'

```

# Answer
There are some instructions at:

Pygamer setup

That need to be followed in order to permit the Arduino IDE to work with the Pygamer. It's not clear that you have followed any or all of these instructions.

I recommend that you carefully follow ALL the steps and then start with the simple example to test that you are building and uploading properly.

Then move on to the Adafruit example that uses the Arcada library.
> 1 votes

---
Tags: library, adafruit
---


# Question
Title: Read Simultaneously RFID TAG with multiple RFID Reader [MFRC522]
i have a project that use two RFID Reader, the project for counting tag from conveyor belt, in this case the reader will placed in the middle of the conveyor belt and the reader faces each other.

So i have question, can two RFID Reader reading one or many tag simultaneously? I tried before but when i tried to scan, the two readers did not respond, but if i scan one tag and one reader it will work correctly.

For example: i have readers 0 and readers 1, and two variables count0 and count1, remember the readers faces each others, so i put one tag in the middle of reader0 and reader1, if the reader 0 scan the tag, count0 will increase to 1 and if reader 1 scan the tag in the SAME TIME it wouldn’t be counting because the reader 0 has scan that tag.

but in my case, the readers(0 and 1) didnt response if i put the tag in the middle of readers.

i use this tutorial for my project https://youtu.be/HmGmFknAIqc

and for this project the data count0 and count1 i send it to nodemcu using SoftwareSerial(5,6).

Im new for using Arduino and i still learn about it(i dont understand too much)

Heres my arduino code

```
/**
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from more than one PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 *
 * Example sketch/program showing how to read data from more than one PICC (that is: a RFID Tag or Card) using a
 * MFRC522 based RFID Reader on the Arduino SPI interface.
 *
 * Warning: This may not work! Multiple devices at one SPI are difficult and cause many trouble!! Engineering skill
 *          and knowledge are required!
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS 1    SDA(SS)      ** custom, take a unused pin, only HIGH/LOW required **
 * SPI SS 2    SDA(SS)      ** custom, take a unused pin, only HIGH/LOW required **
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 */
#include <Wire.h>
#include <SPI.h>
#include <MFRC522.h>
#include <SoftwareSerial.h>
#include <LiquidCrystal_I2C.h> //library penampil LCD

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_1_PIN        10         // Configurable, take a unused pin, only HIGH/LOW required, must be diffrent to SS 2
#define SS_2_PIN        8          // Configurable, take a unused pin, only HIGH/LOW required, must be diffrent to SS 1

#define NR_OF_READERS   2

LiquidCrystal_I2C lcd(0x27,20,4); //0x3f dapat dicari dengan i2c scanner
SoftwareSerial s(5,6);
//SoftwareSerial s1(2,3);

byte ssPins[] = {SS_1_PIN, SS_2_PIN};

MFRC522 mfrc522[NR_OF_READERS];   // Create MFRC522 instance.
int i = 1;
byte code[10];
String uidString;
int count0 = 0;
int count1 = 0;

/**
 * Initialize.
 */
void setup() {
  s.begin(9600);
 // s1.begin(9600);
  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial);
  SPI.begin();        // Init SPI bus

  for (uint8_t reader = 0; reader < NR_OF_READERS; reader++) {
    mfrc522[reader].PCD_Init(ssPins[reader], RST_PIN); // Init each MFRC522 card
    Serial.print(F("Reader "));
    Serial.print(reader);
    Serial.print(F(": "));
    mfrc522[reader].PCD_DumpVersionToSerial();
  }

//  lcd.init();
//  lcd.init();
//  lcd.backlight(); //menghidupkan lampu latar LCD
//  lcd.setCursor (3,0);
//  lcd.print("Final Project");
//  delay (1000);
//  lcd.clear();
}

/**
 * Main loop.
 */
void loop() {
//  lcd.setCursor (0,0);
//  lcd.print("SCAN RFID");

  for (uint8_t reader = 0; reader < NR_OF_READERS; reader++) {
    // Look for new cards
    if(reader == 0){
      reader0(reader);
    }else if(reader == 1){
      reader1(reader);
    }
  }
}

/** SCAN RFID TAG READER0 */
void reader0(int reader){
    if (mfrc522[reader].PICC_IsNewCardPresent() && mfrc522[reader].PICC_ReadCardSerial()) {
      Serial.println();
      Serial.print(F("Reader "));
      Serial.print(reader);
      // Show some details of the PICC (that is: the tag/card)
      Serial.println();
      Serial.print(F("Card UID = "));
      dump_byte_array(mfrc522[reader].uid.uidByte, mfrc522[reader].uid.size);
      Serial.println();
//      Serial.print(F("PICC type: "));
//      MFRC522::PICC_Type piccType = mfrc522[reader].PICC_GetType(mfrc522[reader].uid.sak);
//      Serial.println(mfrc522[reader].PICC_GetTypeName(piccType));
      count0++;
      lcd.setCursor (0,0);

      Serial.print("Counter ");
      Serial.print(reader);
      Serial.print(" = ");
      Serial.print(count0);
      Serial.println();
      s.write(count0);
       }

      mfrc522[reader].PICC_HaltA();
      mfrc522[reader].PCD_StopCrypto1();
}

/** SCAN RFID TAG READER1 */
void reader1(int reader){
    if (mfrc522[reader].PICC_IsNewCardPresent() && mfrc522[reader].PICC_ReadCardSerial()) {
      Serial.println();
      Serial.print(F("Reader "));
      Serial.print(reader);
      Serial.println();
      // Show some details of the PICC (that is: the tag/card)
      Serial.print(F("Card UID = "));
      dump_byte_array(mfrc522[reader].uid.uidByte, mfrc522[reader].uid.size);
      Serial.println();
//      Serial.print(F("PICC type: "));
//      MFRC522::PICC_Type piccType = mfrc522[reader].PICC_GetType(mfrc522[reader].uid.sak);
//      Serial.println(mfrc522[reader].PICC_GetTypeName(piccType));
      count1++;
      lcd.setCursor (0,0);

      Serial.print("Counter ");
      Serial.print(reader);
      Serial.print(" = ");
      Serial.print(count1);
      Serial.println();
      s.write(count1);
    }

      mfrc522[reader].PICC_HaltA();
      // Stop encryption on PCD
      mfrc522[reader].PCD_StopCrypto1();
}

/**
 * Helper routine to dump a byte array as hex values to Serial.
 */
void dump_byte_array(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

```

anyway sorry for my bad english :D

# Answer
> 1 votes
Take a look at this this link it might be of a help to you. It uses four RFID readers at the same time

# Answer
> 1 votes
I'm just starting a project using RFID tags to track cars and engines on a model railroad. Although I haven't gotten very far yet, my first thought was to use a multiplexer to select which reader I receive data from at any given time. It won't be simultaneous but I should be able to read a dozen or more per second which is probably enough.

# Answer
> 0 votes
That's because you can only listen at one `SoftwareSerial` interface at a time. On the other interface you will receive nothing.

The `SoftwareSerial` library uses interrupts to watch at the pins. These interrupts cannot easily be shared between different interfaces, thus the `SoftwareSerial` library doesn't support it.

You can do 2 things:

* You could ditch the code for reporting to the serial monitor (so no debugging code and no interaction with the serial monitor on the PC) and only use the LCD for displaying information. Then you can use the free hardware serial port to communicate with one of the RFID readers. The other can be services through a single `SoftwareSerial` interface.
* You could ditch the Uno and buy an Arduino Mega, which has 4 hardware serial ports. Then you can connect both RFID readers to hardware serial interfaces, using the first serial interface for communication with the PC and still having one interface left. This would be my preferred way.

# Answer
> -1 votes
mfrc522 is not as common any more, but if you want to use them rather then rdm6300 (more expensive device, but cheaper tags), then you can
Mfrc522 uses spi interface which means that each slave needs its own slave select port from arduino to enable arduino to chose whom its talking to at which point. You should read this about multiple SPI devices because SPI is a synchronous communication I would recommend one mcu per reader (nanos' or pro-minis are cheap) and they can communicate results to central arduino

---
Tags: arduino-uno, rfid
---


# Question
Title: How much voltage and amps for 2 SG90 servos?
Question is pretty straight forward: How much amps and voltage do I need for 2 SG90 servos? I want to use 4 but you might already know that Arduino Uno only has 2 5V ports.

# Answer
> 1 votes
The SG90 servo datasheet is here:

SG90 Servo Datasheet

As you can see, the voltage specification is 4.8 - 6.0 Volts. But you do NOT want to power this or any other servo via the Arduino. Servos are quite "noisy" electrically and this can cause instabilities with your Uno.

You want to supply power to the servo directly from a +5V power supply.

I don't see the current draw for this servo specified so you will need to do your own measurements based on the loading of the output shaft. Be aware that these draw more current with increased load on the shaft.

As far as the control signal, the Arduino Uno can certainly drive it via its PWM outputs.

---
Tags: arduino-uno, servo, voltage-level
---


# Question
Title: To update GPS after every 30seconds using NeoGPS and NeoSWSerial Libray
I am using Adafruit Ulitimate Breakout GPS module and NeoGPS and NeoSWSerial Library. Now I want the GPS to update in 30seconds once (1time in 30seconds).After it is updated I want to check the location if new location is equal to old location then it should be updated in 60seconds once(1time in 60seconds).If not the location should be new location. It should display the location every 60seconds. I tried this flow on Adafruit GPS Library, which works but I want to use NeoGPS library and do the same. Below is my adafruit library code:

```
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(11, 10);
Adafruit_GPS GPS(&mySerial);

#define GPSECHO  true
uint32_t timer = millis();
float old_lat,old_lon,new_lat,new_lon;

void setup()
{

  Serial.begin(9600);
  delay(1000);
  Serial.println("Adafruit GPS library basic test!");
  GPS.begin(9600);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand("$PMTK220,30000*1F");
  mySerial.println(PMTK_Q_RELEASE);
}

void loop()                     // run over and over again
{
  char c = GPS.read();
  if (GPS.newNMEAreceived()) {
    //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived() flag to false
    if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
  }

if (GPS.fix) {

      old_lat = GPS.latitudeDegrees;
      old_lon = GPS.longitudeDegrees;
      if (timer > millis())  timer = millis();
      if (millis() - timer > 60000) {
        timer = millis();
          Serial.println("Location 1 minute:");
          displaytime();
          new_lat = GPS.latitudeDegrees;
          new_lon = GPS.longitudeDegrees;

          if (new_lat == old_lat){
            new_lat = old_lat;
          }
          else{
            new_lat = GPS.latitudeDegrees;
          }
          Serial.print("Final Latitude: ");
          Serial.println(new_lat,6);

          if (new_lon == old_lon){
            new_lon = old_lon;
          }
          else{
            new_lon = GPS.longitudeDegrees;
          }
          Serial.print("Final Longitude: ");
          Serial.println(new_lon,6);

}
}
}

void displaytime(){
    Serial.print("\nTime: ");
    if (GPS.hour < 10) { Serial.print('0'); }
    Serial.print(GPS.hour, DEC); Serial.print(':');
    if (GPS.minute < 10) { Serial.print('0'); }
    Serial.print(GPS.minute, DEC); Serial.print(':');
    if (GPS.seconds < 10) { Serial.print('0'); }
    Serial.print(GPS.seconds, DEC); Serial.print('.');
    if (GPS.milliseconds < 10) {
      Serial.print("00");
    } else if (GPS.milliseconds > 9 && GPS.milliseconds < 100) {
      Serial.print("0");
    }
    Serial.println(GPS.milliseconds);
}

```

This is my NeoGPS Library code in which I am using NeoSWSerial:

```
#include <NMEAGPS.h>
#include <NeoSWSerial.h>// import the serial library

NeoSWSerial gpsPort(11, 10); // RX is 11 (to GPS tx), TX is 10 (to GPS rx)
NMEAGPS gps; // the parser
gps_fix fix; // the struct with all the parsed values

void setup() {

  gpsPort.begin(9600);
  Serial.begin(9600);
  Serial.println("GPS Start");
}

void loop() {

  if (gps.available( gpsPort)) {
      fix = gps.read();
      Serial.println("Latitude:");
      Serial.println( fix.latitude(), 6);
      Serial.println("Longitude:");
      Serial.println( fix.longitude(), 6);

    }
 }

```

# Answer
It seems like using the distance feature in NeoGPS would be a good solution for this problem and it should allow you to create a buffer around the original location to filter some of the noise from the GPS readings.

Here's a page with an overview of using Distance in NeoGPS https://github.com/SlashDevin/NeoGPS/blob/master/examples/NMEAdistance/NMEAdistance.ino
> 1 votes

---
Tags: arduino-ide, arduino-nano, gps
---


title: SIM800L LED is not blinking

text:
# Question
Title: SIM800L LED is not blinking
I am using a SIM800L Module with esp32. I am using a 3.7V 2800mAh lipo battery to power the sim800L but the LED is not blinking. I am lookng for answers in web but evryone seems to have a different problem than mine. In other case the sim800l is at least blinkng or blinked once. I have tested the led with multimeter and it glows so hopefully the board is okay. Is the power supplied by the battery is not sufficient? I followed this tutorial

I am sure about the sim card as it is a working sim card in INDIA (of IDEA) and works fine in my smart phone.

# Answer
> 1 votes
So I Finally sort out the problem. Both Battery and Module was completely fine. The problem was with the connecting wires. The connecting wires for some reason was not capable to hold the 2amp current. As a solution what I did was, cut the legs of some quarter watt resistance and solder them to the wire exiting from the battery and fed them directly to the vcc and ground of the module. This way it works perfectly fine.

Even it seems a weird problem with no proper explanation but this solution works for me.

-----------Editing for a better explanation-------------

So my problem was with the connecting wires. For some reason the wires I primarily used could not deliver the the current from battery terminals to the module. May be those wires had a higher resistance for which the current flowing through those could not stay at 2 ampere magnitude and by the time it traveerses the wires and reached to the module, it was no longer at 2 ampere and might be lesser than a certain value which could not trigger the module and so the module did not work.

what I did was cut some legs of a few quatter watt resistance (the metal leads getting out from the carbon resistance from both sides:pic added) and sholder them to the battery terminals. Since I knew the metal legs of quatter watt resistances had a very less resistance from my course that trick worked and delivered 2amp current through them to the module.

I am trully sorry for not attaching picture as I have already submitted the project and currently have no way to replicate the situation.

# Answer
> 1 votes
Can you please explain this part again? if possible,upload image!

As a solution what I did was, cut the legs of some quarter watt resistance and solder them to the wire exiting from the battery and fed them directly to the vcc and ground of the module. This way it works perfectly fine

---
Tags: gsm, esp32
---


title: strcmp doesn't seem to work

text:
# Question
Title: strcmp doesn't seem to work
I'm trying to compare a char array that I'm assembling to a string and I'm having trouble comparing the strings.

I'm getting the data for the char array as a set of bytes and I'm compiling it into a char array like this:

```
void messageHandler(char *topic, byte *payload, unsigned int length)
{
  char buffer[length];
  for (int i = 0; i < length; i++)
  {
    buffer[i] = (char)payload[i];
  }

```

So grabbing each of the ASCII codes and converting it into a character as I add it to the buffer.

After I do that I'm trying to print the buffer to the monitor and then compare it to a string. Though it's not working:

I know I'm getting all of those extra characters in the println b/c the buffer doesn't end in `0` so print keeps reading out memory bytes till it hits the zero, but I don't know why `strcmp` isn't showing the buffer matching the string `"ravenclaw"`.

I'm sure it's for the same "missing the null terminator" issue, but I'm not sure how to fix it. Help is appreciated!!

# Answer
You seem to already understand that it's not null-terminated and that's why it's not working the way you expect. So, I'll take a different tact for "how to fix it".

You can simply not treat the payload as a string, and instead use `memcmp`, as in:

```
if (length == 9 && memcmp(payload, "ravenclaw", 9) == 0) {

```

`memcmp` behaves similarly to `strcmp`, except that it isn't looking for a null terminator. It just compares however many bytes (chars) you specify. In practice you may want to use a variable to hold "ravenclaw" and to strlen() on it rather than specifying the length separately as I've done above, e.g.:

```
static const char ravenclaw[] = "ravenclaw";
static const size_t ravenclaw_len = sizeof ravenclaw - 1;
if (length == ravenclaw_len && memcmp(payload, ravenclaw, ravenclaw_len) == 0) {

```

or any number of variations on that which might use `strlen()`, or a pointer rather than array (if not using `sizeof`) or `PROGMEM` with `strlen_P()` and `memcmp_P()` or... etc, etc, possibly putting this into a function so you can reuse it.

---

As a side note, if you know payload contains non-null-terminated text that you want to print, you can use the overload of `write()` that allows you to specify the length.

```
Serial.write(payload, length);

```
> 2 votes

# Answer
The easier way to simply the code is to use `strcpy` to create a buffer that is 1 byte longer than the `length` and then terminate it with `\0`.

```
void messageHandler(char *topic, byte *payload, unsigned int length) {
  char buffer[length+1];
  strcpy(buffer, (const char*) payload);
  buffer[length] = '\0';

  Serial.println(buffer);

  int matched = strcmp(buffer, "ravenclaw");
}

```
> 2 votes

---
Tags: string, array, c-string
---


# Question
Title: Arduino Nano 33 IoT LSM6DS3: get gyro angle in degrees
I have an Arduino Nano 33 IoT and I want to get the angle of it using the built-in gyro but I can't seem to find any example code that does this.

The default gyro and accelerometer example code doesn't help. Is it even possible to do this?

# Answer
You wil have to calculate the angles. Some trigonometry is required, and for the gyroscopes, also some integration. You can read about it here, and in many other places.

You will get the best results if you combine the data from the gyroscopes and the accelerometers using a *complementary filter*, a *Kalman filter*, or an other algorithm. These are also easily googled.

There is some example code for the LSM6DS3 IMU on the Nano 33 IoT here on Github.
> 1 votes

# Answer
You are supposed to use a filter library on top of the output of the gyro as well as the accelerometer data (both is used!) to get angles ... https://www.arduinolibraries.info/libraries/madgwick

Here is a working example that prints the pitch of the sensor from +90 to -90 degrees:

```
//#include <SPI.h>
//#include <Wire.h>
#include <Arduino_LSM6DS3.h>
#include <MadgwickAHRS.h>
#include <Math.h>

float pitchFilteredOld;
Madgwick filter;
const float sensorRate = 104.00;

void setup() {
  Serial.begin(9600);
  while (!Serial);
  if(!IMU.begin())  {
    Serial.println("Failed to initialize IMU!");
    while (1);
  }
  filter.begin(sensorRate);
  Serial.println("Setup complete!");
}
void loop() {
  float xAcc, yAcc, zAcc;
  float xGyro, yGyro, zGyro;
  float roll, pitch, heading;
  if(IMU.accelerationAvailable() && IMU.gyroscopeAvailable()){
    IMU.readAcceleration(xAcc, yAcc, zAcc);
    IMU.readGyroscope(xGyro, yGyro, zGyro);
    filter.updateIMU(xGyro, yGyro, zGyro, xAcc, yAcc, zAcc);
    pitch = filter.getPitch();
    float pitchFiltered = 0.1 * pitch + 0.9 * pitchFilteredOld; // low pass filter
    Serial.println("pitch: " + String(pitchFiltered));
    pitchFilteredOld = pitchFiltered;
  }
}

```
> 2 votes

---
Tags: arduino-nano, accelerometer, gyroscope, imu
---


# Question
Title: What processor can I replace on behalf of ATMEGA328P, to get more processing power for machine learning in UNO
I wanted to do a machine learning project in Arduino UNO R3. But I came to know that the processor(ATMEGA328P) isn't capable of supporting the processing power needed for machine learning. So is there any other processor that is better than ATMEGA328P for machine learning that is supported in UNO? If not any other way that I can do it?

# Answer
> 3 votes
You can't just replace the processor on the UNO with something better. The 328P is pretty much the best MCU there is in the pinout for that board.

Instead you can replace the whole UNO with something more powerful.

My board of choice for AI work would have to be one based on the Kendryte K210 chip, such as the Maixduino (which is helpfully in an UNO footprint). The K210 is a dual-core 64-bit 400MHz RISC-V CPU with embedded neural network co-processor. On the Maixduino it's also coupled with an ESP32 for WiFi/Bluetooth. That's 2x 400MHz 64-bit cores, 2x 32-bit 240MHz cores, one low-power FSM core, and a neural network core all on one board.

# Answer
> 2 votes
The Arduino blog recommends this: https://store.arduino.cc/nano-33-ble-sense.

See: https://blog.arduino.cc/2019/10/15/get-started-with-machine-learning-on-arduino/

I know Arduino has been talking about machine learning for about a year or so. Here's the Google search I used to find this: Arduino machine learning.

Here's a kit you can buy too: https://store.arduino.cc/usa/tiny-machine-learning-kit.

---
Tags: arduino-uno, atmega328
---


title: Measure the time between 2 inputs

text:
# Question
Title: Measure the time between 2 inputs
I am making a small project, and for that, I need to measure the time between 2 inputs. basically, a program to measure the time elapsed from when digital pin 2 is high to when it again becomes high.

# Answer
The way to go depends on the time range, that the event will have. The Arduino framework already includes a function for timekeeping: `millis()`. It returns the number of milliseconds since the startup (much like a clock) and measures the time via the hardware Timer0 and it's interrupts. This function will work good in the 2 digit millisecond range and above. With single digit millisecond or the microsecond domain, you should instead use `micros()` with works similar, but returns the microseconds since startup. For the low microsecond range and below you would need to work directly with a dedicated hardware timer, configuring it via its hardware registers.

Here I would show the principle of `millis()`/`micros()`, since that is most likely what you need. In the following I will only write `millis()`, but all the calculations can also be done with `micros()`. The only difference for the calculations is the factor 1000 between milli- and microseconds.

When you look at your watch and want to measure a time difference, you take note of the start time and the end time. Then you calculate the difference to get the event duration. You can do the same with `millis()`:

```
unsigned long starttime = millis(); // take note of start time
// here the event to measure
unsigned long endtime = millis(); // take note of end time
unsigned long duration = endtime - starttime; // duration of the event in ms

```

So in your code you need to check for a rising edge of your signal. On every rising edge you calculate the time difference between the last timestamp and the current time. Then you reset the timestamp. Something like this:

```
int last_input_state = LOW;
unsigned long timestamp;

//setup here

void loop(){
    int current_input_state = digitalRead(2); // get current signal level
    if(current_input_state && !last_input_state){ //check, if signal is now high and was low before
        unsigned long current_time = millis(); // take note of the current time
        unsigned long duration = current_time - timestamp; // calculate the duration and do something with it
        timestamp = current_time; // update the timestamp with the current time
     }
     last_input_state = current_input_state; // update the last input state with the new measured one
}

```

Note:

* This code is non-blocking. It needs to run fast and continuously to work correctly. You cannot do long blocking things in the rest of your code, like using high `delay()` calls, but you shouldn't do that either way, since that will block anything from going on.
* You can go even further to lift the weight from your CPU and use an interrupt to sense the rising edge. You could use `attachInterrupt(digitalPinToInterrupt(pin), service_function, RISING);` and provide a `void service_function()`, which does the timestamp measurement and calculation (basically the same code as in the if statement of the code above).
> 3 votes

# Answer
You could do something like this:

```
unsigned long startTime;
unsigned long elapsedTime;

// Any needed setup stuff
void setup()
{
  ...
}

void loop()
{
  // Wait for input to go high
  while(digitalRead(2) == LOW);

  // Start timing
  startTime = millis();

  // Wait for input to go low
  while(digitalRead(2) == HIGH);

  // Now wait for it to go high again
  while(digitalRead(2) == LOW);

  // Now get the time interval
  elapsedTime = millis() - startTime;

  // Do whatever with the result.
  ...
}

```

Keep in mind that the millis() value will overflow every 50 days or so. If you need to run this continuously, you need to check for an overflow and adjust things accordingly.
> 1 votes

---
Tags: time, input
---


# Question
Title: Import into Arduino a vintage data bus from TMS1000
For experimentation I want to import or receive into Arduino the output data from a TMS1000 (1980s) data bus. For model train controller Hornby Zero1, and the bus sends data to receivers, for loco number, speed, direction etc. I have all the data structure etc) Is it feasible to import to Arduino, and export from the same Arduino back to the original bus. Just to see it working, and then later experiment with the data in the Arduino. What libraries would be best ? Thanks Charles Harris

# Answer
You're not going to find any pre-built libraries for this task which is somewhat unusual but not at all impossible.

Basically all you need to do is to connect the TMS1000 address/data and strobe lines to Arduino inputs and write yourself some relatively simple code to detect the various TMS1000 bus states and capture them when they happen. In order to detect specific events as you have mentioned you will need to know more about the TMS1000 software that's running and what I/O devices that it's selecting. But again, that's all pretty straightforward.

Keep in mind, however, that you are going to have to perform level shifting on ALL the inputs from the TMS1000. This old TI chip was implemented using a PMOS (i.e. a predecessor to both NMOS and CMOS) and uses a NEGATIVE power supply instead of the more common today POSITIVE supply.

So rather than being powered by a +5V supply the way an Arduino is, the TMS1000 is powered by a -15V supply. In this case ground is still at 0V but Vdd is -15V. That means the I/O signals adhere to a different scheme as noted in the datasheet:

You can view the datasheet yourself at:

TMS1000 Datasheet

But what this means is that a LOW (i.e. Vil) is at -15V and a HIGH (i.e. Vih) is at 0V. You will need to translate these voltages so that you don't damage either the TMS1000 or the Arduino and you get the correct levels on the pins that you are watching.

The TMS1000 datasheet has some suggested circuits for interfacing to 74LSxx series parts (i.e. 5V logic) which will probably get you started. Note that the simplest method involves running the 5V logic with its VDD at 0V and it's "ground" at -5V. While this might seem odd, the Arduino will not know the difference as voltage is always relative.
> 1 votes

---
Tags: serial, data-type
---


# Question
Title: ESP8266 SocketIOclient constant disconnect with Python WebServerSocket
I am writing a program that echos back the message sent to the web socket server on a host machine. When running the ESP module, the connection is established but immediately disconnects as seen in the first image. I originally thought this maybe a result to the host machines firewall, however, using my laptops connection, I was able to produce the desired echo. Is the constant disconnect a result in different protocols or something I am missing?

WebSocketServer on host machine (modeled off example)

```
import asyncio

from autobahn.asyncio.websocket import WebSocketServerProtocol, \
    WebSocketServerFactory

class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

        # echo back message verbatim
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

if __name__ == '__main__':
    factory = WebSocketServerFactory("ws://127.0.0.1:9000")
    factory.protocol = MyServerProtocol

    loop = asyncio.get_event_loop()
    coro = loop.create_server(factory, '0.0.0.0', 9000)
    server = loop.run_until_complete(coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
        loop.close()

```

ESP8266 modeled in arduinoWebSockets

```
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ArduinoJson.h>

#include <WebSocketsClient.h>
#include <SocketIOclient.h>

#include <Hash.h>

ESP8266WiFiMulti wiFiMulti;
SocketIOclient socketIO;

void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
    switch(type) {
        case sIOtype_DISCONNECT:
            Serial.printf("[IOc] Disconnected!\n");
            break;
        case sIOtype_CONNECT:
            Serial.printf("[IOc] Connected to url: %s\n", payload);
            socketIO.send(sIOtype_CONNECT, "/");
            break;
        case sIOtype_EVENT:
            Serial.printf("[IOc] get event: %s\n", payload);
            break;
        case sIOtype_ACK:
            Serial.printf("[IOc] get ack: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_ERROR:
            Serial.printf("[IOc] get error: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_BINARY_EVENT:
            Serial.printf("[IOc] get binary: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_BINARY_ACK:
            Serial.printf("[IOc] get binary ack: %u\n", length);
            hexdump(payload, length);
            break;
    }
}

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

    //Serial.setDebugOutput(true);
    Serial.setDebugOutput(true);
    Serial.printf("[SETUP] starting up");

    Serial.println();
    Serial.println();
    Serial.println();

      for(uint8_t t = 4; t > 0; t--) {
          Serial.printf("[SETUP] BOOT WAIT %d...\n", t);
          Serial.flush();
          delay(1000);
      }

    // disable AP
    if(WiFi.getMode() & WIFI_AP) {
        WiFi.softAPdisconnect(true);
    }

    wiFiMulti.addAP("ssid", "password");

    //WiFi.disconnect();
    while(wiFiMulti.run() != WL_CONNECTED) {
        delay(5000);
        Serial.println("Retrying...");
    }

    String ip = WiFi.localIP().toString();
    Serial.printf("[SETUP] WiFi Connected %s\n", ip.c_str());

    // server address, port and URL
    socketIO.begin("local host address", 9000);
    // event handler
    socketIO.onEvent(socketIOEvent);
}

unsigned long messageTimestamp = 0;
//int attempts = 0;
void loop() {
    socketIO.loop();
}

```

# Answer
> 1 votes
After testing the server on the host machine using an additional computer, I was able to produce the desired output. I would suspect it is an issue within the library or mis-use/understanding. I found a post that suggested the library was the problem and ended up using this library instead.

Using the example implementation , I was able to achieve the desired results.

---
Tags: esp8266, arduino-ide, web-server, python
---


title: SIM800L module on Arduino nano

text:
# Question
Title: SIM800L module on Arduino nano
I am trying to get Arduino nano and SIM800L module working together. I provided the module with the recommended external voltage of 4.0V (documentation states 3.6V - 4.2V) transformed via LM2596. The original source is 5V 3A.

LED on SIM800L blink once a second as stated in documentation when in an unconnected state.

The schema is the following:

```
                  Antena
                   \_/
                    |
Arduino    SIM800L  |  External 4.0V
             NET ---/
             VCC ----- +4.0V
D2 --------- RST
D3 --------- RX
D4 --------- TX
             GND ----- GND

```

I have already tried 3 different libraries for AT communication and also sending raw AT commands using writing to serial manually. I also tried another SIM800L module because I thought the module is faulty.

Here is the dump from serial communication:

```
[551135] ### TinyGSM Version: 0.10.9
[551139] ### TinyGSM Compiled Module:  TinyGsmClientSIM800
AT
��AT
�AT
H�j���[552012] ### Unhandled: Hj
AT
AT-���[552317] ### Unhandled: AT-
AT
��AT
��AT
�Z5
[553228] ### Unhandled: Z5
AT
␚)O���[553532] ### Unhandled: ␚)O
AT
AT���[553836] ### Unhandled: AT
AT
��AT
��AT
�)OK��[554748] ### Unhandled: )OK
AT
���[555053] ### Unhandled: 5
AT
���AT
��AT
��AT
�j�H�[556266] ### Unhandled: jH
AT
CC����[556570] ### Unhandled: CC
AT
AT���[556875] ### Unhandled: AT
AT
��AT
AT
���[557787] ### Unhandled: T
AT
�H����[558091] ### Unhandled: H
AT
AT���[558395] ### Unhandled: AT
AT
��AT
��AT
AT
jRO���[559610] ### Unhandled: jRO
AT
AT���[559915] ### Unhandled: AT
AT
��AT
��AT
AT
�
OK��[561128] ### Unhandled: OK
Failed to initialize SIM800L

```

As you can see the module is trying to negotiate the baudrate. By default, I use speed 9600 as stated in the documentation. When I use a different baudrate the module does not respond at all.

It seems the module replies and sometimes even correctly. Response to `AT` command should be `OK`.

Do you know how do I successfully negotiate the speed and establish reliable serial communication with the module? Do I miss any electrical components in my circuit like a capacitor or resistor? I tried to use capacitor 35V / 3300µF but without any difference. I think my power source is strong enough.

The source code is the following:

```
#define PIN_GSM_RST             2
#define PIN_GSM_TX              3
#define PIN_GSM_RX              4
#define GSM_BAUDRATE            9600

#define TINY_GSM_MODEM_SIM800
#define TINY_GSM_DEBUG          Serial
#define TINY_GSM_USE_GPRS       true
#define TINY_GSM_USE_WIFI       false

#include <Arduino.h>
#include <SoftwareSerial.h>
#include <TinyGsmClient.h>
#include <StreamDebugger.h>

SoftwareSerial serial_SIM800L(PIN_GSM_RX, PIN_GSM_TX);
StreamDebugger debugger(serial_SIM800L, Serial);
TinyGsm modem(debugger);
TinyGsmClient client(modem);

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

    Serial.println(F("Serial initialized"));

    serial_SIM800L.begin(GSM_BAUDRATE);
    delay(5000);

    while (!modem.init()) {
        Serial.println("Failed to initialize SIM800L");
    }
}

void loop() {
    //
}

```

# Answer
Thanks to @PeterPaulKiefer here is the answer.

External power for SIM800L module GND pin needs to be connected to both SIM800L module GND pin and Arduino nano GND pin. (e.g between RST and R2 pin on Arduino nano)

In order for the calling function to work, you also need to use a capacitor on SIM800L VCC and GND pins. I used 35V, 3300µF.

Schema:

```
                  Antena
                   \_/
                    |
Arduino    SIM800L  |  External 4.0V
             NET ---/
             VCC ----- +4.0V
 D2 --------- RST   |
 D3 ---------  RX  === Capacitor (35V, 3300µF)
 D4 ---------  TX   |
GND --------- GND ----- GND

```
> 1 votes

---
Tags: arduino-nano, softwareserial, gsm
---


# Question
Title: Ethernet Shield web server - Can't find the index.htm file
i've just got the EthernetShield and watched a tutorial on how to host a html page with it but i can't find my html page on the SD card.

```
#include<SPI.h>
#include<Ethernet.h>
#include<SD.h>

byte mac[] = {0xA8, 0x61,0x0A, 0xAE, 0x3A, 0xC4 };

EthernetServer server(80);

File webPage;

void setup() {
  Ethernet.begin(mac);
  server.begin();
  Serial.begin(9600);

  Serial.println(Ethernet.localIP());

  Serial.println("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println("ERROR - SD card initialization failed!");
    return;
  }
    Serial.println("SUCCESS - SD card initialized.");
    if(!SD.exists("index.htm")){
      Serial.println("ERROR - Can't find index.htm file!");
    }
      Serial.println("SUCCESS - Found  index.htm file.");
}

void loop() {
   EthernetClient client = server.available();
   if(client){
    boolean currentLineIsBlank = true;
    while(client.connected()){
      if(client.available()){
        char c = client.read();
        if(c == '\n' && currentLineIsBlank){
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();

          webPage = SD.open("index.htm");
          if(webPage){
            while(webPage.available()){
              client.write(webPage.read());
            }
            webPage.close();
          }
          break;
        }
        if(c == '\n'){
          currentLineIsBlank = true;
        }
        else if(c != '\r'){
          currentLineIsBlank = false;
        }
      }
    }
    delay(1);
    client.stop();
   }
}

```

When i save the HTML file i can't save it with the .htm format

# Answer
> 2 votes
Windows is hiding the extension from you.

The file you showed is either `index.htm` or `index.html`. If it's the latter, you could change the windows setting to "show extensions for know filetypes", or change the sketch so it uses `index.html` instead of \`index.htm. I'd go with the latter, as it's the easiest.

EDIT: the SD library doesn't seem to like file extension that are longer than 3 characters. So changing the code to use "index.html" doesn't work.

---
Tags: arduino-uno, ethernet-shield
---


# Question
Title: Is it possible to check for correct architecture on OTA update (ESP32 or ESP8266)?
Having a skech running on ESP8266 as well as ESP32 with the ability to update via OTA, uploading the wrong binary (upload to ESP8266 compiled for ESP32, and vice versa) leads to crashing the MCU and not being able to do OTA Updates any more.

The Update is done in the simple usual way: Upload binary file and call the methods from the Update Class (begin(), write(), and end()).

Is there any way to check if the uploaded file matches the architecture of the MCU before starting the update?

Edit:

Both the ESP8266 and the ESP32 Updater class check for an "IMAGE\_MAGIC" value in the upload header; but that is defined as "ESP\_IMAGE\_MAGIC = 0xe9" in both cores. So none of them will refuse to update the wrong one.

Edit 2:

Found a simple workaround that satisfies our needs at the moment: As the arduino IDE saves the binaries with a name like \<sketch\_name\>.\<board\_name\>.bin, we just compare the board name as part of the uploaded filename: `if (upload.filename.indexOf(MATCH) > 0) ...`, where `MATCH` is the respective board name. As they are pin compatible, we use "d1\_mini.bin" and "d1\_mini32.bin".

Edit 3:

When the webserver tries to abort the upload with `403 Forbidden` (because of wrong file), the browser continues to send data until the upload is done. After that, it displays the error message. Thus, even when the filename does not match, it is a waste of time and bandwidth. The only possibility to avoid this is to do a `server.client().stop()`, but then the browser will not display the message sent, just something like "connection broken". This does not confirm with the respective RFCs.

This is not really a final solution, so I'ld appreciate any better idea.

Richard

# Answer
> 1 votes
I assume you are the one creating the OTA update. If so, then why don't you just include a "signature" in the code that is the architecture, i.e. ESP8266 vs. ESP32 and then check for that in your updater code so that it will not install an update for the wrong CPU.

---
Tags: esp, ota
---


# Question
Title: How to transfer constants from one loop to next one
```
#include "VernierLib.h"

VernierLib Vernier;

#define led 13

float sensorReading;

void setup() {
  Serial.begin(9600);
  Serial.println(Vernier.sensorName());
  Vernier.autoID();
}

void loop() {
  float base_temp;
  base_temp = Serial.parseFloat();
  sensorReading = Vernier.readSensor();
  Serial.print(sensorReading);
  Serial.print(" ");
  Serial.println(Vernier.sensorUnits());
  Serial.println(base_temp);
  if (base_temp > sensorReading) {
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
  delay(3000);
}

```

That's the code, I have a question. When I write the temperature to Serial, it lasts only until the end of one loop.

How to keep the same temperature in the next loop?

# Answer
> 1 votes
There are two things here you need to consider.

First is that your variable is a "local" variable. This kind of variable is created at the start of each iteration, then discarded at the end of that iteration.

There's two things you can do to "fix" this:

1. Make the variable "global" - that is, move the definition out of `loop()` to the "global" scope (put it at the top of your program). It is then only created once and never discarded.
2. Make the variable "static" - that is, add the `static` keyword to it. It is then created on the first iteration only, and never discarded.

The second thing to consider is that you have no "There is no value" concept. Every iteration you parse a new float, whether there is one there or not. And if there isn't one then it just gives you `0`. So you need to come up with some way of saying "I have entered a number, so parse it". The simplest thing is just to assume that all values of 0 are "no number entered", but that of course prevents you ever entering 0 as a valid input.

# Answer
> 0 votes
Something like this should work (untested, but you get the idea; the explanation is in the comments):

```
void loop() {
  static float base_temp = 21;     // Or whatever default starting value you want
  static float t = 0;              // A temporary store for Serial.parseFloat()

  t = Serial.parseFloat();         // Read t; if Serial.parseFloat() times out, it will return 0.00
  if (t != 0.00) {                 // If something else than 0.00 is in t
    base_temp = t;                 // Update base_temp with t
  }                                // Note: You can't set base_temp to exactly 0.00 with this set-up
  sensorReading = Vernier.readSensor();
  Serial.print(sensorReading);
  Serial.print(" ");
  Serial.println(Vernier.sensorUnits());
  Serial.println(base_temp);
  if (base_temp > sensorReading) {
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
  delay(3000);
}

```

In this code `0.00` means that "no value was entered", so you can't set the temperature to *exactly* 0.00 with this set-up; 0.01 should work fine, though.

---
Tags: arduino-uno
---


# Question
Title: How can I control blinking of LED while in timer function?
When I am in the 30-second standby function, I want to turn the LED on and off at 5-second intervals.

How can I do what I want using the `read_counter()` function?

The problem here is that I am already in the timer function with the `read_counter()` function.

```
void wait_function() {
  timer_init();
  while(read_counter()<30000) { //30 second wait
    // A LED blinking at 1 second intervals ???
  }
}

```

Note: The read\_counter() function increases every 1 millisecond with ISR COMPA vector. I tried many times and couldn't find a stable solution. Example:

`if (read_counter() % 1000) PORTB^=(1<<LED);`

**Update: My new code :**

```
while((TIFR1 & (1 << OCF1A))==0) //4secondIf I do this cycle 8 times, it
                                 //makes 32 seconds.
            {
                if(TCNT1%15624==0) //per 15624=1 second,
                PORTA^=(1<<0);
                 //led_blink_1s
            }

```

But,it doesn't work.Should I use util delay function?

# Answer
> 1 votes
Your waiting loop runs much faster than once per millisecond, and even faster per second. So to get just one "event" per second, you need to detect the change of the second.

```
void wait_function() {
  timer_init();
  for (int second = 0; second < 30; ++second) { // 30 second wait
    // Wait for the next second
    int old_second = read_counter() / 1000;
    int new_second;
    do {
      new_second = read_counter() / 1000;
    } while (new_second == old_second);

    // A LED blinking at 1 second intervals
    PORTB ^= 1 << LED;
  }
}

```

However, you may think about refactoring your timer. You can put the division in the ISR, and then set a flag if a second has past. In your waiting loop you could wait for the flag, reset it, and toggle the LED.

**EDIT:**

If you have your (pseudo) code like this:

```
while (!timed_out) {
    if (timer % ticks_per_second == 0) {
        do_something();
    }
}

```

you will have the following erroneous behavior, presumed that the loop runs 1 million times per second and the timer increments 20000 times per second.

1. The timer starts at 1000, for example, and has just incremented.
2. The loop runs for 50 times until the timer increments to 1001.
3. This happens repeatedly until the timer gets 20000, which will be after (20000 - 1001) * 50 = 949950 loops.
4. Now the loop will run for 50 times, while the timer is still at 20000.
5. The condition is `true` on each repetition, so `do_something()` will be executed 50 times in a row.
6. Next, the timer increments to 20001, and the condition becomes `false`.

This is exactly what you observe: If the condition of the `if` becomes `true`, its statement will be executed repeatedly.

Because the relation between the loop's repetition frequency and the timer's frequency is not the presumed value (but similar) and even depends on the instructions executed, the state of the output is subjectively random. If the XOR instruction is executed an even number, the LED does not change, and if it is executed an odd number, the LED changes.

# Answer
> 1 votes
My solution:

```
uint16_t st_led=0;
  uint16_t et_led=0;

    while((TIFR1 & (1 << OCF1A))==0) //30 second
    {

      st_led=TCNT1;
      et_led=st_led;
      while((et_led-st_led)<=15624) //1 second
      {
        et_led=TCNT1;
      }
      PORTA ^= (1<<ledno);
    }
    TIFR1=(1<<OCF1A);
    TCCR1B=0;

```

# Answer
> 0 votes
If read-counter is already incremented once a millisecond, use that to time your LED flashes:

```
void wait_function() {
  timer_init();
  bool LED_State = LOW
  while(read_counter()<30000) { //30 second wait
    // A LED blinking at 1 second intervals ???
    if (read_counter % 1000 == 0) { //Switch 1000 to 500 here if it flashes too slowly
       LED_State = !LED_State;
       digitalWrite(LEDPin, LED_State ? HIGH : LOW);
    }
  }
}

```

That code will turn the LED on for one second, then off for one second, etc. (For a total cycle time of 2 seconds.) If you want the full on-off cycle to last 1 second, lower the if statement's value from 1000 to 500.

---
Tags: arduino-uno, led, timers, avr-gcc, atmel-studio
---


# Question
Title: ESP-NOW and WIFI and OTA at the same time on Sender and Receiver
I am trying to set up two ESP32s so that they can be updated via OTA and at the same time send sensor readings using ESP-NOW, from Sender Board to Receiver Board.

For this to work both boards must connect to wifi and simultaneously send messages over ESP-NOW.

I don't mind using a mode where a button is pressed and Wifi is only then enabled but switching wifi on and off seems to have intermittent success.

I have tried setting the channels to the same on both boards but this does not work.

In the example below I have stripped all the OTA code out and the code needed for ESP-NOW and just the line for WIFI enable

> WiFi.begin(ssid, password);

which when enabled causes the delivery to fail.

Here is my Sender Code:

```
        #include <esp_now.h>
        #include <WiFi.h>
        #include <Wire.h>
        #define ssid "MYNETWORKSSID"
        #define password "mynetworkpassword"

         const int sNine = 33;

         #define CHAN_AP 2

        uint8_t broadcastAddress[] = {0x24, 0x62, 0xAB, 0xDC, 0x70, 0x90};
        int hall;

        String success;

        typedef struct struct_message {
            int hall;
        } struct_message;
        struct_message hallReadings;

        // Callback when data is sent
        void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
          Serial.print("\r\nLast Packet Send Status:\t");
          Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
          if (status ==0){
            success = "Delivery Success :)";
          }
          else{
            success = "Delivery Fail :(";
          }
        }

        void setup() {
          // Init Serial Monitor
          Serial.begin(115200);
          WiFi.mode(WIFI_STA);
         WiFi.begin(ssid, password); // PROBLEMATIC LINE

          // Init ESP-NOW
          if (esp_now_init() != ESP_OK) {
            Serial.println("Error initializing ESP-NOW");
            return;
          }
          // Once ESPNow is successfully Init, we will register for Send CB to
          // get the status of Trasnmitted packet
          esp_now_register_send_cb(OnDataSent);

          // Register peer
          esp_now_peer_info_t peerInfo;
          memcpy(peerInfo.peer_addr, broadcastAddress, 6);
          peerInfo.channel = CHAN_AP;
          peerInfo.encrypt = false;

          // Add peer
          if (esp_now_add_peer(&peerInfo) != ESP_OK){
            Serial.println("Failed to add peer");
            return;
          }
        }

        void loop() {
          // getReadings();

           hallReadings.hall = analogRead(sNine);

          esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &hallReadings, sizeof(hallReadings));

          if (result == ESP_OK) {
            Serial.println("Sent with success");
          }
          else {
            Serial.println("Error sending the data");
          }
          delay(100);
        }

```

Here is my Receiver code:

```
#include <esp_now.h>
#include <WiFi.h>
#include <Wire.h>

 const int sNine = 15;

//Wi-Fi channel (must match the gateway wi-fi channel as an access point)
#define CHAN_AP 2

// Define variables to store incoming readings
int incomingHall;

//Structure example to send data
//Must match the receiver structure
typedef struct struct_message {
    int hall;
} struct_message;

// Create a struct_message to hold incoming sensor readings
struct_message incomingReadings;

void updateDisplay(){

  Serial.print(incomingReadings.hall);
}

// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
  memcpy(&incomingReadings, incomingData, sizeof(incomingReadings));
  incomingHall = incomingReadings.hall;
}

void setup() {
  // Init Serial Monitor
  Serial.begin(115200);
  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);
  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);
}

void loop() {

  updateDisplay();
  delay(100);
}

```

# Answer
> 2 votes
If you want to switch the softAP connection On/OFF you can do like StefanL38 suggests and have the Receiver transmit a ESP-NOW message with a value to the Sender, but you don't need a reboot. You can drop softAP and come up as STA or vise versa, for example.

```
    if(incomingid == 3){
      incomingValue = incomingReadings.Value;

      // to allow OTA, using Elegant OTA, haven't tried others.

    if(incomingValue == 1){
      WiFi.softAP(ssid,password,6);
      Serial.print("Connecting to ESP32 SSID ");
      Serial.println(ssid);
      IPAddress IP = WiFi.softAPIP();
      Serial.print("AP IP address: ");
      Serial.println(IP);
      WiFi.printDiag(Serial);
    }

      // to disconnect and allow ESP-NOW via Station mode.

   else if(incomingValue == 0){
      WiFi.softAPdisconnect(true);
      delay(1000);
      WiFi.mode(WIFI_STA);
      delay(1000);
      WiFi.printDiag(Serial); // STA Defaults to channel 1
      esp_wifi_set_promiscuous(true);
      esp_wifi_set_channel(6, WIFI_SECOND_CHAN_NONE); // channel 6 setup
      esp_wifi_set_promiscuous(false);
      WiFi.printDiag(Serial);
    }
  }

```

# Answer
> 2 votes
I do something similar on a ESP8266 retrieving time from a NTP-server. Though it is just a "work around".

* I connect to the router retrieving the NTP-time.
* storing the time-information into RTC-RAM including a flag that indicates "time received"
* then do a software-RESET
* the setup-function checks this flag to decide if the ESP8266 shall connect to the router or shall keep WiFi OFF and activate ESP-NOW

if you want to use this for OTA it could "work" like this

sending a special ESP-NOW-Message initiating setting a flag "do\_OTA" in RTC-RAM and then re-boot the setup-function looks for this flag "do\_OTA" to be set does what its name says clearing the "do\_OTA"-flag

What I don't know is writing new code into flash is a different thing than just re-booting through a software-reset. So maybe the content of the RTC-RAM gets lost through the update-process.

If so you could write the flag into flash using LittleFS

best regards Stefan

# Answer
> 2 votes
Another method that works if you don't mind having both at the same time:

Instead of WiFi.begin(ssid, password); I use WiFi.softAp(ssid,password,channel); for both Sender and Receiver.

---
Tags: esp32, espressif
---


# Question
Title: EEPROM programmer works with serial monitor but not with pySerial
I'm trying to modify Ben Eater's eeprom programmer to flash a 32K eeprom, since the arduino has 32K of program data total the data wouldn't fit in the program. So I wrote a python program using pySerial to send the data in chunks of 256 bytes over serial. The arduino program works correctly when I manually send the data over the serial monitor, and the python program works correctly when I print the values to a console as a test, but when I actually run the program over serial it seems to only write zeros to the eeprom. Additionally, the Rx led on the arduino seems to be lighting up with the correct data, but like I said only zeros are written.

Here's the relevant arduino code:

```
void setup() {
  pinMode(SHIFT_DATA, OUTPUT);
  pinMode(SHIFT_CLK, OUTPUT);
  pinMode(SHIFT_LATCH, OUTPUT);
  digitalWrite(WRITE_EN, HIGH);
  pinMode(WRITE_EN, OUTPUT);

  Serial.begin(57600);
  dataArrPage = 0;

  //delay(1000);
  //Serial.println("Reading EEPROM");
  //printContents();

}

void loop() {
  if (Serial.available() > 0) {
    int len = Serial.readBytes(dataArr, 256);

    for (int i = 0; i < 256; i++) {
      writeEEPROM(dataArrPage + i, dataArr[i]); // writeEEPROM(address, data)
    }
    dataArrPage += 0x100;

    Serial.write('s'); //success, writing is done
  }
}

```

And the relevant python code:

```
import time
import serial
ser = serial.Serial('/dev/ttyUSB0', 57600)
time.sleep(4) # wait for arduino to initialize

filename = input("Enter file name: ")
f = open(filename, "rb")
data = f.read()

page = 0
for x in range(128): # 128 pages in 32K eeprom
    for i in range(256):
        #print(hex(data[(page * 256) + i])) # printing prints the correct values
        ser.write(data[(page * 256) + i])
    page += 1

    #wait until receive 's' from arduino
    while True:
        if ser.in_waiting > 0:
            suc = ser.read(size=1)
            if suc == b's':
                print("Success")
                break

print("Writing done")
f.close()
ser.close()

```

I'm a beginner so sorry if it's something obvious.

# Answer
I figured out the problem. The for loop was writing one byte at a time, which probably wasn't fast enough and caused a timeout in the arudino. The code is now:

```
page = 0
for x in range(128): # 128 pages in 32K eeprom
    datalst = []
    for i in range(256):
        datalst.append(data[(page * 256) + i])

    ser.write(datalst)

    #wait until receive 's' from arduino
    while True:
        if ser.in_waiting > 0:
            suc = ser.read(size=1)
            if suc == b's':
                print("Success")
                break

    page += 1

```

I also changed the data types in the arduino sketch to use the ones in stdint.h which solved an unrelated bug. Let me know if I should post the full code for both.
> 1 votes

---
Tags: serial, eeprom, python
---


# Question
Title: How can I execute a string in my Arduino Uno board?
I was making a project with Arduino Uno , It's working is like this it connects to a key pad and a 7segment display ,and when you press a run button connected to Arduino it should run the code written.

I don't want code for display and keypad but for executing a string like we can do in python- **exec("print (8)")**

Please help me and ask any information you need to solve it

# Answer
Unless you want to implement some form of scripting engine, you can't.

Arduino code is compiled code, not interpreted code. There is no way of converting text into runnable code, since that is done by your computer at compile time, not by the Arduino at run-time.

The only thing you could possibly do is write some form of scripting engine which reads text and interprets it in some meaningful way to perform operations. That is not a trivial task, so you have to ask yourself: is this *really* what you want to do? Are you going about tackling your problem in the right way?
> 4 votes

# Answer
As stated in Majenko's answer, you would need an interpreter running on the Arduino. Python is too large to run on an Uno, although it can run on some more powerful microcontrollers.

A Web search for Arduino interpreters yields quite a few promising options. I have not tested any of them:

The Forth language is quite popular when you need an interpreter with minimal footprint.
> 1 votes

---
Tags: arduino-uno, python, cpp
---


# Question
Title: button connection without connection to 5V pin
There are two types of tutorials for buttons:

I don't understand how a button on the first image works. Do we just hope that there is some non zero voltage and hope its enough? I think the first image is really bad, but can't explain why.

# Answer
There is a pullup resistor you don't see in the diagram because it is internal to the Arduino. I have added it in red. To make pin 7 an input, you can write:

```
digitalWrite(7, INPUT_PULLUP);

```

, which not only makes the pin an input but also engages the internal ~20K pullup resistor.

So, you're right about the first diagram - it looks like the pin is left floating. Without the code, or an explanatory note, the pullup resistor isn't documented. In such a diagram, once you are familiar with the processor and know that there are optional pullups on the pin-drivers, you can assume that the optional pullup will be used.

Update: I drew in the resistor assuming the red rail was connected to 5v - I should have drawn that in, too.
> 7 votes

# Answer
The digital pins of an Arduino UNO, or rather the AVR microcontroller used in the UNO, have optional internal pull-up resistors that can be enabled with the `INPUT_PULLUP` option to `pinMode`. When you use `INPUT_PULLUP` (as opposed to `INPUT`) there is a functional resistor somewhere between 20kOhm and 50kOhm connected between VCC ("5V") and the digital pin. When you account for this internal resistor enabled, the circuits in your two images are structurally mirror images of one another:

The boxed numbers here are just to clarify what nodes in the wiring diagram correspond to what nodes in the schematic representation. Don't ask where box number 5 is; it's a mystery. I chopped part of the original second image so a new GND connection was hand-drawn in.

In your first image (left) the code would have to enable the internal pull-up resistor to establish a default `HIGH` state on the digital pin. With `INPUT_PULLUP` enabled you can imagine that internal resistor there when comparing with your second image (right). Here I've drawn a resistor symbol over the board to represent the internal one when enabled. When the button is pushed some current is drawn through that internal pull-up and the voltage at the pin falls to ground. Note you could just as easily have an external resistor there and use plain `INPUT` mode.

Your second example image (right) is using an external pull-down resister to establish a default `LOW` state. So when you push the button, the signal rises toward 5V/VCC or `HIGH`, and some current flows through the pull-down resistor. This would be used with `INPUT` mode rather than `INPUT_PULLUP`; I have not annotated an internal pull-up on the right to indicate that the pull-up is not enabled in this scenario (plain `INPUT` mode). *Note that if you **were** to enable the internal pull-up in this second configuration it would form a voltage divider with external pull-down; for the 10K external pictured this **could** result default voltage at the pin which is only bordering on being a proper `LOW`*.

Some people find it less confusing to have a `HIGH` state when the button is pushed and also using an external resistor like this helps to explain the concept having a pull resistor altogether, because you can see it. In practice though, it's nice to able to use the internal resistors even if they pull in a more confusing direction. Note there do exist microcontrollers have optional internal pull-down resistors as well, but they're not as common; the UNO in particular does not have these.
> 4 votes

---
Tags: button
---


# Question
Title: Wire.endTransmission(false) hanging the program after running once when using MPU6050
For this project, I was using an *Elegoo Car V3* and I was trying to add a gyroscope onto it. When I run the code for the car, my loop code iterates once and it is always able to read the sensor data. But after that, the program starts hanging. I traced back the problem to the `Wire.endTransmission(false)` line in my code. For some reason, that line was not completing the second time.

I spent a few hours trying to find a solution online. I triple checked my wiring and still, I could not find a solution to this problem.

Thank you for taking the time to help me!

This is the output of the program

```
RawX= 82
RawY= 241
RawZ= -1
-----------------------------------------
AngleX= 195.41
AngleY= 216.93
AngleZ= 200.14
-----------------------------------------

```

And this is the code

```

#include <Wire.h>

const int MPU_addr = 0x68;
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

int minVal = 265;
int maxVal = 402;

double x;
double y;
double z;
int c = 0;

//www.elegoo.com

//     Right motor truth table
//Here are some handy tables to show the various modes of operation.
//  ENB         IN3             IN4         Description
//  LOW   Not Applicable   Not Applicable   Motor is off
//  HIGH        LOW             LOW         Motor is stopped (brakes)
//  HIGH        LOW             HIGH        Motor is on and turning forwards
//  HIGH        HIGH            LOW         Motor is on and turning backwards
//  HIGH        HIGH            HIGH        Motor is stopped (brakes)

// define IO pin
#define ENA 5
#define ENB 6
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11

//set car speed
#define CAR_SPEED 100
typedef unsigned char u8;  //Change the name of unsigned char to u8

void forward(u8 car_speed)
{
  analogWrite(ENA, car_speed);
  analogWrite(ENB, car_speed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}

void back(u8 car_speed)
{
  analogWrite(ENA, car_speed);
  analogWrite(ENB, car_speed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}

void left(u8 car_speed)
{
  analogWrite(ENA, 250);
  analogWrite(ENB, 250);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);

  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}

void right(u8 car_speed)
{
  analogWrite(ENA, 250);
  analogWrite(ENB, 250);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}

void stop()
{
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
}

int getGyroData() {
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);
    Wire.endTransmission(false);

    Wire.requestFrom(MPU_addr,6,true);
    AcX = Wire.read()<<8|Wire.read();
    AcY = Wire.read()<<8|Wire.read();
    AcZ = Wire.read()<<8|Wire.read();

    int xAng = map(AcX, minVal, maxVal,-90, 90);
    int yAng = map(AcY, minVal, maxVal,-90, 90);
    int zAng = map(AcZ, minVal, maxVal,-90, 90);

    x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
    y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
    z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

    Serial.print("AngleX= ");
    Serial.println(x);

    Serial.print("AngleY= ");
    Serial.println(y);

    Serial.print("AngleZ= ");
    Serial.println(z);
    Serial.println("-----------------------------------------");

}

void turn(int degrees) {
    int *originalData;
    originalData = getGyroData();
    int originalTurn = originalData[2];

    bool notDone = true;

    while (notDone) {

        int *newVal;
        newVal = getGyroData();
        int newTurn = newVal[2];

        int change = originalTurn - newTurn;
        Serial.println(change);
    }
}

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  pinMode(IN1, OUTPUT);//before useing io pin, pin mode must be set first
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  Serial.begin(9600);

}

void loop(){
    c++;

    Serial.println(c);
    Wire.beginTransmission(MPU_addr);
    Serial.println(c);
    Wire.write(0x43);
    Serial.println(c);
    Wire.endTransmission(false);

    Serial.println(c);
    Wire.requestFrom(MPU_addr,4,true);
    AcX = Wire.read()<<8|Wire.read();
    AcY = Wire.read()<<8|Wire.read();
    AcZ = Wire.read()<<8|Wire.read();
    Serial.println(c);

    Serial.print("RawX= ");
    Serial.println(AcX);

    Serial.print("RawY= ");
    Serial.println(AcY);

    Serial.print("RawZ= ");
    Serial.println(AcZ);
    Serial.println("-----------------------------------------");

    int xAng = map(AcX, minVal, maxVal,-90, 90);
    int yAng = map(AcY, minVal, maxVal,-90, 90);
    int zAng = map(AcZ, minVal, maxVal,-90, 90);

    x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
    y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
    z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

    Serial.print("AngleX= ");
    Serial.println(x);

    Serial.print("AngleY= ");
    Serial.println(y);

    Serial.print("AngleZ= ");
    Serial.println(z);
    Serial.println("-----------------------------------------");
    delay(500);

}

```

This is a schematic of the car I found

# Answer
In the comments below, @chrisl makes something explicit that I hadn't in previous edits. Reading it first may make the below easier to interpret:

> Useful fact about I2C on Arduino: `Wire.endTransmission()` is the function, that actually does the I2C communication. Before that (all the `Wire.beginTransmission()` and `Wire.write()` calls) no data will run over the bus, just placed inside the libraries buffer. Thus a hanging `Wire.endTransmission()` equals a blocked I2C bus.

---

On the UNO the A4 and A5 are SDA and SCL, the same signals that are available near AREF and pin 13 on the other side of the board.

So, the ultrasonic range finder in the picture is attached the signals that are needed to operate the I2C ("Wire") bus, and may easily be interfering with `Wire.endTransmission(false)`. One of the I2C signals is probably causing the range finger to trigger during I2C traffic. After each trigger, the echo signal from the range finder would then interfere with the connected I2C bus signal.

You could try bit banging I2C using a library instead of the native I2C that is on A4/A5, and use that to operate your gyroscope. According to your diagram, A0 through A3 are unused, and seem to be the only signals unused from the UNO. Despite being "analog" pins they function as digital pins also and should work fine for bit-banging. Getting to them may be a pain though, since the shield doesn't seem to make them available again as pins.

Or you may be able to route the ultrasonic sensor away from A4/A5 either by not plugging it into the header on the shield and instead route the signals from the plug to where an unused set of pins is available (again A0 though A3) and then updating the code accordingly. Another possibility might be leave it plugged into the shield but bend the A4 and A5 pins to the side so they don't enter the UNO below, and use jumpers to route them from the bent pins to some other pair of available pins; you won't be able to bend them back and forth more than once or twice, so I would be careful with trying that.
> 3 votes

---
Tags: mpu6050, wire-library, gyroscope
---


title: l298n voltage loss when motor attached

text:
# Question
Title: l298n voltage loss when motor attached
Im trying to power a brushless DC Motor (Tamiya 300054358) through the l298n attached to an Arduino.

The l298n is powered by an external 9V source and the logic of the l298n is powered by the Arduinos 5V, wich is also powered by the 9v.

Both components using the same ground.

The code looks good and i can successfully adjust the power-output for the motor between 6-9V.

As soon as is attach the Motor, the volage drops do somewhere around 0-1V and the motor isnt turning.

When i attach the motor directly to the power source, it runs fine, so the power should be enough. (in the original RC car its powered by an 7V battery).

I tried some smaller motors just to be sure and the problem is similar. The motor is turning, but very slowly.

I also tried to connect the batterypack instead of the extern power source just ending up with the same result.

Do you have any ideas, where the problem could be at?

Thanks in advance

# Answer
> 1 votes
The problem is in the H driver. You lose about 1.4 volts on each leg so your loss from the battery is about 2.8 volts. The internal driver transistors are in a darlington configuration. If the bridge were Power MOS instead of bipolar transistors your voltage would be dependent on the resistance of the MOSFETs. Typically a few tenths of a volt in total. If your 9V source is a battery you probably are not getting the 9V you are expecting.

# Answer
> 1 votes
From an L298N datasheet:

> TOTAL DC CURRENT UP TO 4 A

From motor's "datasheet":

I'm no expert in electric motors and driving them, not even sure I'm novice level, but I just don't see you driving a motor anything near this current draw with this part. If by some miracle you can, it will be horribly inefficient owing to the losses associated with the voltage drops that Gil mentions.

For a motor that operates with this much current I would expect a practical h-bridge setup to have discrete mosfets, perhaps mounted to a heatsink.

---
Tags: motor, l298n
---


# Question
Title: Set TX, RX to LOW before sleeping, re-enable uart after waking up
I have an ATmega1284p and I need to have the TXD0 (i.e. pin 9) set to LOW, before going to sleep. After waking up, I want to restore UART0 communication to work as expected. Here is my code:

```
Serial.begin(38400,SERIAL_8N1);

*do Stuff*

Serial.end();
//pinMode(9,OUTPUT);
//digitalWrite(9,LOW);
//UCSR0B &= ~bit (RXEN0);  // disable receiver
//UCSR0B &= ~bit (TXEN0);  // disable transmitter
cli();
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
sleep_enable();
// turn off brown-out enable in software
//MCUCR = bit (BODS) | bit (BODSE);  // turn on brown-out enable select
//MCUCR = bit (BODS);        // this must be done within 4 clock cycles of above
sleep_bod_disable();  //disable brown-out detection
sei();             // guarantees next instruction executed
sleep_cpu ();              // sleep within 3 clock cycles of above
sleep_disable();

//  UCSR0B |= bit (RXEN0);  // enable receiver
//  UCSR0B |= bit (TXEN0);  // enable transmitter
//pinMode(9,OUTPUT);
//digitalWrite(9,HIGH);
//delay(100);
//pinMode(9,INPUT_PULLUP);
Serial.begin(38400,SERIAL_8N1);
delay(1000);
Serial.println("- Good Morning");

*do Stuff*

```

You can see in comments all the different things I tried:

* Using `Serial.end()` and then, after waking up, `Serial.begin()`
* Using the `UCSR0B` register
* Using `digitalWrite` to set the pin to `LOW` and then, after waking up, either setting it to `high`, or setting it as `input`

All of the above combinations have the common problem that the cpu hangs after waking up, and the Serial is never restarted to print `good morning` message, neither does the program continue to execute further down.

# Answer
After trying many different alternatives, it turns out that my mistake was that, foolishly, **I had included Serial printing inside my ISR routines**, which where accessed when my interrupt fired, in order to wake my uP. As a result, **`Serial.print` was called, with *Serial* being closed** (before issuing the `Serial.begin` command to restart it), thus breaking my uP.

**Extra:** Just wanted to comment about using Serial.print inside ISRs. Although it can lead to unexpected problems like this one, or timing issues (ISR would take too long to execute) and is definitely a bad practice, it can sometimes be useful for debug purposes during development to print some kind of message there.

Printing a message takes long, and the ISR will return before the message is completely transmitted, with the potential to cause a lot of headache. Also, interrupts are disabled inside ISRs, so delay() is not working to do some kind of flow control. The best way to print messages in ISRs that I have come across so far, is by using Serial.flush() before exiting the ISR, making sure the message is completely transmitted.
> 1 votes

---
Tags: serial, uart, sleep
---


title: Arduino PWM fading led in assembly

text:
# Question
Title: Arduino PWM fading led in assembly
I'm writing Arduino UNO (=ATMega328P-PU) programs in assembly to save memory, so I use avra.exe (same as atmel studio's avrasm32) to compile and avrdude to upload, and simple programs like blinking run fine. But now i tried to half-bright a LED with pwm. I checked up my code for errors but I didn't find any, and the LED just full brighs. I checked wiring too. I'm getting struck :c. Here's my pwm.asm code:

```
.nolist
.include "m328pdef.inc"
.list

.cseg
.org 0x00
     rjmp start
.org 0x34
 start: sbi ddrb, 5 ;pin 13
        sbi portb, 5 ;pin 13 on, just to compare with the PWMed led
        sbi ddrd, 5 ;pin 5 pwm
        ldi r16, 0b00100011 ;fast pwm mode, non inverted pwm at oc0b = pin 5 (right?)
        out tccr0a, r16 ;I'm using Timer0
        ldi r16, 0b00000001 ;no prescaler
        out tccr0b, r16
        ldi r16, 128 ; duty cycle = 50%
        out ocr0b, r16

  loop: rjmp loop

```

# Answer
I tried your program, after converting it to GNU-as syntax. It works as expected, as seen on the scope. Your problem may be simply that the difference between 50% ON and 100% ON is not very obvious to the eye because of its logarithmic perception.
> 2 votes

# Answer
you have to set the PRR timers on

start: lds r16,PRR andi r16,0b10010111 ; PRTIM2 | PRTIM0 | PRTIM1 sts PRR,r16
> 0 votes

---
Tags: arduino-uno, led, pwm, timers, assembly
---


title: How to connect to MQTT broker with TLS?

text:
# Question
Title: How to connect to MQTT broker with TLS?
I have ESP8266 which is connecting to MQTT broker and it is working ok using user+pass with following code:

```
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "WIFINAME";
const char* password = "WIFI_PASS";

const char* mqtt_server = "SERVER_IP";
const char* mqttUser = "user";
const char* mqttPassword = "pass";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str(), mqttUser, mqttPassword)) {
      Serial.println("connected");
      client.subscribe("CoreElectronics/test");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

```

As this is insecure usage I have setup TLS on MQTT broker and I can connect over command line:

```
mosquitto_sub --cafile ca.crt -h server_ip  -t "#" -p 8883 -d --cert client.crt --key client.key

```

Problem is that I cannot find any working (for me) sample with using TLS connection on ESP8266 client.

I have tried generating self-signed certs by manually script and over LetsEncrypt.

Thank you

# Answer
> 7 votes
You could make the following changes to your code by making use of WifiClientSecure (which is already part of the ESP8266 Wifi library).

The tricky part is finding out the SHA1 fingerprint for your own MQTT server and hard coding it into the **\*fingerprint PROGMEM = "..."** part (for example by examining the certificate via a PC browser and copying the SHA1 fingerprint).

Alternatively, you could set the connection to setInsecure. This means that the connection will be encrypted but it will accept any server certificate without checking.

```
...
const char* mqttPassword = "pass";

WiFiClientSecure espClient;     // <-- Change #1: Secure connection to MQTT Server
PubSubClient client(espClient);

// Change #2: Set the SHA1 fingerprint for the connection -->
static const char *fingerprint PROGMEM = "44 14 9A 3F C3 E9 F1 F3 84 1A B4 9F B6 4D 19 8A B2 92 31 D6";
...
...
void setup() {
    ...
    setup_wifi();

    espClient.setFingerprint(fingerprint);   // <-- Change #3: Set the SHA1 fingerprint
    // Alternative: espClient.setInsecure;

    client.setServer(mqtt_server, 8883);  // <-- Change #4: Set the port number to 8883
    client.setCallback(callback);
 ...

```

Good luck!

# Answer
> 2 votes
There is an example of client certificates here.

https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino

I believe the answer by @StarCat should be expanded to use the ca cert and client certs. With MQTT, we don't want clients being faked either.

---
Tags: esp8266, mqtt
---


# Question
Title: How can I operate the leds and neopixel strips together (at the same time)?
Here's the code I wrote:

```
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;

int numOfRegisters = 2;
byte* registerState;

long effectId = 0;
long prevEffect = 0;
long effectRepeat = 0;
long effectSpeed = 30;

#define LED_PIN    2
#define LED_COUNT 24

Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
  #endif

  strip.begin();           // INITIALIZE NeoPixel strip object (REQUIRED)
  strip.show();            // Turn OFF all pixels ASAP
  strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)

  //Initialize array
  registerState = new byte[numOfRegisters];
  for (size_t i = 0; i < numOfRegisters; i++) {
    registerState[i] = 0;
  }

  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  do {
    effectId = random(6);
  } while (effectId == prevEffect);
  prevEffect = effectId;

  switch (effectId) {
  case 0:
    effectRepeat = random(1, 2);
    break;
  case 1:
    effectRepeat = random(1, 2);
    break;
  case 3:
    effectRepeat = random(1, 5);
    break;
  case 4:
    effectRepeat = random(1, 2);
    break;
  case 5:
    effectRepeat = random(1, 2);
    break;
  }

  for (int i = 0; i < effectRepeat; i++) {
    effectSpeed = random(10, 90);

    switch (effectId) {
    case 0:
      effectA(effectSpeed);
      break;
    case 1:
      effectB(effectSpeed);
      break;
    case 3:
      effectC(effectSpeed);
      break;
    case 4:
      effectD(effectSpeed);
      break;
    case 6:
      effectE(effectSpeed);
      break;
    }
  }

  // Fill along the length of the strip in various colors...
  colorWipe(strip.Color(255,   0,   0), 1); // Red
  colorWipe(strip.Color(  0, 255,   0), 1); // Green
  colorWipe(strip.Color(  0,   0, 255), 1); // Blue

  // Do a theater marquee effect in various colors...
  theaterChase(strip.Color(127, 127, 127), 1); // White, half brightness
  theaterChase(strip.Color(127,   0,   0), 1); // Red, half brightness
  theaterChase(strip.Color(  0,   0, 127), 1); // Blue, half brightness

  rainbow(1);             // Flowing rainbow cycle along the whole strip
  theaterChaseRainbow(1); // Rainbow-enhanced theaterChase variant
}

void colorWipe(uint32_t color, int wait) {
  for (int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
    strip.setPixelColor(i, color);          //  Set pixel's color (in RAM)
    strip.show();                           //  Update strip to match
    delay(wait);                            //  Pause for a moment
  }
}

void theaterChase(uint32_t color, int wait) {
  for (int a=0; a<10; a++) {  // Repeat 10 times...
    for (int b=0; b<3; b++) { //  'b' counts from 0 to 2...
      strip.clear();          //   Set all pixels in RAM to 0 (off)
      // 'c' counts up from 'b' to end of strip in steps of 3...
      for (int c=b; c<strip.numPixels(); c += 3) {
        strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
      }
      strip.show(); // Update strip with new contents
      delay(wait);  // Pause for a moment
    }
  }
}

void rainbow(int wait) {
  for (long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
    for (int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
      int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
    }
    strip.show(); // Update strip with new contents
    delay(wait);  // Pause for a moment
  }
}

void theaterChaseRainbow(int wait) {
  int firstPixelHue = 0;      // First pixel starts at red (hue 0)
  for (int a=0; a<30; a++) {  // Repeat 30 times...
    for (int b=0; b<3; b++) { //  'b' counts from 0 to 2...
      strip.clear();          //   Set all pixels in RAM to 0 (off)
      // 'c' counts up from 'b' to end of strip in increments of 3...
      for (int c=b; c<strip.numPixels(); c += 3) {
        // hue of pixel 'c' is offset by an amount to make one full
        // revolution of the color wheel (range 65536) along the length
        // of the strip (strip.numPixels() steps):
        int hue   = firstPixelHue + c * 65536L / strip.numPixels();
        uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB
        strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
      }
      strip.show();                // Update strip with new contents
      delay(wait);                 // Pause for a moment
      firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames
    }
  }
}

void effectA(int speed){
  for (int i = 0; i < 16; i++) {
    for (int k = i; k < 16; k++) {
      regWrite(k, HIGH);
      delay(speed);
      regWrite(k, LOW);
    }

    regWrite(i, HIGH);
  }
}

void effectB(int speed) {
  for (int i = 15; i >= 0; i--) {
    for (int k = 0; k < i; k++) {
      regWrite(k, HIGH);
      delay(speed);
      regWrite(k, LOW);
    }

    regWrite(i, HIGH);
  }
}

void effectC(int speed){
  int prevI = 0;
  for (int i = 0; i < 16; i++) {
    regWrite(prevI, LOW);
    regWrite(i, HIGH);
    prevI = i;

    delay(speed);
  }

  for (int i = 15; i >= 0; i--) {
    regWrite(prevI, LOW);
    regWrite(i, HIGH);
    prevI = i;

    delay(speed);
  }
}

void effectD(int speed){
  for (int i = 0; i < 8; i++) {
    for (int k = i; k < 8; k++) {
      regWrite(k, HIGH);
      regWrite(15 - k, HIGH);
      delay(speed);
      regWrite(k, LOW);
      regWrite(15 - k, LOW);
    }

    regWrite(i, HIGH);
    regWrite(15 - i, HIGH);
  }
}

void effectE(int speed) {
  for (int i = 7; i >= 0; i--) {
    for (int k = 0; k <= i; k++) {
      regWrite(k, HIGH);
      regWrite(15 - k, HIGH);
      delay(speed);
      regWrite(k, LOW);
      regWrite(15 - k, LOW);
    }

    regWrite(i, HIGH);
    regWrite(15 - i, HIGH);
  }
}

void regWrite(int pin, bool state) {
  //Determines register
  int reg = pin / 8;
  //Determines pin for actual register
  int actualPin = pin - (8 * reg);

  //Begin session
  digitalWrite(latchPin, LOW);

  for (int i = 0; i < numOfRegisters; i++) {
    //Get actual states for register
    byte* states = &registerState[i];

    //Update state
    if (i == reg){
      bitWrite(*states, actualPin, state);
    }

    //Write
    shiftOut(dataPin, clockPin, MSBFIRST, *states);
  }

  //End session
  digitalWrite(latchPin, HIGH);
}

```

# Answer
This comes up ALL THE TIME. Don't use delay. Do a Google search on "arduino blinkwithoutdelay" and read one of the various write-ups on the subject.

Here's a writeup that looks pretty good:

https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing
> 2 votes

---
Tags: arduino-uno, led, neopixel
---


# Question
Title: 7 segment 4 digit not showing numbers 2,3 and 0
https://www.instructables.com/Using-a-4-digit-7-segment-display-with-arduino/

I used this link to make my circuit and I used this code also but some numbers like 2,3 and 0 doesn't display correctly.

# Answer
It looks like you have the center segment and the top left vertical segment reversed. For the image you show, if you switched the on/off states of those 2 segments, you'd see `1230`.

I don't know if the problem is in your code or in your wiring. The simplest fix would be to swap the pins for those 2 segments.
> 6 votes

---
Tags: arduino-nano, wires, 7-segment
---


# Question
Title: Why do I get different results when compiling the same code with different ide?
I have a basic code about reading true rms.I compiled the same code with arduino ide and atmel studio, then ran it in a proteus simulation.I'm trying to measure how long the read\_rms() function takes.

My mcu:attiny84

1.experiment)I have added board to arduino ide with board manager.And I chose attiny84 and internal 1Mhz from tools menu in arduino menu. The result was that the read\_rms() function took 23.25 milliseconds.

2.experiment)I compiled the same code without any changes in Atmel Studio.Device,attiny84 selected. The result was that the read\_rms() function took 44 milliseconds.

44 miliseconds vs 23.25 miliseconds. Why?

Note:The following settings are selected in the proteus.Internal RC Osc. 8 Mhz,and CKDIV8=Programmed.

My code:

```
#define F_CPU 1000000UL
#include <avr/io.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>
const uint8_t muxbits = 1<<MUX3 | 1<<MUX2 | 1<<MUX1 | 1<<MUX0;

void adc_init()
{
    ADMUX = 0;    //Vcc_ref_
    ADCSRA = (1<<ADEN)|(1<<ADPS1)|(1<<ADPS0); //adc_enable_and_prescaler_8_ 125000 Hz (1000000/8)
    //first_try
    ADCSRA |= (1<<ADSC);
    while ((ADCSRA & (1<<ADSC)) != 0);
}

uint16_t adc_read(uint8_t channel)
{
    ADMUX = (ADMUX & ~muxbits) | channel;
    // start_single_convertion
    ADCSRA |= (1<<ADSC);

    // wait for conversion to complete
    while ((ADCSRA & (1<<ADSC)) != 0);

    return (ADC);
}

double read_rms()
{
    uint16_t i=0;
    uint16_t a_data=0;
    uint32_t sum=0;
    float avarage=0;
    double rms=0;
    for(i=0;i<200;i++)
    {
        a_data=adc_read(1);

        sum=sum+(a_data*a_data);
    }
    avarage=(float)sum/200;
    rms=sqrt((double)avarage);

    return rms;

}

int main(void)
{

    DDRA|=(1<<7);
    PORTA &=~ (1<<7);
    adc_init();

    while(1)
    {

    read_rms();
    PORTA ^= (1<<7);// TOOGLE_PA7   for_measure_time_of_read_rms()_with_oscilloscope

    }
}

```

# Answer
> 1 votes
Different compilers produce different machine code.

As Majenko pointed out, the Arduino IDE's compiler, which happens to be GCC, uses `float` even when you write `double`.

The Atmel Studio creates `double` for `double`, using twice as much bits.

Calculating with more bits takes longer.

---
Tags: programming, arduino-ide, avr, adc, atmel-studio
---