# Question
Title: RFID-RC522 not working with Arduino Uno clone
I am using this library https://github.com/miguelbalboa/rfid, and using **DumpInfo.ino** from it:

```
/*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from a 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 a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 *
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 *
 * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
 * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
 * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
 * keep the PICCs at reading distance until complete.
 *
 * @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      SDA(SS)      10            53        D10        10               10
 * 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 <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init();     // Init MFRC522
    mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    // Dump debug info about the card; PICC_HaltA() is automatically called
    mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

```

When I connect everything correctly and upload that sketch, this shows up in my Serial Monitor:

I have tried this with another cheap Arduino Uno, I connected it exactly the same and scanned one card, everything works perfectly fine:

So I guess RC522 module is working fine, and there is probably issue with that Arduino Uno board.

What I tried next without any success is:

* Copy bootloader from working Arduino Uno to this Arduino Uno that is not working.
* Switch ATMEGA328P from working Arduino Uno to this Arduino Uno that is not working.

I tested all pins (on board that is not working) for PWM and Digital Output functionality with Firmata Test, and everything is fine in this test.

You can take a look on images of this Arduino Uno board here.

**So my question is: something is wrong with the board itself or I am doing something wrong?**

Thanks!

# Answer
Try using this code:

```
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>

#define SS_PIN 10
#define RST_PIN 9

#define SERVO_PIN 3
Servo myservo;

#define ACCESS_DELAY 2000
#define DENIED_DELAY 1000
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

void setup()
{
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();          // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522

  myservo.attach(SERVO_PIN);
  myservo.write( 70 );
  delay(7500);
  myservo.write( 0 );
  Serial.println("Put your card to the reader...");
  Serial.println();

}
void loop()
{
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "69 C8 E2 2A") //change here the UID of the card
  {
    Serial.println("Authorized access");
    Serial.println();
   myservo.write( 70 );
 delay(7500);
  myservo.write( 0 );

  }

 else   {
    Serial.println(" Access denied");

    delay(DENIED_DELAY);

  }
}

```
> 0 votes

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


title: aRest.io - how does it work?

text:
# Question
Title: aRest.io - how does it work?
With aRest.io you are able control your Arduino/Esp from all over the world - but how?

In the Client SourceCode (found here) you only find the PubSubClient, which is an MQTT client.

I'm assuming:

My Arduino can (during the aRest.h) subscribe to topics in my aRest.io dashboard (http://dashboard.arest.io/) and if I add something to the dashboard the aRest's Broker will inform my Arduino. But here is my error. How can the Broker contact my Arduino behind the firewall? Does the Arduino use hole punching? Is my attempt wrong?

# Answer
The Client contacts the broker and maintain the connection - waitung for topic to be updated.
> 0 votes

---
Tags: remote-control, iot, network
---


title: For what is used an ESC with a PWM?

text:
# Question
Title: For what is used an ESC with a PWM?
So I was reading a few questions on drone, and I reach this one.

It said that an ESC is used between the PWM Arduinno's port and the motor. I don't really understand what it means. According to what I understand, a PWM is a varying signal and you just need an electric relay to receive this signal so that the motor receives correct voltage.

However, in other article I read that there are many different ESCs, with firmware and many other parameters to be taken into account. It seems quite overkill for what a relay does, so I am wondering:

* What is inside an ESC?
* More important, what does it do with PWM signal that could not be achieved with a relay and is essential to command the motor?

# Answer
> 3 votes
An ESC is an Electronic Speed Controller. It's purpose is to control the speed and direction of a *Brushless DC Motor*.

A Bushless DC Motor ("BLDM") is not like other motors. You can't just provide it power and it will spin. Instead it is made up of three (or multiples of three) electromagnets along with a permanent magnet on the rotor. Energising these electromagnets in the right order at the right time (and the right amount, too) pulls the permanent magnet around in a circle, making the motor spin.

It's the ESC that has the job of controlling these electromagnets.

You provide a PWM signal as a digital speed indication. The ESC then interprets that as an indication of how fast you want the motor to turn, and excites the electromagnets in the right way to make that happen.

Oh, and no, you certainly never want to provide a PWM signal to a relay. A PWM signal switches hundreds, if not thousands, of times per second. A relay is capable of switching, at best, maybe 10 or 20 times per second. Relays don't drive motors. Motor drivers (or at the bare minimum, MOSFETs) drive motors.

---
Tags: motor, pwm, electronics, drone
---


# Question
Title: How to fill a triangle using the LCD5110 Graph library?
Good day! I'm currently trying to create a small 3D engine using C++, an Arduino UNO as well as a Nokia 5110 display with a library. Now I have successfully drawn a cube using triangles, but I want to fill the triangles to add proper lighting. My method for drawing triangles is the following:

```
LCD5110 lcd(8,9,10,12,11);

void DrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
 lcd.drawLine(x1, y1, x2, y2);
 lcd.drawLine(x2, y2, x3, y3);
 lcd.drawLine(x3, y3, x1, y1);
}

```

My library hasn't got a triangle draw or fill method unfortunately. I have no idea how I could fill a triangle so I hope for help.

Thanks in advance...

**NOTE:** Please keep it simple.

**NOTE NR.2:** I have already asked this question at StackOverflow but I haven't got a good answer so I will try it again.

# Answer
After tinkering around for hours I have finally found a great way to fill triangles! Here we go:

```
for(int x = x1; x<=x2; x++) {
    for(int y = y1; y<=y2; y++) {
     lcd.drawLine(x3, y3, x, y);
    }
}

```

Great!
> 0 votes

---
Tags: c++, lcd, display
---


title: missing /dev/ttyACM* on Ubuntu

text:
# Question
Title: missing /dev/ttyACM* on Ubuntu
I installed the Arduino IDE according to the arduino.cc instructions (invoking `install.sh`) rather than `sudo apt install ...`. The ports `/dev/ttyACM*` were present when the following Linux command is issued.

`ls -l /dev/ttyACM*`

This shows that the devices have membership in the `dialout` group. It is necessary to add myself as a user to the group `dialout`.

`sudo usermod -a -G dialout <username>`

I selected the board and the port and did a download which eventually completed but it seemed to take a long time. The program probably wasn't working since the program was to flash an LED at a 2 second period but the flash rate was definitely much faster so it seems the download did not work.

I deleted the IDE and reinstalled and the ports disappeared.

I have applied this fix for using the Arduino IDE on Linux.

From the description of the fix the instruction is to issue the following commands:

```
wget https://github.com/adafruit/Trinket_Arduino_Linux/raw/master/99-adafruit-boards.rules

sudo cp 99-adafruit-boards.rules /etc/udev/rules.d/

```

Next reboot Linux.

According to this page on Arduino for Linux there ought to be some devices at `/dev/ttyACM*` but mine are missing. What is the solution to this problem? I have replaced the USB cable and it makes no difference.

The board is Adafruit Feather 32u4 which has an ATmega32u4. The OS is Ubuntu 16.04.

# Answer
If the Arduino IDE does not show the port or does not allow you to select the port, load a known to be working program (such as Example \> Blink), start a download, and then double-click the board's reset button.

For the same advice plus extraneous information view this help page on the particular Feather, the 32u4 micro-controller board, which seems to suggest the use of a verbose download mode but that seems to be unnecessary because you can just try again if it failed. The verbose download mode is enabled in preferences. Even though it is unnecessary I eventually decided to always use the verbose download mode because it gives what appears, to me at least, more immediate and obvious feedback about success and failure.
> 1 votes

# Answer
> According to this page on Arduino for Linux there ought to be some devices at /dev/ttyACM\*

That is not the case. On a "traditional" Arduino board, like the Uno, you have two chips: the main MCU which you program, and a USB interface chip, which is pre-programmed with code to present a CDC/ACM interface to the computer (which it then creates a /dev/ttyACMx device for).

With the feather you don't have that. You have one single chip. That chip is both the USB interface and the chip that you program - and most importantly, it is *your* program that provides the CDC/ACM device *if you choose*. If your program doesn't provide a CDC/ACM device then the computer will never see one, so it will never create /dev/ttyACMx.

In general the Arduino core always adds a CDC/ACM device whether or not you ask for it, since it is often used to initiate a reset into the bootloader. However if your sketch stops working for whatever reason then the CDC/ACM port is no longer there.

The M0 on the feather has a neat trick though - if you reset the board with the reset button *twice* the startup code recognises that fact and forces it to run the bootloader. That bootloader then presents the needed CDC/ACM device to the computer allowing you to upload new code.

Of course, if your program that you upload then doesn't initialise its own CDC/ACM device, or crashes, the CDC/ACM device will not be presented until you do the double-reset trick again.
> 3 votes

# Answer
> /dev/ttyACM\* mine are missing.

I think that something udev rules issue, you can define another rules with add `Feather32u4.rules` and remove `99-adafruit-boards.rules` file before.

```
SUBSYSTEM=="usb", ATTRS{idProduct}=="0c9f", ATTRS{idVendor}=="1781", MODE="0660", GROUP="dialout"
ATTRS{idVendor}=="239a", ENV{ID_MM_DEVICE_IGNORE}="0"
ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"
SUBSYSTEM=="tty", ATTRS{idProduct}=="8011", ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"
SUBSYSTEM=="tty", ATTRS{idProduct}=="0011", ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"

```

after saved and copy your files to /etc/udev/rules.d/

```
sudo cp Feather32u4.rules /etc/udev/rules.d/

```

and then restart your udev

```
sudo reload udev

```

or,

```
sudo udevadm control --reload-rules
sudo udevadm trigger

```

don't forget to restart your service

```
sudo systemctl restart ModemManager.service

```

check again your port with following ll `/dev/tty*`, if it appear with named `/dev/ttyUSBx` or `/dev/ttyACMx` add a user to your group

```
sudo usermod -a -G plugdev <user>

```

also try to automatically reset button with add a delay into your sketch

```
while(!Serial){
  delay(1000);
}
Serial.begin(115200);

```

if it not showed port on `/dev/tty` list, try

* Enabled **verbose upload** in the Arduino Preferences.
* Open the Blink example.
* and add automatically reset above.

that will showed as the Bootloader COM/Serial Port with bootloading mode.

**If** didn't work, i advice install driver on Adafruit\_Driver Windows only using Wine or PlayOnLinux, and remove udev files. also check again your `/dev/tty*` list.

Hope this helps.
> 2 votes

# Answer
So I tried EVERYTHING... turns out my USB cable was a cheaper cable that didn't have the data pins in it. It is worth making sure your cable supports data transfer by plugging it into something else to make sure it w
> 1 votes

# Answer
`ttyACM*` didn't show up on my /dev/ also, but as soon as I changed the USB port I was working with, the arduino board started blinking differently. So I checked the IDE again and under `Tools` \> `port` \> `Serial Port` I saw ttyACM0 came up. Didn't make sense to me but it worked.
> 1 votes

# Answer
For my situation, where I'm using a custom Linux kernel, I was missing the **cdc\_acm** driver.

This excellent page on the Gentoo Wiki helped me find it: https://wiki.gentoo.org/wiki/Arduino
> 0 votes

---
Tags: ubuntu
---


title: MCU to MCU communication over UART

text:
# Question
Title: MCU to MCU communication over UART
What would be the best way to send the following information from one MCU to another?

Now I'm just sending the sentence over as is eg. Serial.print(sentence in here)

Example sentence: 1306,60.123456,50.123456,23.765382,40.897558,245,85,20.3,5,65,1500,0.9

Many thanks.

# Answer
It depends actually on your requirements what is 'best'.

If (transmission) speed is an issue, there are mainly some things you can do to improve this:

1. Increase the transmission speed (this depends on the distance of the wires and the noise).
2. Decrease the start/stop bits (this reduces the certainty the values will arrive ok)
3. Pack your data (takes more processing time possibly, and more programming work, but can be faster).

About the third option: since you are mostly sending values, you can make some improvements. So you can send them as float (by sending the float data, with the length of sizeof(float)). However, note there could be inaccuracies in the last digit.
> 1 votes

---
Tags: serial, arduino-mega, programming
---


title: Esp8266 Arduino WiFi Exception Error 29

text:
# Question
Title: Esp8266 Arduino WiFi Exception Error 29
Background: I know nothing about hardware.

I am writing a small project with **Arduino IDE**, **ESP8266 library**, and my board is **ESP8266 V3 ESP-12N F NodeMcu Lua CP2102**.

Now I get `Exception 29` and I don't know why.

Sketch and server code(**written in Python**) github link (I also posted the client and server code at the bottom)

---

```
Module: [NodeMCU 1.0 (ESP-12E Module)]
Flash Size: [4MB]
lwip Variant: [v2 Lower Memory]
Flash Frequency: [40Mhz]
CPU Frequency: [80Mhz]
Upload Using: [SERIAL]
Upload Speed: [115200]

```

---

Stack Dump:

```
Exception 29: StoreProhibited: A store referenced a page mapped with an attribute that does not permit stores
PC: 0x4000e1c3
EXCVADDR: 0x00000018

Decoding stack results
0x40100908: malloc(size_t) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\umm_malloc\umm_malloc.cpp line 511
0x40100b6e: calloc(size_t, size_t) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\umm_malloc\umm_malloc.cpp line 826
0x40100b60: calloc(size_t, size_t) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\umm_malloc\umm_malloc.cpp line 820
0x4020318b: loop_task(ETSEvent*) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 188
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x402109ff: tcp_output at core/tcp_out.c line 1259
0x4020216a: ClientContext::wait_until_sent(int) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 331
0x40100908: malloc(size_t) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\umm_malloc\umm_malloc.cpp line 511
0x402151c0: mem_malloc at core/mem.c line 210
0x4020f104: pbuf_alloc_LWIP2 at core/pbuf.c line 284
0x40214732: ip4_output_if at core/ipv4/ip4.c line 1550
0x4020fe90: tcp_write at core/tcp_out.c line 263
0x402031dc: __esp_yield() at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 100
0x4020378e: __delay(unsigned long) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_wiring.cpp line 54
0x4020230f: ClientContext::_write_from_source(DataSource*) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 464
0x4020239d: WiFiClient::write(unsigned char const*, unsigned int) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 364
0x40204c30: WiFiClient::write(unsigned char) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src\WiFiClient.cpp line 217
0x40201bc4: DataSource::~DataSource() at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/DataSource.h line 12
0x402026c9: WiFiClient::flush(unsigned int) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src\WiFiClient.cpp line 318
0x40201113: loop() at C:\Users\ptq00\Documents\Arduino\sketch_jan03b/sketch_jan03b.ino line 44
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x402032f4: loop_wrapper() at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 180

```

---

Sketch(Client) Code:

```
#include <ESP8266WiFi.h>

const char ssid[] = "luminous";
const char pass[] = "zxcv78()[]";

//Mac IP 192.168.1.101
//PC IP 192.168.1.103

IPAddress server(192,168,0,103);
int port = 12700;

WiFiClient client;

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

  Serial.begin(115200);
  Serial.println("");

  WiFi.begin(ssid, pass);
  delay(500);
  while(WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".../");
  }

  Serial.println("");
  //WiFi is connected

  if(client.connect(server, port)){
    Serial.println("connected to server");
  }

}

// 3s client read timeout. I set this value casually. The server has a 5s timeout when reading data from client.
const unsigned long clientTimeout = 3000;

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

  if(client.connected()){
    client.write(WiFi.RSSI());
    delay(100); // Add for nothing. Not sure if it's useful
    unsigned long timeout = millis();
    //Client timeout, if client can't reach the server, it should start to reconnect the server
    while(client.available() == 0){
      if (millis() - timeout >= clientTimeout){
        Serial.println(">>> Client Timetout !");
        client.stop();
        break;
      }
    }
    //Client is connected and has data to read
    //discard all data
    client.flush();
  }else{
    //Try to reconnect to the server
    client.connect(server,port);
    delay(500); // Add for nothing. Not sure if it's useful
    while(!client.connected()){
       //failed to reconnect
       Serial.println("Failed to reconnect...");
       delay(500);
       client.connect(server,port);
    }
    //succeed reconnecting
    Serial.println("Succeeded reconnecting..");
  }
}

```

Server Code:

```
import socket

HOST = '0.0.0.0'
PORT = 12700

catSafeZone = False
serverTimeout = 3

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1);
    s.bind((HOST, PORT))
    s.listen()
    print("Start listening")
    print("Device is not conncted")

    while True:
        conn, addr = s.accept()
        try:
            with conn:
                print("Connected by", addr)
                print("Cat is online")
                conn.settimeout(serverTimeout)

                # client won't try to disconnect on its own.
                # So we only need to capture connection timeout exception
                while True:
                    data = conn.recv(128)
                    if data:
                        if catSafeZone == False:
                            catSafeZone = True
                            print("Cat is in safe zone.")
                        conn.send(b'1')
                    else:
                        print("Unexpected condition")
                        print("Client disconnected on its own.")
                        raise Exception("server data NULL")

                    # Code that is used for wifi signal strength detection:
                    #
                    # if not data:
                    #     break
                    # wifiStrength = int.from_bytes(data, byteorder='big', signed=True)
                    # print(wifiStrength)

        except socket.timeout:
            print("!!!Cat is out of safe zone")
            # Warn user in some ways
            catSafeArea = False

# never reach here
print("Server shutdown")

```

# Answer
I fixed the problem. It turned out to be that the `flush` function in Arduino WiFi library has toally different meaning from the one that defined in **ESP8266WiFi librarry**.

From https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/client-class.html:

> `flush()` returning `true` indicates that output data have effectively been sent, and `false` that a timeout has occurred.

This acts more like a `flush` `stdout` buffer in a typical `C` program.

Then I replaced `client.flush()` with:

```
 while(client.connected() && client.available() > 0){
    client.read();
  }

```

And everything works well then.

---

And I use your code with a little bit modification.

```
#include <ESP8266WiFi.h>

const char ssid[] = "luminous";
const char pass[] = "xxxxxxxx";

IPAddress server(192,168,0,101);
int port = 12700;

WiFiClient client;

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

  Serial.begin(115200);
  Serial.println("");

  WiFi.begin(ssid, pass);
  delay(500);
  while(WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".../");
  }

  Serial.println("");
  //WiFi is connected

  if(client.connect(server, port)){
    Serial.println("connected to server");
  }else{
    Serial.println("Failed to connnect to server at setup().");
  }

}

int needToReconnect = 0;

void loop() {
  // put your main code here, to run repeatedly:
  while(!client.connected()){
       //failed to reconnect
       needToReconnect = 1;
       Serial.println("Failed to reconnect...");
       delay(500);
       client.connect(server,port);
  }

  // Use a flag to indicate if client was in reconnect procedure
  if(needToReconnect){
    Serial.println("Succeeded reconnecting...");
    needToReconnect = 0;
  }

  client.write(WiFi.RSSI());
  delay(100); // Add for nothing. Not sure if it's useful

  while(client.connected() && client.available() > 0){
    client.read();
  }

}

```
> 2 votes

# Answer
In your code there is a possibility that you stop the client and then flush it after. That could lead to the observed error.

```
// Client timeout, if client can't reach the server,
// it should start to reconnect the server
while(client.available() == 0)
{
  if (millis() - timeout >= clientTimeout)
  {
    Serial.println(">>> Client Timetout !");
    client.stop(); // <----- HERE is the STOP !!!!!!
    break;
  }
}
//Client is connected and has data to read
//discard all data
client.flush(); <-- Then a flush on a stopped client !!!!!

```

I have no chance to try the following code, so use it as an example of what I would suggest you could try out. Attention: I've grayed out the last IP number and the SSID and the password.

```
#include <ESP8266WiFi.h>

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

IPAddress server(192,168,0,XXX);
int port = 12700;

WiFiClient client;

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

  WiFi.begin(ssid, pass);
  delay(500);
  while(WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".../");
  }

  // New line after .../.../...
  Serial.println("");

  if( client.connect(server, port) )
  {
    Serial.println("connected to server");
  }

}

// 3s client read timeout. I set this value casually.
// The server has a 5s timeout when reading data from client.
const unsigned long clientTimeout = 3000;

void loop()
{
  while( ! client.connected() )
  {
     //failed to reconnect
     Serial.println("Failed to reconnect...");
     client.connect(server,port);
     delay(500);
  }

  client.write(WiFi.RSSI());

  // Add for nothing. Not sure if it's useful
  // PPK: Me too ;-)
  delay(100);

  unsigned long timemark = millis();
  // Client timeout, if client can't reach the server,
  // it should start to reconnect the server
  while( client.available() == 0 )
  {
    if (millis() - timemark >= clientTimeout)
    {
      Serial.println(">>> Client timed out !");
      client.stop();
      break;
    }
  }

  if ( client.connected() && client.available() > 0 )
  {
    // remove bytes in the read buffer
    client.flush();
  }
}

```
> 2 votes

---
Tags: esp8266
---


title: ESP32 seconds from epoch

text:
# Question
Title: ESP32 seconds from epoch
When using ESP8266 - getting seconds from epoch is done using

```
NTP.begin(NTPserver, 2, true);
delay(delay_tries);
time_t t = now();

```

while `t` stores amount of seconds from 1-1-1970.

When trying to do the same, using ESP32 - I cant get that numeric representation.

code below is from ESP32 example- updating time using NTP server ( process is done correct ). BUT when using `now()` yields 1970, as if NTP update has never occured.

How can I get time from Epoch ?

```
#include <WiFi.h>
#include "time.h"
#include <TimeLib.h>    <------- Added to original Code

const char* ssid       = "YOUR_SSID";
const char* password   = "YOUR_PASS";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

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

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

void loop()
{
  delay(1000);
  printLocalTime();
  Serial.println(now());   <-------- Added to original code
}

```

# Answer
to return 'epoch' seconds there is a function `time` in time.h

```
time_t now;
time(&now);

```

`time_t` is defined as `long`

this time is retrieved by the ESP32 SDK from NTP servers configured with ESP32 Arduino function `configTime`

EDIT: it is the standard C `time()` function
> 2 votes

---
Tags: esp32, time
---


# Question
Title: make EEPROM.h use custom eeprom partition
I created the below partition table for an esp32 and replaced the 'default\_8MB.csv' with it.

```
# Name,   Type, SubType, Offset,  Size, Flags
nvs,      data, nvs,     0x9000,  0x5000,
otadata,  data, ota,     0xe000,  0x2000,
app0,     app,  ota_0,   0x10000, 0x330000,
app1,     app,  ota_1,   0x340000,0x330000,
eeprom,   data, 0x99,    0x670000,0x1000,
spiffs,   data, spiffs,  0x671000,0x18f000,

```

After uploading a sketch, I confirmed that the partition table was correctly uploaded to the flash at address 0x8000, using `esptool.py --port /dev/ttyACM1 read_flash 0x8000 0x300 partition_table.bin && gen_esp32part.py partition_table.bin && cat partition_table.bin`.

Now my question is: what do I have to do so that the `EEPROM.h` library maps the eeprom emulation to the address that I have specified in the partition table? I naively assumed that `EEPROM.h` would automatically use the partition named "eeprom", which doesn't seem to be the case.

I uploaded the following test sketch to analyse the situation:

```
#include <Arduino.h>
#include <EEPROM.h>

String s="this is a unique string";

void setup(){
  EEPROM.begin(1024);

  for (uint32_t i=0;i<s.length();i++){
    EEPROM.write(i,s[i]);
  }
  EEPROM.commit();
  Serial.println("EEPROM stored");
}

void loop() {
  delay(10000);
}

```

After the sketch has stored my unique string I read the flash memory using esptool and expected to find the string at an offset of 0x670000, but that wasn't the case. Instead it must be stored somewhere else because I can retrieve the string in a different sketch.

One thing that is confusing me: I'm pretty sure that I once ordered ESP-WROOM32s with 4MB flash, but the esptool's auto-flash-detection states that my board has 8MB. Can this flash-detection be trusted or does it simply fail because I try to flash 8MB to a 4MB ESP32? What is supposed to happen if I created a partition table that exceeds the flash memory size? When I put a partition table at an offset of 10M the build process still doesn't fail (is that what should happen?).

My main question: which additional steps do I have to take to get my ESP running with a custom\_partion\_table.csv (beside creating the table) and when using "EEPROM.h"?

# Answer
> 2 votes
EEPROM on the ESP32 doesn't work like you would expect. It uses the SDK's "Non-Volatile Ram" storage system to store the data within the `nvs` partition. This works through a system of "Key / Value" pairs, and the data is stored as a "BLOB" (Binary Large OBject) for the key `eeprom` in the namespace `eeprom`.

Quite what the internal layout of the data within the partition itself is I have no clue (the SDK is closed source), but it won't just have your string located at the start of the partition - it will be at the start of the BLOB, wherever that happens to be in the partition.

The `eeprom` partition is no longer used. It's just wasted space.

> Can this flash-detection be trusted or does it simply fail because I try to flash 8MB to a 4MB ESP32?

I can't comment on that I'm afraid. I would have thought it would look at the chip's JEDEC data, but it may just look at the partition table information instead.

> What is supposed to happen if I created a partition table that exceeds the flash memory size?

Probably not a lot, since much of the partition table refers to data storage, or a (presently) unused OTA partition.

When you compile your code you're only compiling it for the partition in which it will reside (app0 for example). When you upload the code you are only uploading to that partition. Anything outside that range is irrelevant to the compilation / uploading.

> When I put a partition table at an offset of 10M the build process still doesn't fail (is that what should happen?).

As I mentioned, it won't care. The partition will not be accessible, since it doesn't actually exist, but it's just an entry in a table. The compiler doesn't know or care what it is.

---
Tags: arduino-ide, esp32, uploading, eeprom, flash
---


# Question
Title: Using MouseX in processing to control LEDs. Error in code - LEDs remain off
I am fairly new to processing and Arduino - I have a coursework deadline for both on Monday (6th January).

I am trying to write a script that uses the mouseX values to turn LEDs on and off. I haven't got any error messages on either of the scripts but currently, nothing happens to the LEDs (they remain off) when I move my mouse. I have tested the circuit with a simpler Arduino code and it is correct so there must be an error in my code!

I would be very grateful for some help. Thanks!

**Processing code:**

```
import processing.serial.*;
Serial port;
byte lightsOn;

void setup()
{
  size(600,300);
  port=new Serial(this,"/dev/cu.usbmodem1411",9600);
}

void draw()
{
  background(32,78,95);
  rect(300,0,300,300);
  noStroke();
  fill(185,215,216);

  lightsOn=byte(mouseX);
  port.write(lightsOn);

  println(lightsOn);
}

```

**Arduino code:**

```
#include <Servo.h>

Servo myservo;
int ledpinA=12;
int ledpinB=13;

void setup()
{
  Serial.begin(9600);
  myservo.attach(ledpinA&&ledpinB);
  pinMode(ledpinA,OUTPUT);
  pinMode(ledpinB,OUTPUT);
}

void loop()
{
  if(0<Serial.available())
  {
    int data = Serial.read();

  if (data>300)
  {
    digitalWrite(ledpinA, HIGH);
    digitalWrite(ledpinB, LOW);
  }
  else
  {
    digitalWrite(ledpinB, HIGH);
    digitalWrite(ledpinA, LOW);
  }
  }
}

```

# Answer
```
lightsOn=byte(mouseX);

```

A byte can be any number from -128 to 127 (Java has no concept of "unsigned" values). The Arduino will reinterpret that as a value from 0 to 255.

```
if (data>300)

```

255, the maximum value, can never be more than 300 - so this will *always* fail.

You need to re-think what data you are sending and how you want to send it.
> 1 votes

---
Tags: arduino-uno, led, processing-lang, mouse
---


title: Plant irrigation system

text:
# Question
Title: Plant irrigation system
I'm very new to the Arduino game I wanted to make a small auto watering system for my plants. I bought these items

* 5V 1 CHANNEL RELAY MODULE FOR ARDUINO PIC AVR DSP ARMB
* 9 VOLT BATTERY SNAP CONNECTOR B
* ARDUINO UNO R3
* CAMELION 9V BATTERY SUPER HEAVY DUTY
* PIN TO HOLE DUPONT 40 PIN 30CM ARDUINO JUMPER WIRE 12 INCH
* SOIL MOISTURE METER FOR ARDUINO.

I followed a video on youtube I attached the guys circuit diagram as well. After following instructions my pump wont turn on I also programmed it as well. Please help if anyone can show me how to rewire the device and codes or if I'm doing something wrong. Please help.

```
int Relay = 13;
int sensor = 8;
int val;
void setup() {
  pinMode(13,OUTPUT); //Set pin 13 as OUTPUT pin, to send signal to relay
  pinMode(8,INPUT); //Set pin 8 as input pin, to receive data from Soil moisture sensor.
}

void loop() {
  val = digitalRead(8);
  if(val == LOW)
  {
    digitalWrite(13,LOW); //if soil moisture sensor provides LOW value send LOW value to relay
  }
  else
  {
    digitalWrite(13,HIGH); //if soil moisture sensor provides HIGH value send HIGH value to relay
  }
  delay(400);
}

```

# Answer
I've seen so much fake projects from "Viral science". I'm not sure whether he/she simply don't know what he/she does or if he/she simply tries to trap people. This project is a race condition itself ;-).

Besides your battery is empty. I don't think it is a big problem to use a 9V block battery, but Gerben is right, it won't do its job for very long. Have you thought about using a LiPo or LiOn Accu and a Solar loader?

There are worse things I see:

The sensor is powered by 3.3V but you read the ON/OFF signal with a 5-Volt Pin. That could be a problem, if there are other voltage drops that lead to a signal the PIN can not recognize as HIGH. Check the documentation of the moisture sensor and if it allows 5V use 5V to power it. All sensors I have found on Google have at least a range from 3.3 Volt to 5 Volt.

Check the current consumption of the relay. It must not draw more current than the Arduino PIN can provide (40mA for the UNO). And, don't use PIN13 to switch the relay. There are so many others and PIN 13 is connected to the onboard LED, which draws 10 - 20 mA on its own.
> 1 votes

---
Tags: sensors, code-optimization, wire-library, system-design
---


# Question
Title: Can I force Arduino not to be powered by USB?
I'm building a 3D printer and I'm using an ATmega2560 + RAMPS board.

The whole thing is powered by an ATX PSU (12v for motors and stuff, 5v for the Arduino), but when I plug in my USB cable, I can't shut the printer down, as it switches over to USB power.

Is there a way to make the Arduino never use the USB power, only the external power source?

Thanks!

# Answer
The best way of doing this, if you want your USB connection to still work, is to remove the P-channel MOSFET `T1` from the board.

You can't just disconnect the power from the USB port since that power connection goes directly to `UVCC` on the ATMega16U2 chip. That is used to power the internal USB peripheral (it goes to a 3.3V regulator inside the chip) and without it the USB interface won't have power.

The USB power is connected to the main 5V rail through that transistor, so if you remove that transistor the 5V from the USB remains connected to the ATMega16U2, but is no longer connected to the rest of the circuit.
> 16 votes

# Answer
you could do this if you cut the trace for the 5V line from the USB connector to the rest of the board. if you place the mega underside up on a bench in front of you, with the USB facing towards you, i believe it should be the top left pin of the 4 USB pins, but you should double check that first.
> 3 votes

# Answer
Just modify your UBS cable to not provide power.
> 0 votes

---
Tags: arduino-mega, power
---


# Question
Title: UPDATE: Fault in processing code - doesn't receive correct data from Arduino
I am receiving data from an LDR which I am inputting into processing. The data seems to be received to Arduino correctly and I have looked at the data being sent via the serial monitor and it all seems correct. However, the data that is being received in processing doesn't reflect the data received by the LDR so I think I have done something wrong here but not sure what as I am fairly new to this all. (Please see image for what is printing in the processing serial monitor).

Any help identifying where I have gone wrong would be so so helpful!

**ARDUINO CODE**

```
int rval=0;
int lightval;

//Recorded minimum and maximum values
int minval=0;
int maxval=950;

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

void loop()
{
  rval = analogRead(1);
  //Serial.println(rval);
  rval=constrain(rval,minval,maxval);
  lightval=map(rval,minval,maxval,0,255);
  //Serial.println(lightval);
  Serial.write(lightval);
}

```

**PROCESSING CODE**

```
import processing.serial.*;

Splash paintsplash;
Serial port;

float value=0;

void setup()
{
  size(600,600);
  smooth();
  background(255);
  paintsplash= new Splash();
  port=new Serial(this, Serial.list()[6],9600);
  //printArray(Serial.list());
}

void draw()
{
  paintsplash.display();
  paintsplash.splash();
  delay(200);

  if(0<port.available())
  {
    value=port.read();
  }

  println(value);

  if(value<=75)
  {
    fill(255,137,132);
  }

  else if(value>75 && value<=125)
  {
    fill(32,78,95);
  }

  else
  {
    fill(183,215,216);
  }
}

```

**PROCESSING CLASS - PAINT\_SPLASH**

```
class Splash
{
  float x;
  float y;
  float size;

  Splash()
  {
    x=0;
    y=0;
    size=int(random(35));
  }

  void display()
  {
    //fill(255,137,132);
    noStroke();
    ellipse(x,y,size,size);
  }

  void splash()
  {
  float xcord=int(random(600));
  float ycord=int(random(600));
  pushMatrix();
  translate(xcord,ycord);

     for ( float i =3; i < 29; i ++)
     {
       float splashX = x + random(100);
       float splashY = y + random(100);

       ellipse(splashX,splashY,size-i,(size-i+random(3)));
     }

   popMatrix();
  }
}

```

# Answer
> 1 votes
You're sending your `lightval` twice - once as a textual representation of the number, and once as a character representing the lower 8 bits:

```
Serial.println(lightval);
Serial.write(lightval);

```

For example:

```
Q308
R304
Q306

```

If you take the 308 and AND it with 255 you get 52. 52 as an ASCII character is `R`.

So you print 308, including a newline, then you print "R". Then you print 304, which would be 48 after ANDing with 255 - which of course is a Q.

---
Tags: arduino-uno, serial, serial-data, processing-lang, data
---


# Question
Title: How should I customize UIPEthernet constants?
I am using UIPEthernet to get an Arduino Nano to drive an ENC28J60 Ethernet Shield for a UDP-based application. I'm customizing a number of its `#define` parameters to change default settings to save space, but I'm not sure I'm doing it correctly. It's clearly designed to facilitate per-sketch customization, but things aren't quite working for me, and I can't tell if it's me doing it wrong, or if the customization doesn't quite do what I'm expecting.

Specifically, the comments at the top of `utilities/uip-conf.h` say:

> uIP has a number of configuration options that can be overridden for each project. These are kept in a project-specific uip-conf.h file and all configuration names have the prefix UIP\_CONF.

So that sounds great - I've copied `uip-conf.h` into my sketch (into the top directory next to my other sources), adjusted it appropriately, and ... nothing changes.

Now, I'm #including `<UIPEthernet.h>` into my source files, and everything compiles using the Arduino IDE (v1.8.10). Looking in the library, I can see `<UIPEthernet.h>` includes `<utilities/uipopt.h>`, which in turn includes `"uip-conf.h"` (note the quotes). So I think it's intended to be picking up my local one. But it doesn't - it uses the original one from the library.

My understanding of `#include "example.h"` is that it looks for `example.h` relative to the *current file location*, (ie `<utilities/uipopt.h>`, so *utilities/*), so I'm actually seeing correct inclusion behaviour and now I don't see how this customization approach could ever work!

I tried adding the `#include "uip-conf.h"` to my own sources, and that sort of works for my sources, but of course doesn't affect the library `.cpp` files themselves which still see the original version.

I could probably drag the entire lib into my sketch and fix up the includes, but that seems like the wrong answer. It's extensively designed to be customizable. Do you know what steps need to be taken to do it please? (Or a pointer to some docs would be fine!) Thanks!

# Answer
Creating a copy of the include file in sketch folder will not work. At library compilation the source files of sketch are not included. The "" for include is "search first in the same folder as the including file".

The *project* in the description of use of uip-conf.h is UIPEthernet. It includes the UIP library by Adam Dunkels and configures it with this file.

---

A project with UIPEthernet library can configure the library with options in uipopt.h. Most of the options in uipopt.h are defined as

```
#ifdef UIP_CONF_UDP_CONNS
#define UIP_UDP_CONNS UIP_CONF_UDP_CONNS
#else /* UIP_CONF_UDP_CONNS */
#define UIP_UDP_CONNS    10
#endif /* UIP_CONF_UDP_CONNS */

```

this allows to define the value on compiler command line as -D. Most IDEs enable to set project defines in project settings. Arduino IDE does not enable this yet, because it doesn't have a project configuration file.

With Arduino IDE you can add defines for platform or for board definitions with build.extra\_flags in platform.local.txt or in boards.local.txt. Example for boards.local.txt for Arduino Mega:

mega.build.extra\_flags=-DUIP\_CONF\_UDP\_CONNS=20 -DUIP\_CONF\_MAX\_LISTENPORTS=30

platform.local.txt and boards.local.txt must be in boards package folder nect to platform.txt and boards.txt.
> 1 votes

---
Tags: library, sketch, enc28j60
---


# Question
Title: Reading multiple pins via registers on the Arduino Due
I would like to read multiple pins at once in Arduino Due via registers just like PINB, PINC, PIND of the arduino uno. I know that the pins will be scattered to multiple registers, but i deduce it would still be faster this way since there for sure there will be multiple pins on a single register rather than call digitalRead 40 times.

Arduino shared the documentation for what digital/analog pins corressponds to the what ports to the actual sam chip, i just need that snippet of code that reads via registers.

So if any can give me the equivalents to these, It would be greatly appreciated:

* DDRx - The Port C Data Direction Register - read/write
* PORTx - The Port C Data Register - read/write
* PINx - The Port C Input Pins Register - read only

# Answer
> 1 votes
You will find a good introduction on using port registers here. It also mentions some cons and pros of using port manipulation.

---
Tags: arduino-due
---


# Question
Title: Basketball board arduino endlessly transmitting shot scored
I've been working on trying to get this arduino project I found to work but I've been encountering some problems.

The project was designed for an Arduino mega 2560 but I've been using my UNO and breadboard for it along with the Software Serial library. I'm very, very new to working with Arduinos so if there are any basic things I might be missing please do mention them.

Components:

* Arduino UNO
* Bluetooth HC-05 module
* E18-D80NK Proximity Sensor
* Saeed Grove 420 Proximity Sensor
* 10k Ohm resistor
* Breadboard
* The included app in the above link

The issues I'm facing are

a)Initially, the proximity sensor would detect if I e.g. moved my hand infront of it and send the data to the app and it would increment the score and play the sound.

However, if I tried flicking the vibration sensor and not moving my hand infront of the proximity sensor, a miss wouldn't be recorded. Initially, even just flicking the proximity sensor would record a score as well, but later it would just do nothing.

b)I'm not sure what is the problem, but now nothing happens at all. The wiring and everything is all connected in the same way as before, but now even though the proximity sensor lights up if I move my hand infront of it, no scores are transmitted by the HC-05 module or anything. I have tried keeping the Serial Monitor open but nothing is printed on it.

Also, the code I've pasted below is after including the SerialSoftware library header and after deleting all the code for setting the LED lights which is still available in the link above. Problem B started occurring before I did this, so I don't think that has anything to do with it. Just didn't want to include the LEDs in my project.

Any help would be really appreciated, thank you!! If there's any information I've missed out on, please let me know.

Edit: Okay, so I had the RX and TX wires of the module in the incorrect sockets. The RXD of the hc-05 module is now in pin 11 and the TXD in pin 10. Data is being transmitted, but it just endlessly keeps incrementing the shots even if the proximity sensor isn't detecting anything. :/ Any suggestions?

Edit2: Alright, issue resolved. I hadn't set the correct baud rate in the Bluetooth setup portion. Should've been 9600.

```
#include <SoftwareSerial.h>
SoftwareSerial Serial1(10, 11); // RX, TX

//----------------------------------------------------------------------------//
// Filename    : Scoreboard.ino                                               //
// Description : Smart Basketball Scoreboard                                  //
// Version     : 1.1.0                                                        //
// Author      : Marcelo Avila de Oliveira <marceloavilaoliveira@gmail.com>   //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// DEFINITIONS                                                                //
//----------------------------------------------------------------------------//

// TURN ON DEBUG MODE
// #define DEBUG
// #define DEBUG_PROX
// #define DEBUG_VIBR

//----------------------------------------------------------------------------//
// CONSTANTS                                                                  //
//----------------------------------------------------------------------------//

// PINS
const int prox_pin = 2;
const int vibr_pin = 3;

// TIME
const unsigned long wait_interval = 3000;

//----------------------------------------------------------------------------//
// VARIABLES                                                                  //
//----------------------------------------------------------------------------//

// TIME
unsigned long wait_time;

// STATUS
boolean prox = false;
boolean vibr = false;
boolean wait = false;

//----------------------------------------------------------------------------//
// FUNCTIONS (SETTINGS)                                                       //
//----------------------------------------------------------------------------//

void setup() {
    // INITIATE PINS
    pinMode(prox_pin, INPUT);
    pinMode(vibr_pin, INPUT);

    // INITIATE SERIAL COMMUNICATION
    Serial.begin(9600);

    // INITIATE BLUETOOTH COMMUNICATION
    setup_bluetooth();

    #ifdef DEBUG
        Serial.println("Board is alive");
        Serial.println();
    #endif
}

void setup_bluetooth() {
    #ifdef DEBUG
        Serial.println("Setting Bluetooth");
        Serial.println();
    #endif

    Serial1.begin(38400);                   // Set baud rate
    Serial1.print("\r\n+STWMOD=0\r\n");     // Set to work in slave mode
    Serial1.print("\r\n+STNA=Arduino\r\n"); // Set name
    Serial1.print("\r\n+STOAUT=1\r\n");     // Permit Paired device to connect me
    Serial1.print("\r\n+STAUTO=0\r\n");     // Auto-connection should be forbidden here
    delay(2000);                            // This delay is required.
    Serial1.print("\r\n+INQ=1\r\n");        // Make the slave inquirable
    delay(2000);                            // This delay is required.
    while (Serial1.available()) {           // Clear data
        delay(50);
        Serial1.read();
    }
}

//----------------------------------------------------------------------------//
// FUNCTIONS (CHECK)                                                          //
//----------------------------------------------------------------------------//

void check_prox() {
    if (!prox) {
        if(digitalRead(prox_pin) == LOW) {
            #ifdef DEBUG_PROX
                Serial.println("Proximity detected");
                Serial.println();
            #endif

            prox = true;
            if (!vibr) {
                wait = true;
                wait_time = millis() + wait_interval;
            }
            set_shot(1);
        }
    }
}

void check_vibr() {
    if (!prox && !vibr) {
        if(digitalRead(vibr_pin) == HIGH) {
            #ifdef DEBUG_PROX
                Serial.println("Vibration detected");
                Serial.println();
            #endif

            vibr = true;
            wait = true;
            wait_time = millis() + wait_interval;
        }
    }
}

void check_wait() {
    if (wait && millis() > wait_time) {
        if (!prox) {
            set_shot(0);
        }
        reset();
    }
}

//----------------------------------------------------------------------------//
// FUNCTIONS (MIS)                                                            //
//----------------------------------------------------------------------------//

void set_shot(int mode) {
    // MODE:
    // 0 = WRONG SHOT (MISS)
    // 1 = RIGHT SHOT (SCORE)

    Serial1.print(mode);
    delay(1000);
}

void reset() {
    vibr = false;
    prox = false;
    wait = false;
}

//----------------------------------------------------------------------------//
// MAIN                                                                       //
//----------------------------------------------------------------------------//

void loop() {
    check_prox();
    check_vibr();
    check_wait();
}

```

# Answer
> 0 votes
Alright, issue resolved. I hadn't set the correct baud rate in the Bluetooth setup portion. Should've been 9600.

---
Tags: arduino-uno, softwareserial, hc-05, proximity
---


title: My gimbal program does not compile

text:
# Question
Title: My gimbal program does not compile
my code:

```
// Get Yaw, Pitch and Roll values
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    // Yaw, Pitch, Roll values - Radians to degrees
    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    // Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }
    // After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      // Control the servos according to the MPU6050 orientation
      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif

// Yaw, Pitch, Roll values - Radians to degrees
    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

// Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }

// After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      // Control the servos according to the MPU6050 orientation
      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }

```

it says ypr does not name a type

```
/*
   Arduino and MPU6050 Accelerometer and Gyroscope Sensor Tutorial
   by Dejan, https://howtomechatronics.com
*/
#include <Wire.h>
const int MPU = 0x68; // MPU6050 I2C address
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY, gyroAngleZ;
float roll, pitch, yaw;
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY, GyroErrorZ;
float elapsedTime, currentTime, previousTime;
int c = 0;
void setup() {
  Serial.begin(19200);
  Wire.begin();                      // Initialize comunication
  Wire.beginTransmission(MPU);       // Start communication with MPU6050 // MPU=0x68
  Wire.write(0x6B);                  // Talk to the register 6B
  Wire.write(0x00);                  // Make reset - place a 0 into the 6B register
  Wire.endTransmission(true);        //end the transmission
  /*
  // Configure Accelerometer Sensitivity - Full Scale Range (default +/- 2g)
  Wire.beginTransmission(MPU);
  Wire.write(0x1C);                  //Talk to the ACCEL_CONFIG register (1C hex)
  Wire.write(0x10);                  //Set the register bits as 00010000 (+/- 8g full scale range)
  Wire.endTransmission(true);
  // Configure Gyro Sensitivity - Full Scale Range (default +/- 250deg/s)
  Wire.beginTransmission(MPU);
  Wire.write(0x1B);                   // Talk to the GYRO_CONFIG register (1B hex)
  Wire.write(0x10);                   // Set the register bits as 00010000 (1000deg/s full scale)
  Wire.endTransmission(true);
  delay(20);
  */
  // Call this function if you need to get the IMU error values for your module
  calculate_IMU_error();
  delay(20);
}

void loop() {
  // === Read acceleromter data === //
  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value
  // Calculating Roll and Pitch from the accelerometer data
  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.58; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) + 1.58; // AccErrorY ~(-1.58)
  // === Read gyroscope data === //
  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
  // Correct the outputs with the calculated error values
  GyroX = GyroX + 0.56; // GyroErrorX ~(-0.56)
  GyroY = GyroY - 2; // GyroErrorY ~(2)
  GyroZ = GyroZ + 0.79; // GyroErrorZ ~ (-0.8)
  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
  gyroAngleY = gyroAngleY + GyroY * elapsedTime;
  yaw =  yaw + GyroZ * elapsedTime;
  // Complementary filter - combine acceleromter and gyro angle values
  roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
  pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;

  // Print the values on the serial monitor
  Serial.print(roll);
  Serial.print("/");
  Serial.print(pitch);
  Serial.print("/");
  Serial.println(yaw);
}

void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * 180 / PI));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * 180 / PI));
    c++;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 200;
  AccErrorY = AccErrorY / 200;
  c = 0;
  // Read gyro values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();
    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }
  //Divide the sum by 200 to get the error value
  GyroErrorX = GyroErrorX / 200;
  GyroErrorY = GyroErrorY / 200;
  GyroErrorZ = GyroErrorZ / 200;
  // Print the error values on the Serial Monitor
  Serial.print("AccErrorX: ");
  Serial.println(AccErrorX);
  Serial.print("AccErrorY: ");
  Serial.println(AccErrorY);
  Serial.print("GyroErrorX: ");
  Serial.println(GyroErrorX);
  Serial.print("GyroErrorY: ");
  Serial.println(GyroErrorY);
  Serial.print("GyroErrorZ: ");
  Serial.println(GyroErrorZ);
}

  Wire.beginTransmission(MPU);
  Wire.write(0x1C);                  //Talk to the ACCEL_CONFIG register (1C hex)
  Wire.write(0x10);                  //Set the register bits as 00010000 (+/- 8g full scale range)
  Wire.endTransmission(true);
  // Configure Gyro Sensitivity - Full Scale Range (default +/- 250deg/s)
  Wire.beginTransmission(MPU);
  Wire.write(0x1B);                   // Talk to the GYRO_CONFIG register (1B hex)
  Wire.write(0x10);                   // Set the register bits as 00010000 (1000deg/s full scale)
  Wire.endTransmission(true);
  */

  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value

  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.58; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) + 1.58; // AccErrorY ~(-1.58)

  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroX = GyroX + 0.56; // GyroErrorX ~(-0.56)
  GyroY = GyroY - 2; // GyroErrorY ~(2)
  GyroZ = GyroZ + 0.79; // GyroErrorZ ~ (-0.8)
  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
  gyroAngleY = gyroAngleY + GyroY * elapsedTime;
  yaw =  yaw + GyroZ * elapsedTime;

  roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
  pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;

void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * 180 / PI));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * 180 / PI));
    c++;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 200;
  AccErrorY = AccErrorY / 200;
  c = 0;
  // Read gyro values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();
    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }
  //Divide the sum by 200 to get the error value
  GyroErrorX = GyroErrorX / 200;
  GyroErrorY = GyroErrorY / 200;
  GyroErrorZ = GyroErrorZ / 200;
  // Print the error values on the Serial Monitor
  Serial.print("AccErrorX: ");
  Serial.println(AccErrorX);
  Serial.print("AccErrorY: ");
  Serial.println(AccErrorY);
  Serial.print("GyroErrorX: ");
  Serial.println(GyroErrorX);
  Serial.print("GyroErrorY: ");
  Serial.println(GyroErrorY);
  Serial.print("GyroErrorZ: ");
  Serial.println(GyroErrorZ);
}

```

We simply print the values on the serial monitor and once we know them, we can implement them in the code as shown earlier, for both the roll and pitch calculation, as well as for the 3 gyroscope outputs.

MPU6050 Pitch Roll and Yaw outputs

Finally, using the Serial.print function we can print the Roll, Pitch and Yaw values on the serial monitor and see whether the sensor works properly.

```
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    if (j <= 300) {
      correct = ypr[0];
      j++;
    }
    else {
      ypr[0] = ypr[0] - correct;
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif

    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    if (j <= 300) {
      correct = ypr[0];
      j++;
    }
    else {
      ypr[0] = ypr[0] - correct;
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }

```

# Answer
I know this is more of a comment but I can't do that yet.

This is for the code with wire.h at the top of the code.

I loaded your code into my arduino IDE and my line numbers reference those

1. You have lines 22-32 commented out.
2. The // at the end of line 40 may cause you problems.
3. If lines 41-43 the same that you have in void setup () the same then you have the program doing something over and over again, that has already been set up.
4. line 145 you have a lone \*/ that the compiler should have found.
5. Lines 136 to 178 are not inside {} are not being run. They also look very similar to what is inside your void loop()
6. Line 180 has the same `void calculate_IMU_error() {` as on line 80, which one is being ran?
> 1 votes

---
Tags: accelerometer
---


# Question
Title: op amp circuit single sourced from arduino power
Getting an audio signal from a 3.5mm jack amplified (non-inverted) and fed into analog in pin on a Mega 2560. I am having problems using a potentiometer as a variable resistor to adjust gain. I'm also getting a lot of noise (+/-10 units on the 0-1023 scale)

Circuit: \- The audio is from a mono 3.5mm jack, playing from my laptop (with audio split to my speakers). \- Audio goes through an op amp TL071, single sourced shared with arduino 5V \- The potentiometer is wired with 2 pins as a variable resistor. The pins are connected to ground and the inverting input (VCC-) \- Output signal from the op-amp is biased by 2.5V and seems to work fine.

I'm closely following the instructions here (https://www.instructables.com/id/Arduino-Audio-Input/) but with a TL071 op amp as a single sourced from the Arduino 5V power supply.

The potentiometer doesn't seem to make much difference; I can even unplug it and I still get some readings on A0. I'm misunderstanding how to 'rewire' the op-amp for a single supply, but I can't figure out what else I can do.

# Answer
> 0 votes
In case anyone is looking for a solution, I followed the TL071 manual (texas instruments) for an op-amp instead of using the diagram posted above. That signal then links into a bias.

The noise was coming from having 5V shared with the LED lights (WS2812B). Once I put them on a different circuit (shared ground) it was ok.

# Answer
> 0 votes
The TLO series don't work with 5v supply. They have also a reversal phase : that meens, when used in follower, it's output will go high when intut is lower than 3v... One can use an old LM324 or LM358, but output is not going up to VCC... OPA140 is a correct choice. Also, may be a link capacitor of 100µF between input and potentiometer is necessary : this avoids amplification of DC, gives a centered output, and will reduce noise due to DC paht in potentiometer.

---
Tags: audio, op-amp
---


# Question
Title: Continous running light with fading trail
In examples of FastLED library, there's the animation of a dot sweeping back and forth, with fading trails (file "DemoReel100", animation "sinelon"). How can I alter the code so instead of moving back, the dot begins at LED #1 again; so when using a LED ring, then the movement is continuous and circular. Since the code will be part of a more complex project with reading of button states etc, the animation code has to be non-blocking, i.e. `delay()` is not an option.

```
void sinelon()
{
fadeToBlackBy( leds, NUM_LEDS, 20);
int pos = beatsin16( 13, 0, NUM_LEDS-1 );
leds[pos] += CHSV( gHue, 255, 192);
}

```

# Answer
If you look at the surrounding methods, you'll see that 'fadeToBlackBy' will give a fading effect on anything you feed in. You'll want to locate method 'beatsin16' and then edit it yourself so that it doesn't bounce back but restarts the counter at the first LED. (hint: phase\_offset)

You'll find the code snippet you want to copy in lib8tion.h

```
/// beatsin16 generates a 16-bit sine wave at a given BPM,
///           that oscillates within a given range.
LIB8STATIC uint16_t beatsin16( accum88 beats_per_minute, uint16_t lowest = 0, uint16_t highest = 65535,
                               uint32_t timebase = 0, uint16_t phase_offset = 0)
{
    uint16_t beat = beat16( beats_per_minute, timebase);
    uint16_t beatsin = (sin16( beat + phase_offset) + 32768);
    uint16_t rangewidth = highest - lowest;
    uint16_t scaledbeat = scale16( beatsin, rangewidth);
    uint16_t result = lowest + scaledbeat;
    return result;
}

```
> 1 votes

---
Tags: programming, led-strip, sine-wave
---


title: Arduino recorder with SD card module

text:
# Question
Title: Arduino recorder with SD card module
Can any one suggest me best device in cheap rates to record audio in to SD-card and vice versa from the speaker......i want to record audio into the sd card like as feedback from customer

# Answer
For decent audio recordings, you need an external (16 or 24 bit, 44.1 KHz or more) ADC with at least two channels (stereo).

To save it to an SD, you can buy a so called SD data logger, they are very cheap. Not all SD cards are compatible so you might have to try several ones. The protocol used is SPI.
> 0 votes

---
Tags: esp8266, programming
---


title: json format in esp32 with arduino json

text:
# Question
Title: json format in esp32 with arduino json
I am using an ESP32 module for bluetooth connection and scaning wifi network. But I cannot format the json using arduinojson library in the way I want.

```
void scanWifiNetworks() {
  //creating json
  DynamicJsonDocument jsonDoc(1024);
  char jsonBuffer[512];
  JsonObject wifiJsonObject = jsonDoc.createNestedObject("wifiList");
  wifiJsonObject["ssid"];
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0) {
    Serial.println("no networks found");
  } else {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
//      Serial.print(i + 1);
//      Serial.print(": ");
//      Serial.print(WiFi.SSID(i));
//      Serial.print(" (");
//      Serial.print(WiFi.RSSI(i));
//      Serial.print(")");
//      Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");

      wifiJsonObject["ssid"] = WiFi.SSID(i);
      serializeJsonPretty(jsonDoc, SerialBT);
      serializeJsonPretty(jsonDoc, Serial);
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(60000);
}

```

The output is like this

```
scan start
scan done
5 networks found
{
  "wifiList": {
    "ssid": "quark"
  }
}{
  "wifiList": {
    "ssid": "Airtel_Zerotouch"
  }
}{
  "wifiList": {
    "ssid": "NETGEAR77"
  }
}{
  "wifiList": {
    "ssid": "Itobuz-technologies"
  }
}{
  "wifiList": {
    "ssid": "Nokia 6.1"
  }
}

```

what I want is something like that

{ "wifiList": { "ssid1": "quark1", "ssid2": "quark2" } }

I know I am looping in a wrong way but could not figure it out. if possible please pointing out the right direction will help a lot.

# Answer
> 2 votes
You are repeatedly overwriting the `ssid` property of the same object. Instead, you want to write different properties, like

```
wifiJsonObject["ssid" + String(i+1)] = WiFi.SSID(i);

```

Then, only serialize the document once, when it is complete.

That being said, I strongly concur with Juraj in that the correct way to represent a list in JSON (and `wifiList` is clearly meant to be a list) is by using an array:

```
void scanWifiNetworks() {
    DynamicJsonDocument jsonDoc(1024);
    JsonArray wifiList = jsonDoc.createNestedArray("wifiList");
    int n = WiFi.scanNetworks();
    for (int i = 0; i < n; ++i) {
        JsonObject wifiNet = wifiList.createNestedObject();
        wifiNet["ssid"] = WiFi.SSID(i);
    }
    serializeJsonPretty(jsonDoc, SerialBT);
    serializeJsonPretty(jsonDoc, Serial);
}

```

This should produce a JSON document that looks like this:

```
{
  "wifiList": [
    { "ssid": "quark" },
    { "ssid": "Airtel_Zerotouch" },
    { "ssid": "NETGEAR77" },
    { "ssid": "Itobuz-technologies" },
    { "ssid": "Nokia 6.1" }
  ]
}

```

---

**Edit**: Note that, if it's clear from the context (e.g. a request URL) that you are transmitting a list of WiFi networks, then you can get rid of the outer object and the "wifiList" label, and use the array as the JSON document:

```
[
  { "ssid": "quark" },
  { "ssid": "Airtel_Zerotouch" },
  { "ssid": "NETGEAR77" },
  { "ssid": "Itobuz-technologies" },
  { "ssid": "Nokia 6.1" }
]

```

As suggested by Jaromanda X, if you are never going to extend the inner objects with extra information, you can further simplify the document by removing those objects and just listing the SSIDs in the array:

```
[
  "quark",
  "Airtel_Zerotouch",
  "NETGEAR77",
  "Itobuz-technologies",
  "Nokia 6.1"
]

```

---
Tags: bluetooth, esp32, json
---


title: How to reset millis( )?

text:
# Question
Title: How to reset millis( )?
I am currently doing a school project. There you have to program a stopwatch with the Arduino. I wrote a program where millis starts. But when I press my start button, millis don‘t start from 0. Has someone an idea? Please let me know.

Ps: I‘m German, so I‘m sorry for my bad English

# Answer
> 2 votes
You don't. Instead you just remember what `millis()` was when you pressed your start button, then subtract that from whatever `millis()` is showing at any other point in the future.

---
Tags: arduino-uno, millis
---


# Question
Title: How can measure the 3-axis accelerations?
i'm a student who is studying the Arduino. I want to measure acceleration using arduino and any sensor. i looked at some acceleration sensors (ex, MPU6050, AXDL335), but they were just measuring gravity, not axial acceleration.

Could you tell me any sensor that can measure the axis-acceleration available with Arduino?

# Answer
There is no difference between gravity and other kinds acceleration. Gravity is the constant downward acceleration of ≈9.81 m/s². You cannot feel any difference between the force of gravity and the force you would experience on a surface without gravity that's accelerating upwards at 9.81 m/s².

You can use the gyroscope to keep track of the orientation of the sensor, so you know the downward direction of gravity, and can correct your accelerometer measurements for it.

The problem is that gyroscope orientation measurements are subject to drift. To correct the orientation for drift, the accelerometer is used (because it can measure the direction of gravity, so you know what the downward direction is). The accelerometer only measures the exact acceleration due to gravity if the sensor is not accelerating, of course, but that's most likely not the setup you're going to use an accelerometer in.

As you can see, this is kind of a chicken and egg problem.
Luckily, there are advanced sensor fusion algorithms and complementary filters available that combine the accelerometer and gyroscope measurements, and give you a pretty good approximation for both.
I've successfully used Madgwick's algorithm for a quadcopter.
Depending on your use case, you'll have to tweak some coefficients to indicate if you rely mostly on the gyro or the accelerometer data. The MPU6050 has a DMP that can run sensor fusion algorithms on the chip itself, so the Arduino doesn't have to deal with that.
> 1 votes

---
Tags: arduino-uno
---


title: execute if function in a timed loop

text:
# Question
Title: execute if function in a timed loop
I have a school project where I had to make a piece of code work for 1 minute and then return. I first used a RFID reader which didn't work for me so I decided to use the serial monitor. I did this through a switch function and if it was the correct number you had 1 minute to push in the buttons.

But now to the problem for me is that in the timed loop I made it can't look for if functions and because of that I can't look if the buttons are pressed. I hope it was a clear explanation and someone can help me. Thanks in advance.

# Answer
> 0 votes
As chrisl mentions, you should use `digitalRead`. Assign this to the correct variables:

```
switchState1 = digitalRead(…) // Fill in the correct pin here
switchState2 = digitalRead(…) // Fill in the correct pin here

```

Also, you can separate the first part of the `if`, so you get:

```
if (switchState1 == HIGH)
{
    if (switchState2 == HIGH)
    {
        digitalWrite(2, HIGH);
        digitalWrite(3, HIGH);
        digitalWrite(4, HIGH);
    }
    else if (switchState2 == LOW)
    {
        digitalWrite(2, LOW);
        digitalWrite(3, LOW);
        digitalWrite(4, LOW);
    }
}

```

Since the inner condition only depends on switchState2 and the pins are equal, you can write:

```
if (switchState1 == HIGH)
{
    digitalWrite(2, switchState2 == HIGH);
    digitalWrite(3, switchState2 == HIGH);
    digitalWrite(4, switchState2 == HIGH);
}

```

And you can use instead of the switchState2 a switchState2High (Boolean), and only check it when switchState 1 == HIGH.

```
if (switchState1 == HIGH)
{
    switchState2High = (digitalReadState(…) == HIGH);
    digitalWrite(2, switchState2High);
    digitalWrite(3, switchState2High);
    digitalWrite(4, switchState2High);
}

```

You also could use a for loop for the last part so you get:

```
if (switchState1 == HIGH)
{
    switchState2High = (digitalReadState(…) == HIGH);
    for (int pin = 2; pin < 5; pin++)
    {
        digitalWrite(pin, switchState2High);
    }
}

```

---
Tags: time
---


# Question
Title: How can I read this digital pin for Nano by using AVR's Atmel Studo?
How can I read digital pin 6 in AVR?

I set the pin as input as follows:

DDRD = B0100000; //this will set pin 6 as input

But how can I now digital read this pin?:

Another way of putting it: how can I convert this Arduino code to be used in Atmel Studio?:

digitalRead(DATA\_PIN);

Edit:

```
while (1) {

        unsigned long data = 0;//32 bit variable to store encoder data

        for (int i=0; i<25; i++) {//25 bit encoder data, first 12 bit is CCW count data and the rest 13 bit is the position angle data
        data <<= 1;//shift all read data left one bit
        PORTD &= ~(1 << 5);//clock pin goes low
        _delay_us(2);
        PORTD |= (1 << 5);//clock pin goes high
        _delay_us(2);

        data |= digitalRead(DATA_PIN);//cat the new read bit to the whole read data
        }

```

I want to use usual C code for AVR instead of using digitalRead above. data is an 32 bit array storing 25 bit encoder data. It is bit by bit filled by digitalRaed.

I think I found it:

```
while (1) {

        unsigned long data = 0;//32 bit variable to store encoder data
        uint8_t val;

        for (int i=0; i<25; i++) {//25 bit encoder data, first 12 bit is CCW count data and the rest 13 bit is the position angle data
        data <<= 1;//shift all read data left one bit
        PORTD &= ~(1 << 5);//clock pin goes low
        _delay_us(2);
        PORTD |= (1 << 5);//clock pin goes high
        _delay_us(2);

        if ( (PIND & (1 << PIND6)) == (1 << PIND6) ) {
            val = 1;
            } else {
            val = 0;
        }

        data |= val;//cat the new read bit to the whole read data
        }

```

# Answer
> 0 votes
1. Read the port state with PIND
2. Isolate the bit you want with `&`
3. Profit

```
if (PIND & 0b0100000) {
    val |= 1;
}

```

Or, as a ternary:

```
val |= ((PIND & 0b01000000) ? 1 : 0);

```

---
Tags: arduino-nano, digital, atmel-studio
---


title: String to float on Arduino

text:
# Question
Title: String to float on Arduino
I'm trying to convert a String to a float but I'm running into issues with precision, even with the Arduino's own String example I'm getting bad results.

Example 0: Input string: 1.234567 After conversion to float: 1.2345669

Example 1: Input string: 60.123456 After conversion to float: 60.1234512

Example 2: Input string: 9.876543 After conversion to float:9.8765430

Why is this happening and how do I get rid of this?

# Answer
You get this, because a float uses a certain number of bytes (I don't have an Arduino at hand), I think it is 4 bytes.

In these bytes, only a certain accuracy can be stored, so the least significant digits gets rounded (binary, resulting in different end digits).

Only for e.g. Arduino Due: You can use doubles instead, see https://www.arduino.cc/reference/en/language/variables/data-types/double/

You might check for the `strtod` function, but I'm not sure if it is handled by the Arduino:

https://www.techonthenet.com/c\_language/standard\_library\_functions/stdlib\_h/strtod.php

If this doesn't work, you can use a function to split the '.' and process the left/right part to convert to an unsigned long and combine it together. But if there are exponential and minus signs involved it might get more difficult.
> 2 votes

# Answer
There are two issues at play here:

## 1 – Limited precision of the float data type

A float has a precision of roughly 10−7, and any number that is not an exact float is supposed to be rounded to the nearest float. For example, the two floats closest to 1.234567 are
10356298 × 2−23 = 1.2345669269561767578125 and
10356299 × 2−23 = 1.23456704616546630859375.
The latter is the closest.

## 2 – Naive string to float implementation in the Arduino core

The Arduino core aims at being small and consume few resources. Sometimes it cuts corners, at the cost of accuracy. In this case, although a correct implementation is supposed to round 1.234567 *up*, because the nearest float is *above* that number, the actual implementation ends up rounding *down*. Thus you end up with roughly 1.234566927, which is off by 0.61 ULPs (units of the last place), instead of the expected error of 0.39 ULPs.
> 1 votes

# Answer
It seems that I must convert to string first then use atof.
> 0 votes

# Answer
If you are using atof() to convert the string to a floating-point number, you would only get 6 or 7 digits of precision. And the numbers in your examples already have that much precision.
> 0 votes

---
Tags: programming, string, float
---


# Question
Title: Hook Arduino up with thermal printer and power both externally
**Disclaimer:** *I have no connection to adafruit.*

A friend and me want to build a little project. We want to connect an arduino to a thermal printer and then print out little fortune-cookie like messages, when a button is pressed. The whole setup should not be stationary and thus we need external, mobile power like batteries.

Since this is our first time using an arduino as well as a thermal printer and we have no clue about electronics, I am asking for help to set everything up without frying the arduino or the thermal printer.

We are using a standart arduino uno rev3 and the Adafruit Tiny Thermal Reciept Printer.

First question: **Setting up the power supplies**

So the idea was to power the arduino via a 9v battery pack to it's 2.1mm DC port. I think this should work, right?

What I am confused about is the Adafruit Tiny printer. It says it takes 5-9 V, 1.5-2A. Can I just hook up a 9V battery packand clip the caples to the printer? Or what setup do I need so that the printer will recieve enough amperes when printing?

And how would I connect both tools to a single ( larger ?) battery pack? So that we can turn the power off easily?

Second question: **Finding a good button compatible with an arduino and setting it up in the project.**

So we have a gerneal idea of how things should work. Somehow we need to connect the button to the arduino which then can register a click via one of it's pins. This click I can then register with my code and from there on things get easy for me. But getting to this point is hard for us.

We don't know which buttons will work and neither how to connect it to the right pin. Which pin should we adress? Digital? Analog? Does the button need an external power supply as well? Since otherwise the arduino would not register a change of current on a pin, right? Or do we need to connect the button to the whole circuit?

*I do a lot of high language engineering and have no real idea about circuits and electronics and my friend is more of a craftsmen so we really appreciate your ideas, setups and help in general!*

I am not sure if this is too much to ask but a sketch of the whole setup with a single power source and button would be awesome! Thanks. Really!

# Answer
> Setting up the power supplies

As Gerben already stated in the comments, a 9V block battery isn't capable of supplying enough current for the thermal printer, so you cannot simply use one of them (these are meant for low power applications, like a smoke alarm). There are many different types of batteries, that you can use for this. Probably some kind of LiPo or LiIon pack would be suitable. (I'm sure you can find information about pros and cons of different battery types on the web). But the easiest way for you would be an USB power bank, that can supply at least 2.5A. A power bank incorporates mostly a LiIon pack and also already the mandatory smart charging electronics (to charge and discharge correctly and also to monitor the charge level), and - every important - a 5V voltage regulator. You can supply the 5V from the USB power bank directly to the Arduino and thermal printer in parallel. If you need to switch them on and off together (and the power bank doesn't already incorporate some kind of switch), you can use a simple switch between the positive lead from the power banks USB port and the positive leads for Arduino and printer.

> Finding a good button compatible with an arduino

**Every** normal button is compatible with Arduino. A button is nothing more as a switch, that automatically opens again, if you are not pressing it. Just two pieces of conductive material, that get's pressed together, if you press the button. A normal button has 2 pins (you might see more pins on the button, but mostly some of these are electrically connected together, so that you effectively have only 2 pins). Connect one pin to ground and the other to a digital input pin of the Arduino. Then in your sketch use `pinMode(pin_number, INPUT_PULLUP);` in your `setup()` function. This will enable the Arduinos internal pullup resistor, which pulls the pin to HIGH, if the button isn't pressed. If you press the button, the pin will be pulled to LOW. Keep this inverted logic in mind (LOW means pressed, HIGH not pressed).

There are also many button examples for Arduino on the web, since using a button is the second thing to learn with Arduinos (after blinking an LED). Button example code via `digitalRead()` is also incorporated into the Arduino IDE (look for examples in the menu).

> a sketch of the whole setup

Even, if someone wanted to write the code for you (and this is not a free coding service, so you cannot expect someone to simply do it), you haven't given us enough information, what behavior you want. But please don't add that here, to get this free code. What you are asking (single power source and button) is not difficult. Surely - currently you don't know much about this stuff, but it's not rocket science and there are many many Arduino tutorials on the web to help you. About the code for the thermal printer: Adafruit always provides dedicated guides for the devices they sell. There you can find a description, how the device works and is connected and used. They also provide example code and in most cases complete Arduino libraries, that hide most of the complexity of a task.

You should start by connection the Arduino to the power bank. Then you should go on and get the button going (you can write a sketch to turn the onboard LED on and off with it to learn how it works). Then you can connect the printer. Try adafruits example code. If it works, you can extend your sketch with the printers code.

---

Note: Some power banks turn of the power completely, if only a small current is flowing out of if. With such a power bank your Arduino might turn of as the power bank cuts the power. It normally does not draw enough current for the power bank. I think this shouldn't happen, when the printer is connected, but this depends on the current, that it draws (considering the minimal current, that it draws while idling), and the current, that is the minimal limit for your specific power bank.
> 0 votes

---
Tags: arduino-uno, power, battery, arduino-setup
---


# Question
Title: cast double to long leads to unexpected results
I wrote a little program to show my problem:

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

  double K=39.85;
  double a=K*100;
  Serial.print("a= ");
  Serial.println(a);

  long val_long = 0;
  val_long = a;
  Serial.print("val_long= ");
  Serial.println(val_long);
}

void loop() {
}

```

I get this back from my Arduino uno:

```
a= 3985.00
val_long=3984

```

I've been pondering for a long time and can't find the mistake! Why is the long value decremented by one? Can anybody help me please?

# Answer
The problem is that float numbers are seldom an exact representation. So the float is stored as the closest number that is exactly representable as a float, namely
10446438 × 2−18 = 39.84999847412109375.

When you multiply this by 100, you get 16322559 × 2−12 = 3984.999755859375.

And than casting to an int or long results in 3984, not 3985.

so whenever you cast a value from a float or double to an int or long, you always should add 0.5 (so all values from \[x - 0.5, x + 0.5) are rounded to x assuming x \>= 0, thus:

```
val_long = int(a + 0.5);

```

Beware of negative values, see therefore https://www.cs.cmu.edu/~rbd/papers/cmj-float-to-int.html

Better is to use the `round` function, see comment of Edgar Bonet below.

**UPDATE**

See comment of Lightness Races with Monica

In case it's not wanted to round up, but you still want 39.84999847412109375 to be 39.85, than you have to add a value that has the value of the least significant bit (actually slightly less but that is impossible to define). In most cases, it's best to add half the significance you want. So if you need two decimal accuracy, add 0.005.
> 7 votes

---
Tags: programming, data-type, convert
---