body: I have a problem, I am using 56V DC combined batteries system. I get ADC values comes to Arduino like 211, 217 etc... I have to find out when the DC volt drop to 42V. How do i know the digital value for the ADC from Aruino.

title: Arduino Analog to Digital Conversion from 56V DC Batteries

Answers: 2

body:
I'll assume you're using Li-Ion batteries in 14s configuration. You'll want to measure voltages up to around 60 V while charging. With a bit of safety margin, I'd set it up to measure up to 72V without damaging the Arduino - which can measure voltages up to 5 V, but the input on that pin should never exceed 5.5 V.

To bring your battery voltage down to something the Arduino can use, you'll need to use a voltage divider, as [chrisl suggested][1].

[![Schematic, allaboutcircuits.com][2]][2]

With R1 = 10 kOhm and R2 = 680 Ohm, you'd get readings up to an input voltage of 78 Volts.

With `analogRead()` returning values between 0 and 1023, your 42 V cutoff would be around 546.

  [1]: https://arduino.stackexchange.com/questions/72739/arduino-analog-to-digital-conversion-from-56v-dc-batteries#comment159022_72739
  [2]: https://i.stack.imgur.com/ZqJpf.png

body:
**Warning: this is going to get math-heavy**

Ok. So you have a battery with a voltage divider on it, and you are using the Aruino ADC to read the output of that voltage divider. And you want to "back-calculate" the battery voltage from the ADC reading.

First let's look at exactly what happens with a voltage divider and just how it works. For that we'll turn to good ol' Ohm's Law.

Rule number one is that two resistors in series *sum* their resistances. So if you have a 10kΩ and 680Ω resistor in series (as suggested in @towe's answer) the total resistance is 10680Ω.  We'll use this arrangement as our example.

Now Ohm's Law states that the current flowing through a resistive load is directly proportional to the voltage across it. So for a fixed resistance and a given voltage we can calculate the current that will be flowing through the resistors.  That formula is:

# ***I=V/R***

So for a voltage of 56V and a resistance of 10680Ω we can say that the current is 56/10680 amps - or about 5.24mA.

Great. But so what? Well, now we can reverse the formula and find the voltage across a given resistance for that specific current. Which we can do for, for example, the 680Ω resistor.  We know that the same current is flowing through both resistors (since they are in series), so flipping the formula around we get:

# ***V=I×R***

So at 0.00524 amps and 680Ω that's 0.00524×680 = 3.57V.  We can do the same for the 10kΩ resistor: 0.00524×10000 = 52.43V.  And oh look - if we add those two voltages together, what do we get? We get 56V. The resistors have divided the voltage into two portions.

You can combine those two formulae together to give you:

# ***VOUT = VIN × (R2 / (R1 + R2))***

And if we move the VIN to the left hand side we get:

# ***VOUT / VIN = (R2 / (R1 + R2))***

And that is known as the *transfer function*, or the ratio of the input to output voltage of the voltage divider.

For a 10kΩ (R1) and 680Ω (R2) resistor pair we get 680/10680 = 0.0637.

And that is the "magic number" we want to calculate back from the ADC to the battery voltage.  Whatever the voltage we read at the ADC the battery voltage is the reciprocal of that number times bigger (reciprocal is "one over the value").  The reciprocal of 0.0637 is 15.7.  So if you read the value from the ADC then convert that into a voltage relative to the internal reference voltage (approximately 5V for a normal Arduino) then multiply that voltage by 15.7 you will get your battery voltage.

So next is to get the ADC voltage. And again, it's all ratios.  The ADC gives you a number that is a ratio of the incoming voltage to the reference (5V) voltage.  At 1023 you get "5V minus 1 LSB", so about 4.995V. We don't need that kind of accuracy for this, really, so we'll just call it 5V.

Say you read 482 from the ADC, if you convert that into a voltage you take the ratio 482/1024 and multiply it by the reference voltage (1024 is the range of a 10-bit ADC - you would change that for other types of ADC):

# ***VIN = 482 / 1024 × 5 = 2.35V***

Multiply that by our "magic number" 15.7 and you get 36.95V - and that's the battery voltage.


body:
I am using MAC OSX Mojave and trying to program an Arduino UNO board. However, whenever I start the Arduino IDE, I only find one port in the ports section called: /dev/cu.Bluetooth-Incoming-Port.
When I select that, since there is no other option, I get the following error code on pressing 'Upload' button. The error code I receive is given in image. [![error msg on pressing upload][2]][2]

My programmer is ArduinoISP and the board is Arduino UNO
[![image of options in tools menu][1]][1]

Kindly help me resolve this issue.

Note
I have reinstalled CH34x drivers (latest version v.5)

  [1]: https://i.stack.imgur.com/zBJfN.png
  [2]: https://i.stack.imgur.com/T8ILa.png

title: Aruino UNO not getting programmed on MAC OSX

Answers: 0


body:
I'm building a single master multiple slave RS485 network for remote sensors on test equipment. I have the hardware built and working, and I can do a Serial.print on the master and have the slaves display the values received on their attached OLED screens. The goal is for the master to cycle through the slave addresses one by one and request data, then wait for the slave to respond (or timeout and register as a fail on the master's GUI).

The issue I have is that to work out if a packet is intended for a slave device I have to parse the entire packet, wait for start and end packets, and check the address. This means every device has to capture and check every packet on the network for its own address byte. If I compare on the fly I can exit the serial loop as soon as I know which device the packet is intended for, but the next received packet will just re-open the serial loop part way through transmission.

Other than disabling the RS485 transceiver between packets, is there an elegant way to solve this issue without massive overheads?

My hardware uses Arduino Nanos (master is currently an Uno but will be a piece of National Instruments hardware) and MAX13487 transceivers.

Thanks!

title: Arduino RS485 communication protocol - minimising overheads and best practice

Answers: 0


body:
I want to write an Arduino code, that runs on several different Boards. The code can perform digitalRead/Write operations, but the pin number will be set from the user/outside. I want to include a check, if the selected pin exists.

Is it possible, to read the amount of I/Os (digital and analog) of the Arduino the code is currently running on, to check if the users selection is in the given range? Or is it possible to check, if a certain pin number exists?

title: Read amount of I/Os in code

Answers: 2

body:
It depends on the core, but most provide the macro `NUM_DIGITAL_PINS` which tells you the number of digital pins the board has.  In general this doesn't equate to the actual number, but to one more than the highest number (there are boards with gaps in the pin number sequence).

So you can use:

    if (pinNumber < NUM_DIGITAL_PINS) {
        digitalWrite(pinNumber, HIGH);
    } else {
        Serial.println("Invalid pin number");
    }

In tandem with that you also usually have `NUM_ANALOG_INPUTS`.

body: The number of the GPIO pins available depends on how the chip is wired on the Arduino Board and which microcontroller one is running on. For example, an Arduino Uno with a ATMega328p chip has 14 Digital I/O pins, whereas an Arduino Mega 2560 with a chip has 54 digital I/O pins.


body:
I have some unused pins, should I connect them together and to the ground or leave them floating?

[![][1]][1]

  [1]: https://i.stack.imgur.com/g9Cyj.png

title: What to do with Arduino floating pins?

Answers: 3

body:
The simplest thing to do is set them to INPUT_PULLUP.  If you want a purely hardware solution then you could connect them to GND through some resistors (10kΩ or whatever you have in that kind of order of magnitude will do).

You don't want to just tie them directly to ground, and you don't want to link them directly together - that could lead to short circuits and dead IO ports if any of the pins happened to get set as output and HIGH in software.

body: Leaving them floating in most cases won't do any harm. Even touching the pins won't destroy anything. Tying extra external hardware is just unnecessary (though a 10k resistor would be harmless as well). Of course, you could also think about potential extra usages for those pins if you want to make your design a bit "future-proof". For example, adding 4k7 pull-up resistors to A4 and A5 and a connector could allow you to use the I2C interface for additional functions.

body: I saw instability with a kiosk audio player I built years ago, when I left the unused pins floating.  Once I grounded them through a 10k resistor, all was OK.  This was in a very dry environment so I suspect static was the problem.


body:
By using the following draft i decode the signals from an RF receiver

    #define CH1 2
    #define CH2 3
    #define CH3 4
    #define CH4 5
    #define CH5 6
    #define CH6 7

    int ch1Time, ch2Time, ch3Time, ch4Time, ch5Time, ch6Time = 0;
    void channels()
    {
      TCNT1 = 0;
      ch1Time = 0; ch2Time = 0; ch3Time = 0; ch4Time = 0; ch5Time = 0; ch6Time = 0;

      while ((PIND & ((1 << CH1) | (1 << CH2) | (1 << CH3) | (1 << CH4) | (1 << CH5) | (1 << CH6))))
      {
        if (PIND & (1 << CH1))
          ch1Time = TCNT1;

        if (PIND & (1 << CH2))
          ch2Time = TCNT1;

        if (PIND & (1 << CH3))
          ch3Time = TCNT1;

        if (PIND & (1 << CH4))
          ch4Time = TCNT1;

        if (PIND & (1 << CH5))
          ch5Time = TCNT1;

        if (PIND & (1 << CH6))
          ch6Time = TCNT1;
      }
    }

The issue is that i need also to use the 6 PWM's of the nano board.
So i thought of moving the channels 1-6 to the analog pins like so..

    #define CH1 A0
    #define CH2 A1
    #define CH3 A2
    #define CH4 A3
    #define CH5 A4
    #define CH6 A5

    while ((PINC & ((1 << CH1) | (1 << CH2) | (1 << CH3) | (1 << CH4) | (1 << CH5) | (1 << CH6))))
      {
        if (PINC & (1 << CH1))
          ch1Time = TCNT1;
    etc...

but it simply does not work. Any thoughts please?

title: Decoding RF receiver signals

Answers: 1

body:
I see two immediate problems:

1. The macros A0-A5 are the numbers 14 to 19, not the numbers 0 to 5 - so you're looking at (1 << 14) for CH1 not (1 << 0).
2. The analog pins are port C not port B, so you need to use `PINC` not `PINB`.
3. Your `ch?Time` variables should be `volatile`.


body:
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
    #include <SoftwareSerial.h>

    char Mob[20]="+923319020922";
    String stringGPS = "";
    String stringGPS1 = "";
    char c=0;
    int t=0,i;
    int buzzer = 9;
    int buttonState = 0;

    SoftwareSerial mySerial(10, 11); // RX, TX

    //const int buttonPin1 =9 ;
    int buttonState1 = 0;
    int helmetstate=0;
    const int relay=8;
    char inByte=0;

    void setup()
    {
      lcd.begin(20, 4);
      lcd.setCursor(0, 0);
      pinMode(relay, OUTPUT);
      pinMode(buzzer, OUTPUT);
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial2.begin(9600);
      digitalWrite(relay, LOW);
      delay(15000);
      lcd.print("Config modem....");

      Config();

      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Smart helmet      ");
    }

    void loop()
    {
      if(Serial2.available())
      {
        inByte = Serial2.read();
        //Serial.write(inByte);
        if(inByte=='A'||inByte=='B'||inByte=='C'){
        inByte=0;
        SMS(Mob);

        while(Serial2.available()>0)
        {
          i = Serial2.read();
        }
      }

      if(inByte=='D')
      {
        digitalWrite(relay, LOW);
        inByte=0;
      }

      if(inByte=='E')
      {
        digitalWrite(relay, HIGH);
        inByte=0;
      }
      else
      {
      }
    }

     //buttonState = digitalRead(buttonPin);
     // if (buttonState == LOW) {
     //Serial.print("ok");
     //lcd.clear();
     // lcd.setCursor(0, 0);
     //lcd.print("Sending msg       ");
     // lcd.setCursor(0, 0);
     //lcd.print("Smart helmet      ");
     // checkGPS();
     // SMS(Mob);

     //helmet();
     checkGPS();
     lcd.setCursor(0, 1);
     lcd.print(stringGPS1);
     //Serial.println(stringGPS1);
    }

    /*
    void helmet()
    {
      buttonState1 = digitalRead(buttonPin1);
      if (buttonState1 == HIGH)
      {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("SWITCH ON  .......    ");
        digitalWrite(relay, HIGH);
      }
      else
      {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("SWITCH OFF .......    ");
        digitalWrite(relay, LOW);
      }
    }
    */

    void checkGPS()
    {
      // Serial.print("check gps");
      // while (Serial.available())
      // {
      if (Serial.available()>0)
      {
       // c = Serial.read();
       // stringGPS  = c;
       //Serial.print(c);
       while (c != 'R')
       {
         c = Serial.read();
         // Serial.print(c);
       }
        // if (c== 'R')
        // {
        //   Serial.print(c );
             while(t!=41)
             {
               if (Serial.available())
               {
                 c = Serial.read();
                 stringGPS += c;
                 t++;
                 //Serial.print(stringGPS );
              }
      }
      stringGPS1= stringGPS.substring(15, 41);
      // Serial.println(stringGPS1);
      t=0;
      c=0;
      stringGPS = "";
        // }
      }
      }

    void SMS(char Mob[20])
    {
       digitalWrite(buzzer, HIGH);
       lcd.setCursor(0, 0);
       lcd.print("Sending msg       ");
       Serial1.print("AT+CMGS=\"");     // send the SMS number
       Serial1.print(Mob);/// Send mobile number
       Serial1.print("\"\r");
       delay(4000);
       Serial1.print(stringGPS1);// send the SMS Data
       Serial1.print("\r");
       delay(2000);
       Serial1.write(0x1A);  ///Ctrl+Z
       delay(1000);
       Serial1.write(0x0A);  ///Carrige return
       delay(1000);
       Serial1.write(0x0D);    ///line feed
       delay(1000);
       stringGPS1 = "";
       lcd.setCursor(0, 0);
       lcd.print("Smart helmet      ");
       digitalWrite(buzzer, LOW);
    }

    void Config()/////configuration for sim900
    {
      delay(4000);
      Serial1.print("ATE0\r"); ////Disable Echo
      delay(4000);
      Serial1.print("AT\r"); ///checking echo
      delay(4000);
      Serial1.print("AT+CMGF=1\r");///msg format
      delay(4000);
    }

when i run this code it give me error that serial1 was not decleared in the scope

title: serial 1 was not declared in the scope

Answers: 1

body:
The only **SoftwareSerial** you a declaring is `SoftwareSerial mySerial(10, 11); // RX, TX
`
(And you you didn't use it afterwards).

If the hardware serials `Serial1`, `Serial2` or `Serial3` are available
(and already declared in the `arduino.h` header depends on the board you are using.


body:
Pc and Mcore with bluetooth module are paired. The port is COM9 outgoing in PC. However, when I send message Arduino does not get anything. I just disconnect arduino from pc and write simple code in Mcore that turn on LED when input message is 1. However still nothing. These are the codes in python and arduino side:

    import time
    import serial

    port="COM9"          #This will be different for various devices,COM port.
    bluetooth=serial.Serial(port, 9600)         #Start communications with the bluetooth unit
    bluetooth.flushInput()      #This gives the bluetooth a little kick
    bluetooth.write(b'1')       #These need to be bytes not unicode
    bluetooth.close()          #Otherwise the connection will remain open until a timeout

Arduino code:

    char a;

    void setup()
    {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
    }

    void loop()
    {
    if(Serial.available()){a = Serial.read();}

    if (a == '1'){
      digitalWrite(13, HIGH);
      }

      else{
      digitalWrite(13, LOW);}

      delay(100);
    }

I have tried to install Pybluez for WIN10, however, there was error. Do you think that this is the reason?

Thanks in advance

title: MCore(Arduino) - Python bluetooth communication

Answers: 2

body: kindly add a serial print before the if statement(```if (a == '1')```) to see what value of a is recieved so we can debug it

body:
Probably because you never called `bluetooth.open()`.

What would be much easier to do is use [pySerialTransfer][1] and [SerialTransfer.h][2] to guarantee reliable and robust serial communication between Python and your Arduino.

pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE's Libraries Manager.

Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs and come with examples.

  [1]: https://github.com/PowerBroker2/pySerialTransfer
  [2]: https://github.com/PowerBroker2/SerialTransfer


body:
I'm trying to use SMS messages to turn a relay on/off but before doing that i need to have a password system before allowing the user to turn the relay on/off. Basically, you have to send the password to the GSM via SMS first, then have an option select of ON or OFF, which you also send to the GSM. I can already do the password and ON/OFF of the relay separately, but I'm having trouble trying to combine them together. Here is the code:
```
String _buffer;
String number = "+639562284415";
String textMessage;
String relayState = "HIGH";

int relay = 24;
int _timeout;

void setup() {
  pinMode(relay, OUTPUT);
  digitalWrite(relay, HIGH);

  Serial.begin(9600);
  Serial1.begin(9600);
  delay(1000);
  Serial.print("SIM900 ready...");
  Serial1.print("AT+CMGF=1\r");
  delay(100);
  Serial1.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
}

void loop() {
  if (Serial1.available() > 0) {
    textMessage = Serial1.readString();
    Serial.print(textMessage);
    delay(10);
  }
  if (passFlag == 0) {
    if (textMessage.indexOf("1231") >= 0) {
      commandList();
      passFlag++;
      if (textMessage.indexOf("ON") >= 0) {
        // Turn on relay and save current state
        digitalWrite(relay, LOW);
        relayState = "on";
        Serial.println("Relay set to ON");
        textMessage = "";
      }

      if (textMessage.indexOf("OFF") >= 0) {
        // Turn off relay and save current state
        digitalWrite(relay, HIGH);
        relayState = "off";
        Serial.println("Relay set to OFF");
        textMessage = "";
      }
    }
  }
}

void commandList() {
  Serial.println ("Sending Message");
  Serial1.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);
  Serial.println ("Set SMS Number");
  Serial1.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
  delay(1000);
  String SMS = "Enter your command!";
  Serial1.println(SMS);
  delay(100);
  Serial1.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  _buffer = _readSerial();
}

String _readSerial() {
  _timeout = 0;
  while  (!Serial1.available() && _timeout < 12000  )
  {
    delay(13);
    _timeout++;
  }
  if (Serial1.available()) {
    return Serial1.readString();
  }
}
```
Basically what happens with this code is that it succeeds with the password entry, but it somehow skips over the ON/OFF option select. Since I used a flag to increment the password entry (so it doesn't endlessly send me the "Enter your command" message), the loop completely stop after loop. I want to use `switch case` but I don't really know how to use it in this case. I don't really know how to best approach this problem, so if anyone can give some advice I would really appreciate it! BTW I'm using a SIM800L and Arduino MEGA for this

title: Using SMS to receive password, then to choose whether to turn the relay on or off

Answers: 0


body:
I'm trying to make a kernel for a macro-key maker, this is the starting page's code:

    char m[] = "What do you want to do? Type the following commands in this "
          "terminal:\nnew  --> Creates a new Keybinding\ndelete  --> Deletes a "
          "previous Keybind\nlookup --> Find what is bound to a key\n\nTurn off the "
          "switch to go back to the normal mode.";
    Serial.println(m);
    Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

When I run it, the screen displays:

    What do you want to do? Type the following commands in this terminal:
    new  --> Creates a new Keybinding
    delete  --> Deletes a previous Keybind
    lookup --> Find what is bound to a key

    Turn off the switch to go back to the normal mode.

 The last line is missing.  Is this a problem with object casting? `takenKeybind` is an `int`.

title: Line not printing int in Serial Monitor

Answers: 1

body:
You should never do this:

    Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

Yes, it *should* cope with it and append the strings, but that's really nasty even if it does work. And there is absolutely no call to ever do concatenation when printing to serial.

Instead just use:

    Serial.print(takenKeybinds);
    Serial.println(F("/64 Keybinds taken."));

Note also the use of the `F()` macro when printing a string literal. This keeps the string in flash and prevents it being copied to RAM, which is just wasteful.

The same with your big long string - it's wasting RAM, and if you never want to modify it, why have it in RAM? Better is:

    Serial.println(F("What do you want to do? Type the following commands in this terminal:"));
    Serial.println(F("new  --> Creates a new Keybinding"));
    Serial.println(F("delete  --> Deletes a previous Keybind"));
    Serial.println(F("lookup --> Find what is bound to a key"));
    Serial.println();
    Serial.println(F("Turn off the switch to go back to the normal mode."));


body:
I am currently carrying out a project where I am using an Arduino Mega2560, to recover data from two ultrasonics sensors (HC-SR-04).
For the purpose of my project, I must add HTTP requests to this, unfortunately the Arduino Mega2560 does not allow me to connect to a WIFI.
I contacted my school, they gave me an ESP32, but as far as I understand I will not be able to connect it to my Arduino 2560?
I also have an esp8266, I found the documentation for the code, but despite many attempts (ex: https://arduino.stackexchange.com/questions/30057/connecting-esp8266-to-mega-2056), I cannot connect, I cannot connect it to my MEGA 2560.

Anyone have any ideas / advice?

Regards,
David

title: ESP8266 + Arduino Mega

Answers: 0


body:
Ok. So I'm close to tearing me hair out on this one.

I have a batch of cheap Arduino Nano clones, that just straight up won't work. (I HAVE gotten one of them to work, but I suspect that was by pure coincidence)

Anyway, I feel like I've tried everything to make them work.
I am consistently getting

> Device signature = 0xffffff

errors from avrdude, which I believe is a hardware problem. Up til now I have tried:

 - Installed CH340 drivers, no difference
 - Tried to burn bootloader using Uno as an ISP (with 10uF cap between reset and ground!)
 - Tried the "(Old Bootloader)" option in the IDE

All I have left is to desolder the entire board and troubleshoot each single component, but... no, I want to keep my sanity intact, thaaank you!

Any ideas on how I should move forward here?

title: Arduino NANO (CH340) error while flashing bootloader

Answers: 1

body: Hit reset randomly in the first few seconds of uploading/burning.


body:
I'm trying to set up an ESP32 (DOIT ESP32 DEVKIT V1 in the Arduino IDE, with Espressif's WiFi libraries) with the following includes so far:
```
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <HTTPSServer.hpp>
#include <SSLCert.hpp>
#include <HTTPRequest.hpp>
#include <HTTPResponse.hpp>
```
Now, if I have a callback routine that's set up with
```
ResourceNode * nodeEchoPost = new ResourceNode("/cmd", "POST", &handleEcho);
```
how can I parse out the POST request string? On the serial console I get
```
[HTTPS:I] Request: POST /cmd
```
which is a debug output from the HTTPSRequest library itself. But I have no clue how to get that '/cmd' string for my own use!
I've tried the example code of
```
byte buffer[256];
size_t s = req->readBytes(buffer, 256);
```
getting a buffer that only returns garbage, probably because all the request is in the POST statement and the body is empty.

Since all I need is the request-info
```
'/cmd?command1=foo&command2=bar&etc'
```
to chop up and use, well.. how do I get that out from the library? I've been googling around, and looking in the library header files, without much luck.

Also, is there any advantage to using the WiFiClientSecure library instead, since everything already goes over HTTPS? That's more of a side question, though if it makes it easier to grab the Request string that way, I'm totally fine with accepting that.

title: ESP32 HTTPS server - how to get POST request string

Answers: 2

body:
I think I found the answer, by looking through examples in the github repo of Hessel's HTTPS library.

In short, this seems to be it:
```
void handleEcho(HTTPRequest * req, HTTPResponse * res) {

Serial.print("in handleEcho. request is:");
Serial.println(req->getRequestString().c_str());
```
Output from serial console:
```
"in handleEcho. request is:/cmd?command1=foo&cmd2=bar"
```
Now I have a plain-text string that I can use plain string commands on to chop up in parts with strtok or similar. I don't mind the extra hassle of finding keywords in the string, I'm happy to just have _gotten_ the damn thing.

Since I have all the data I want in that request, I'll just use req->readBytes as mentioned in examples to empty the buffer and discard all 'body' data.

And someone's gotta agree with me that adding the .c_str() to an already existing function just seems extra complicated. :/

body:
That's a GET and not a POST, so variables are accessible with

    auto params = req->getParams();
    std::string command1;
    std::string cmd2;
    bool hascommand1 = params->getQueryParameter("command1", command1);
    bool hascmd2 = params->getQueryParameter("cmd2", cmd2);

See example at
https://github.com/fhessel/esp32_https_server/blob/master/examples/Parameters/Parameters.ino

The `.c_str()` is required to transition from std::string to what println needs, not a problem related to the getRequestString() function itself

I came across this question while looking for ways to read actual POST variables, which is not documented (and the source code does not show sign of it)


body:
Im working on a sketch that needs to display some internal variable values and analogue reads in a simple webpage. The only catch is that it *needs* to be as reliable as possible.

Im getting some odd behaviour across multiple shields where the sketch will work briefly (sometimes as long as 5-6 minutes) before cutting out and setting the IP to something weird (commonly 0.0.0.0 or something similar)

My main loop has some other code in it for reading buttons, values, sensors, etc, but the bulk of it is basically

    void loop()
    {
      ... do some stuff ...
      // listen for incoming clients
        EthernetClient client = server.available();
        if (client) {
            Serial.println("new client");
            // an http request ends with a blank line
            boolean currentLineIsBlank = true;
            while (client.connected()) {
                if (client.available()) {
                    char c = client.read();
                    Serial.write(c);
                    // if you've gotten to the end of the line (received a newline
                    // character) and the line is blank, the http request has ended,
                    // so you can send a reply
                    if (c == '\n' && currentLineIsBlank) {
                        // send a standard http response header
                        client.println("HTTP/1.1 200 OK");
                        client.println("Content-Type: text/html");
                        client.println("Connnection: close");
                        client.println();
                        client.println("<!DOCTYPE HTML>");
                        client.println("");
                        // add a meta refresh tag, so the browser pulls again every 5 seconds:
                        client.println("<meta http-equiv=\"refresh\" content=\"5\">");
                        // output the value of each analog input pin
                        client.println(getStrDivByTag("MyWebPage", "h3"));
                        client.println("
");

                        client.println("");
                        break;
                    }
                    if (c == '\n') {
                        // you're starting a new line
                        currentLineIsBlank = true;
                    } else if (c != '\r') {
                        // you've gotten a character on the current line
                        currentLineIsBlank = false;
                    }
                }
            }
            // give the web browser time to receive the data
            delay(1);
            // close the connection:
            client.stop();
            Serial.println("client disconnected");
        }

      ... do some more stuff ...

    }

When the server is working as expected, my serial output gives me something like:

> new client

>GET / HTTP/1.1

>Host: 192.168.1.17

>User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:73.0)
Gecko/20100101 Firefox/73.0

>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

But just before it stops working, I get two back to back requests:

> GET / HTTP/1.1 Host: 192.168.1.17 User-Agent: Mozilla/5.0 (X11;

> Ubuntu; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0 Accept:

> text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

> Accept-Language: en-CA,en-US;q=0.7,en;q=0.3 Accept-Encoding: gzip,

> deflate Connection: keep-alive Upgrade-Insecure-Requests: 1

> Cache-Control: max-age=0

>

> client disconnected Current Draw: -0.341

> 192.168.1.17 new client GET /favicon.ico HTTP/1.1 Host:
192.168.1.17 User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux
x86_64; rv:73.0)

> Gecko/20100101 Firefox/73.0 Accept: image/webp,*/* Accept-Language:

> en-CA,en-US;q=0.7,en;q=0.3 Accept-Encoding: gzip, deflate Connection:
> keep-alive Cache-Control: max-age=0
>

> client disconnected Current Draw: -0.048

> 0.0.0.0

>Accept-Language: en-CA,en-US;q=0.7,en;q=0.3

>Accept-Encoding: gzip, deflate

>Connection: keep-alive

>Upgrade-Insecure-Requests: 1

>Cache-Control: max-age=0

>client disconnected

What is that request, something about favicon.ico? After these back to back requests, the IP resets to 0.0.0.0, sometimes jumping to something odd like 0.64.1.0, 0.1.0.64, etc.

Is there an issue with my network configuration, the ethernet2 library Im using?

title: Arduino Ethernet shield frequently drops its IP address

Answers: 1

body:
There are many Ethernet sketch examples that are not reliable at all. They basically handle the network setup in setup(), and the TCP connections in loop(). This is wrong. It just means that if there is anything wrong in your network connection, it won't restart correctly. You should check Ethernet.localIP(); and restart your sketch if it doesn't fit.
This routine should do the trick : void reset() { asm volatile ("jmp 0"); }

Also, you should be ready for requests for a favicon.ico from usual browsers (that's the small icon that comes in your tabs and favorites) and reply to it (you can use a 404 reply if you don't want to send a file). Providing a robots.txt is also good practice.


body:
I am using the library [**`SerialCommands`**](https://github.com/ppedro74/Arduino-SerialCommands) and I am just trying to print the first text message in the Serial Monitor. But this code does not work for some reason.

The expected result is that the Serial monitor prints a message ("Hello world !!") when I write "hello" and press "enter" as input. Is there something wrong or is this not working like I was expecting? Is there another way to check if these commands work? Is there anythin that I am missing?

    #include <SerialCommands.h>

    char serial_command_buffer_[32];
    SerialCommands serial_commands_(&Serial, serial_command_buffer_, sizeof(serial_command_buffer_), "\r\n", ",");

    void cmd_hello(SerialCommands* sender) {
      sender->GetSerial()->println("Hello world !!");
    }

    SerialCommand cmd_hello_("hello", cmd_hello);

    void cmd_unrecognized(SerialCommands* sender, const char* cmd) {
      sender->GetSerial()->print("ERROR: Unrecognized command [");
      sender->GetSerial()->print(cmd);
      sender->GetSerial()->println("]");
    }

    void setup() {
      Serial.begin(9600); // Serial comm begin at 9600bps
      serial_commands_.AddCommand(&cmd_hello_);
      serial_commands_.SetDefaultHandler(&cmd_unrecognized);
      Serial.println("Ready");
    }

    void loop() {
      serial_commands_.ReadSerial();
    }

title: How can I make the Serial Monitor work with the Serial Commands library?

Answers: 1

body: You defined, that every command will end with `\r\n`. So you need to choose "Both NL & CR" as line ending in the Serial monitor, so that it appends the line ending to your command. If you don't send the correct line ending, the library will think, that the command hasn't finished yet, and thus will do nothing, until it receives the correct line ending.


body:
i have a lot of tags (Animal tags rounded yellow) EM4305, this have 15 spaces of memory and i need change ID writed, currently i'm using this [module][1] but it did not can possible write on tag, exist a similar function to Write() from EEPROM, i see that already exist external writers to EM4305, but, is only external?

  [1]: https://www.googleadservices.com/pagead/aclk?sa=L&ai=DChcSEwiU6cankO_nAhVOBpEKHdvEAl8YABAFGgJjZQ&ohost=www.google.com&cid=CAESQOD2sm1tQSQkF0ISO-Jwj_Pw5zEjqQsV_eqxy0TJlpChx1eiepIa0LVX0Sj-UGt-MPNY_HI21kD7GGHT2ejgCZs&sig=AOD64_0LlaeH46FM4xIIfU2newmTSJIpTg&ctype=5&q=&ved=2ahUKEwikyMCnkO_nAhX1H7kGHfQtCvkQ9aACegQICxA6&adurl=

title: Is it possible to modify the animal tags (EM4305) with any module that works with Arduino? 134,2Khz

Answers: 0


body: I want to build a systems that measures if some parking spots are occupied or not. I chose to use an ESP8266 12-E NodeMCU Kit with multiple HC-SR04 ultrasonic sensors. In my project, it is essential to connect as many ultrasonic sensors to one ESP. Unfortunately, I have found out that if I connect the input/output of the HCSR04 to GPIO 10/9 and GPIO 1/3, The board can't boot. Can anyone explain to me why I cannot use those GPIO pins and what alternatives I have in order to connect more sensors to the ESP (other microcontrollers, pin extenders etc.)?

title: ESP8266 GPIO limitations with HC-SR04

Answers: 0


body: Connecting MPU6050 with Arduino without using A0-A5 pins.

title: How to connect MPU6050 with Arduino Uno without using A0-A5 pins?

Answers: 1

body:
You could use a Software I2C library, like [this one on github][1], which can be used on almost any pin of a board. But keep in mind, that doing such communication in software imposes some limits (for example the linked library can only be a master). Keeping it in hardware is often the better choice, depending on your requirements.

  [1]: https://github.com/felias-fogg/SoftI2CMaster


body:
I am having diffuclt times with this sensor, so I kndliy ask for your help!
The sensor is named "SPUVA-CS-C3535-A", datasheet here.
The sensor I use (cs3535) has just two pins (+ and -).
From my undesrstanding the ouput is a current corresponding on the UV light exposed to this sensor.
Max value of the current is difficult to understand from the datasheet that also do not have a typical suggested circuit. It seems that a medium value is 200nA, it seems really low!
I have connected (+) of the sensor to 3.3V, (-) of the sensor to A0, and a 220ohm resistor from A0 to Gnd. But readings are always 0.
Any help would be really appreciated! Thanks

title: Reading sensor with current ouput with Arduino

Answers: 1

body:
The "sensor" is just a photodiode that is sensitive to UV. You use it the same as any photodiode.

The simplest (and crudest) way is to use a very large (eg 1MΩ) pullup resistor to 5V on an ADC pin, then connect the sensor (reverse biased) between the ADC pin and GND.


body:
Right now I'm programming an Arduino Uno Rev3, I'm using a Sensor Shield v5 *(image at the bottom)* to be able to have several Ultrasonic sensors and Servos. Right now I'm thinking about getting a [Nucleo][2] board, due to the better CPU, more memory and more flash. Although on the page, Arduino compatibility is listed, I don't quite understand what it means in my case. I understand that it has the same pins as the Arduino, but can I be sure that my Sensor Shield (v5) will work?

I found too little resources about this, one concern was that Arduino and Nucleo board have separate needs (3V or 5V), but the Sensor Shield can get power separately. (Lower right corner.)

Also, there is a [Bluetooth shield][3] for the Nucleo, I will buy it if I buy the Nucleo board, how can I know that it will work with the Sensor Shield? Or how can I know how many shields can I connect to a Nucleo or an Arduino?

[![Sensor Shield][1]][1]

  [1]: https://i.stack.imgur.com/jHvw1.jpg
  [2]: https://www.st.com/content/st_com/en/products/evaluation-tools/product-evaluation-tools/mcu-mpu-eval-tools/stm32-mcu-mpu-eval-tools/stm32-nucleo-boards/nucleo-f446re.html
  [3]: https://www.st.com/en/ecosystems/x-nucleo-idb05a1.html

title: Using Arduino Sensors with STM32 based NUCLEO boards

Answers: 0


body:
I'm trying to print the information, which is received from the other ESP32 by CAN transceiver, on an OLED. The CAN bus is working perfectly, as the 'HELLO WORLD' is already be received. But I can't print the received 'HELLO WORLD' on OLED (also the OLED is work). The code shows below,
<!-- language-all: lang-cpp -->

    #include <CAN.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>

    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 32 // OLED display height, in pixels

    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

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

      if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
        Serial.println(F("SSD1306 allocation failed"));
        for (;;);
      }
      delay(2000);
      display.clearDisplay();
      display.setTextColor(WHITE);

      Serial.println("CAN Receiver");
      CAN.setPins(16, 17);
      // start the CAN bus at 500 kbps
      if (!CAN.begin(500E3)) {
        Serial.println("Starting CAN failed!");
        while (1);
      }
    }

    void loop() {
      // try to parse packet
      int packetSize = CAN.parsePacket();

      if (packetSize) {
        // received a packet
        Serial.print("Received ");

        if (CAN.packetExtended()) {
          Serial.print("extended ");
        }

        if (CAN.packetRtr()) {
          // Remote transmission request, packet contains no data
          Serial.print("RTR ");
        }

        Serial.print("packet with id 0x");
        Serial.print(CAN.packetId(), HEX);

        if (CAN.packetRtr()) {
          Serial.print(" and requested length ");
          Serial.println(CAN.packetDlc());
        } else {
          Serial.print(" and length ");
          Serial.println(packetSize);

          // only print packet data for non-RTR packets
          while (CAN.available()) {
            Serial.print((char)CAN.read());
          }
          Serial.println();
        }

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

      display.clearDisplay();

      display.print((char)CAN.read());

      display.display();
    }

title: How can I display text on OLED?

Answers: 1

body:
Just guessing but looks to me like you read the `CAN` message and print it character by character to the Serial console but you don't save those characters in a buffer as you get them from `CAN.read()`.

So when you then try to `display.print((char)CAN.read());` at that point there are no more characters to available for the `CAN.read()` to read so nothing is printed by the `display.print()`.

So what you need to do is to read the characters into a buffer so that you save them after reading them so that you can use the text string for other purposes.


body:
I am attempting to control a Folinn VFD (Manual: [Manual][1]) with an Arduino Uno via a MAX485 module [such as this][2].

 - Pins for MAX485:
    - DI > D8
    - DE & RE > D10
    - RO > D11

VFD settings:

   - F00.01 set to 2
   - F00.06 set to 9
   - F13.00 set to 1
   - F13.01 set to 5
   - F13.02 set to 3

At this stage I am attempting a very simple code just to turn the VFD on:

    /*

       ModBus RTU control VFD

       Address               : 01H  (is the address of the VFD)
       Function              : 06H  (write function code)
       Starting data address : 20H
                             : 00H  (2000H  is the address of control command)
       Data(2Byte)           : 00H
                             : 01H  (0001H is forward command)
       CRC CHK Low           : 43H
       CRC CHK High          : CAH

    */

    #include <SoftwareSerial.h>

    #define SSerialRX        11  //Serial Receive pin
    #define SSerialTX        8  //Serial Transmit pin
    #define SSerialTxControl 10   //RS485 Direction control
    #define RS485Transmit    HIGH
    #define RS485Receive     LOW
    #define Pin13LED         13

    // From manual vfd Forward command = 01H 06H 2000H 0001H 43CAH

    byte request1[] = {0x01, 0x06, 0x20, 0x00, 0x00, 0x01, 0x43, 0xCA};

    SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
    byte byteSend;

    void setup()
    {
      // Start the built-in serial port, probably to Serial Monitor
      Serial.begin(9600);
      Serial.println("SerialRemote");  // Can be ignored

      pinMode(Pin13LED, OUTPUT);
      pinMode(SSerialTxControl, OUTPUT);

      // digitalWrite(SSerialTxControl, RS485Receive);  // Init Transceiver

      RS485Serial.begin(9600);

    }
    void loop()
    {
        digitalWrite(SSerialTxControl, RS485Transmit);
        RS485Serial.write(request1, sizeof(request1));

    }

With the MAX485 connected to the correct ports (S+ and S-) on the VFD, this current setup receives no response is someone able to spot where I am going wrong? I have taken the values for CRC CHK Low & High from a different example, is this the issue?

Have also tried setting F00.01 to an unlisted '3' setting that I have seen pop up in other discussions but this made no difference. Any advice would be much appreciated, let me know if I can supply further details.

(I chose this method based on [this example][3]

  [1]: https://cononmotor.com.au/wp-content/uploads/2017/09/BD600-Manual.pdf
  [2]: https://www.ebay.com.au/itm/RS485-Transceiver-Communication-Module-MAX485/283525020751?hash=item4203687c4f:g:DcoAAOSwebpdDuuf&frcectupt=true
  [3]: https://forum.arduino.cc/index.php?topic=663365.0

title: Controlling VFD with ModBus RTU via RS485 and Arduino

Answers: 1

body:
User on other site (https://forum.arduino.cc/index.php?topic=663365.0) Might have default run conditons on VFD set differently or by hardware.

Check the VFD is listening to the ModBus Comms.  OK.

Check VFD is 'Ready to Run'. Hardwire e-stop or 'Active' inputs.
F00.22 Check Binding source
F00.05 Check Set min Hz
F01.01 Check Set min Hz

Give drive MIN Hz So when received RUN signal has default speed to goto.

Are you doing a Hard Reset on the UNO every time you want to send the Modbus string? Code runs once, does not actively transmit.


body:
I am currently hooking up my arduino to an adafruit mini thermal printer. When a button is pressed, some code is executed which then sends some information to the thermal printer.

Everything works fine except the thermal printer print is very weak and can barely be seen as soon as the printer needs to print more than 3-5 chars. Any ideas why? Both, the arduino and the thermal printer are hooked up to 9V batteries.

Here is the code
```cs
#include "Adafruit_Thermal.h"

// Here's the new syntax when using SoftwareSerial (e.g. Arduino Uno) ----
// If using hardware serial instead, comment out or remove these lines:

#include "SoftwareSerial.h"
#define TX_PIN 6 // Arduino transmit  YELLOW WIRE  labeled RX on printer
#define RX_PIN 5 // Arduino receive   GREEN WIRE   labeled TX on printer

SoftwareSerial mySerial(RX_PIN, TX_PIN); // Declare SoftwareSerial obj first
Adafruit_Thermal printer(&mySerial);     // Pass addr to printer constructor

int buttonIn = 8;
int val = 0;

void setup() {
  pinMode(7, OUTPUT);
  digitalWrite(7, LOW);

  pinMode(buttonIn, INPUT);

   mySerial.begin(19200);  // Initialize SoftwareSerial
   //Serial.begin(19200); // Use this instead if using hardware serial
   printer.begin();        // Init printer (same regardless of serial type)
}

void loop() {
  // put your main code here, to run repeatedly:
     val = digitalRead(buttonIn);
     if(val == HIGH)
     {
        printer.println("test");
        printer.sleep();      // Tell printer to sleep
        delay(3000L);         // Sleep for 3 seconds
        printer.wake();       // MUST wake() before printing again, even if reset
        printer.setDefault();

     }
}
```
Did I set up anything false? Is the power supply not enough?
The adafruit was sent with a selftest from the seller where everything seemed to be fine.

Left, seller test, second from left, my selftest, third and fourth from left are example printer and charset tests.

[![enter image description here][1]][1]

And here you can see how everything is wired together.

[![enter image description here][2]][2]

Thank you very much!

  [1]: https://i.stack.imgur.com/EkVc1.jpg
  [2]: https://i.stack.imgur.com/NwnLR.jpg

title: Adafruit thermal printer prints weak

Answers: 2

body:
The datasheet states:
Requires 5-9VDC @ 1.5Amp power supply during print.

In my experience this printer provides best results when operated at its upper limit. I am using a 9V 2A power supply for that. A bettery is definitiverly not enough.

body:
Proper care of your thermal transfer printer is critical to keeping it at peak performance for as long as possible. Keep reading for five tips to keep your thermal transfer printer running optimally so you don’t have to spend on unnecessary new parts or wasted media down the line.

1. Maintain The Right Heat And Speed Ratio
These two things are true:

High print speeds can improve throughput
Higher heat increases the darkness of your print and therefore the contrast of your barcodes.
However, the wrong ratio can lead to print issues and even damage your printhead.

We generally recommend running your printer on a relatively slow setting. This uses less heat and ensures a crisp, clear printed image. On a similar note, we recommend you avoid increasing heat settings without guidance from a professional.

If you work with a supplier who sets up and tests your printer with your media prior to shipping it to you, they have likely adjusted the heat and speed ratio to one suitable for your application.

Maintaining a proper heat and speed ratio will ensure a scannable barcode and extend the life of your printhead so you can avoid costly waste and unnecessary part replacements.

2. Keep The Print Head Clean
Keeping your print head clean is imperative to maintaining your printer. Without regular cleaning, your print head will be more susceptible to abrasion during printing. This can reduce image quality and shorten the life of your printer.

We recommend you establish a schedule for regular print head cleaning. Our technical team endorses cleaning this part whenever you replace the label roll or install a new ribbon.

3. Protect The Print Head From The Media
To safeguard the print head against abrasion, use a thermal transfer ribbon that’s slightly wider than the media.

4. Don’t Use Razor Blades Or Box Cutters
Unless you’re using a model with a peeler or applicator, you should only use tools such as the printer’s tear bar or scissors to remove labels. Razor blades, box cutters, and other inappropriate tools can easily slip and cut the driver roller. These cuts can create voids in your printed labels leading to misreads.

5. Avoid “Ribbon Wrinkles”
If you’re seeing seemingly random diagonal lines on your print you’re probably dealing with ribbon wrinkles. The main culprit of ribbon wrinkles is too much heat, so your first option is to lower the heat setting. If that doesn’t work, make sure your printer is set up properly. Check that the ribbon is loaded correctly, the media guides are set properly, and the head pressure is balanced. If you’re still experiencing issues you might want to reach out to your supplier to ensure your media and ribbon combination is ideal.

Regards,
Peter


body:
I was trying for one month to make multiple **RC522 rfid readers** work together on SPI on an arduino yun, one works fine, but if **I plug 4**, each with a specific slave select, **only one, sometimes 2, sometimes none are working**.

The library i use is `RFID.h` (i think the miguelbalboa one) , but I had the same results with `MFRC522.h` wich have a specific `readUidMultiReader` so I dont think my code is at fault.

Searching for this issue, I found [this question][1] wich is basically my issue, as I suspect [the readers I bought][2] are not supporting multidrop. [These readers][3] dont work either.

I read about solutions using [multiplexers][4] for SPI lines, tristate buffers on miso lines and/or [diodes][5] but these are workarounds, and there should be a more straightforward solution.

Also I tested with **no resistors** most of the time, but tried putting 10kΩ from all MISO to 3v3, no change, as i really dont understand what their use are, even if I feel they could be mandatory.

---
*I am using a yun for the builtin ethernet, because I tried nanos with ethernet shields and again the shields are ignoring the Slave select and thus not working with spi multidrop, so each time I plugged the shield on nano, even not using it, rfid stopped working.*

[![wiring][6]][6]

  [1]: https://arduino.stackexchange.com/questions/18313/issue-sharing-miso-with-multiple-rc522-rfid-readers
  [2]: https://www.amazon.fr/AZDelivery-lecteur-Arduino-Raspberry-démarrage/dp/B074S9FZC5/ref=sr_1_2
  [3]: https://www.gotronic.fr/art-module-rfid-13-56-mhz-vma405-25477.htm
  [4]: https://github.com/miguelbalboa/rfid/issues/191#issuecomment-242631153
  [5]: https://github.com/miguelbalboa/rfid/issues/290#issuecomment-549559010
  [6]: https://i.stack.imgur.com/PDIKZ.png

title: multiple RC522 RFID on arduino yun

Answers: 2

body:
I suppose that digital output power from yun is insufficient to drive all four readers - so, you need to add some [digital buffers][1] to MOSI, SCK, and RST lines.

74LS07 digital buffer:

[![74LS07][2]][2]

  [1]: https://www.electronics-tutorials.ws/logic/logic_9.html
  [2]: https://i.stack.imgur.com/mflqI.png

body:
Multiple SPI devices on the same bus shouldn't be a problem. I would try the following steps to narrow down the problem:

1. Add Pull-Up resistors to each CS line (10k should be enough)
(The is no need for resistors on the MISO, MOSI or CLK lines since they a push/pull when active)

2. Make sure each CS is set to `HIGH` before you attempt to access the reader

3. Use a simple sketch that only access 1 reader.
    - if you could access the first reader -> change the sketch to use the second one without changing the hardware setup. Continue until you've checked all readers.
- if you are not able to communicate with one reader, you still have a bug in your hardware setup

4. When the readers work independently, you could start to write your sketch using more than one at a time. (depending on the libraries this could be quite difficult since the lib must support multiple instances, but first we should check the hardware setup)


body:
I'm trying to build a low power GPS datalogger and I am trying to get the Mediatek based GPS module (Quectel L80-R) to run in periodic mode. I've sent the PMTK225 code to the module with various parameters, but it never seems to go into stand by or back up mode. Code below.

    //Testing that commands sent to the GPS unit work

    #include <NeoSWSerial.h>
    NeoSWSerial gpsPort(3,2); // pins 3/2

    #include <NMEAGPS.h>
    NMEAGPS gps;

    void setup() {

      // connect at 115200 so we can read the GPS fast enough and echo without   dropping chars
      // also spit it out
      Serial.begin(115200);

      gpsPort.begin( 9600 );
      gps.send_P( &gpsPort, F("PMTK605")); //firmware version
      delay(100);
      //gps.send_P( &gpsPort, F("PMTK314,-1")); //reset to default
      //gps.send_P( &gpsPort, F("PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") ); // RMC_GGA
      //gps.send_P( &gpsPort, F("PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") ); // RMC only
      delay( 100 );
      //gps.send_P( &gpsPort, F("PMTK220,200") );  // 5Hz
      //gps.send_P( &gpsPort, F("PMTK220,1000") ); //1hz
      delay( 100 );
      //gps.send_P( &gpsPort, F("PMTK225,0")); // normal mode
      //gps.send_P( &gpsPort, F("PMTK223,1,25,180000,60000")); // ephemeris data receiving
      gps.send_P( &gpsPort, F("PMTK225,2,3000,10000")); //period mode but not working
      //gps.send_P( &gpsPort, F("PMTK161")); //stand by mode
      //gps.send_P( &gpsPort, F("PMTK103")); //cold start
      delay(100);
      gps.send_P( &gpsPort, F("PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") ); // RMC only

      //gps.send_P( &gpsPort, F("PGCMD,33,0") );   // No antenna status messages needed
      delay( 100 );

      Serial.println("Ready!");
    }

    void loop() {
      if (gpsPort.available())
        Serial.write( gpsPort.read() );
    }

title: Mediatek GPS periodic mode

Answers: 1

body: Quectel L80-R does NOT have periodic mode, while the L80 does.


body:
Im currently working on a project which displays vital signs such as pulse and oxygen on my display. Now, my sensor is connected through I2C while my OLED runs through SPI. Im trying to display the sensor readings on the OLED but that doesnt seem to work. Tried reading through the threads and wasnt able to come up with a concise solution.

Anyone with a similar case and working solution will truly appreciate the support.

    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #include <Arduino.h>
    #include "algorithm.h"
    #include "max30102.h"

    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 64 // OLED display height, in pixels

    // Declaration for SSD1306 display connected using
    // software SPI (default case):
    #define OLED_MOSI   11
    #define OLED_CLK   13
    #define OLED_DC    9
    #define OLED_CS    12
    #define OLED_RESET 8
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
      OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

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

    #define MAX_BRIGHTNESS 255

    #if defined(ARDUINO_AVR_UNO)
    // Arduino Uno doesn't have enough SRAM to store
    // 100 samples of IR led data and red led data in 32-bit format
    // To solve this problem, 16-bit MSB of the sampled data
    // will be truncated. Samples become 16-bit data.
    uint16_t aun_ir_buffer[100]; //infrared LED sensor data
    uint16_t aun_red_buffer[100];  //red LED sensor data
    #else
    uint32_t aun_ir_buffer[100]; //infrared LED sensor data
    uint32_t aun_red_buffer[100];  //red LED sensor data
    #endif

    // data length
    int32_t n_ir_buffer_length;
    // SPO2 value
    int32_t n_spo2;
    // indicator to show if the SPO2 calculation is valid
    int8_t ch_spo2_valid;

    // heart rate value
    int32_t n_heart_rate;

    // indicator to show if the heart rate calculation is valid
    int8_t  ch_hr_valid;
    uint8_t uch_dummy;

    void setup()
    {
      //resets the MAX30102
      maxim_max30102_reset();

      // initialize serial communication at 115200 bits per second:
      Serial.begin(115200);

      // pin D10 connects to the interrupt output pin of the MAX30102
      pinMode(10, INPUT);
      delay(1000);

      // Reads/clears the interrupt status register
      maxim_max30102_read_reg(REG_INTR_STATUS_1,&uch_dummy);
      // wait until user presses a key
      while( Serial.available() == 0 )
      {
        Serial.write(27);       // ESC command
        Serial.print(F("[2J")); // clear screen command
        Serial.println(F("Press any key to start conversion"));
        delay(1000);
      }

      uch_dummy=Serial.read();
      maxim_max30102_init();

      Serial.begin(115200);
      sensors.begin();

      if(!display.begin(SSD1306_SWITCHCAPVCC))
      {
        Serial.println(F("SSD1306 allocation failed"));
      }

      display.clearDisplay();
      display.setTextSize(2);
      display.setTextColor(WHITE);
      display.setCursor(30,30);
      display.print("ATRAL:D");
      display.display();
      delay(1000);
      display.clearDisplay();
    }

    void loop()
    {
      // Call sensors.requestTemperatures() to issue
      // a global temperature and Requests to all devices on the bus
      sensors.requestTemperatures();

      Serial.print("Celsius temperature: ");
      // Why "byIndex"? You can have more than
      // one IC on the same bus. 0 refers to the first IC on the wire
      Serial.print(sensors.getTempCByIndex(0));
      Serial.print(" - Fahrenheit temperature: ");
      Serial.println(sensors.getTempFByIndex(0));
      delay(100);

      // variables to calculate the on-board LED
      // brightness that reflects the heartbeats
      uint32_t un_min, un_max, un_prev_data, un_brightness;
      int32_t i;
      float f_temp;

      un_brightness=0;
      un_min=0x3FFFF;
      un_max=0;

      // buffer length of 100 stores 4 seconds
      // of samples running at 25sps
      n_ir_buffer_length=100;

      // read the first 100 samples, and determine the signal range
      for( i=0; i < n_ir_buffer_length; i++ )
      {
        // wait until the interrupt pin asserts
        while( digitalRead(10) == 1 );
        //read from MAX30102 FIFO
        maxim_max30102_read_fifo( ( aun_red_buffer + i ),
                                  ( aun_ir_buffer + i ) );

        if(un_min>aun_red_buffer[i])
          un_min=aun_red_buffer[i];  //update signal min
        if(un_max<aun_red_buffer[i])
          un_max=aun_red_buffer[i];  //update signal max
        Serial.print(F("red="));
        Serial.print(aun_red_buffer[i], DEC);
        Serial.print(F(", ir="));
        Serial.println(aun_ir_buffer[i], DEC);
      }
      un_prev_data=aun_red_buffer[i];

      // calculate heart rate and SpO2 after first 100 samples
      // (first 4 seconds of samples)
      maxim_heart_rate_and_oxygen_saturation( aun_ir_buffer,
             n_ir_buffer_length, aun_red_buffer,
             &n_spo2, &ch_spo2_valid, &n_heart_rate,
             &ch_hr_valid );

      // Continuously taking samples from MAX30102.
      // Heart rate and SpO2 are calculated every 1 second
      while(1)
      {
        i=0;
        un_min=0x3FFFF;
        un_max=0;

        // dumping the first 25 sets of samples
        // in the memory and shift the last 75 sets
        // of samples to the top
        for( i=25; i<100; i++ )
        {
          aun_red_buffer[i-25]=aun_red_buffer[i];
          aun_ir_buffer[i-25]=aun_ir_buffer[i];

          //update the signal min and max
          if(un_min>aun_red_buffer[i])
            un_min=aun_red_buffer[i];
          if(un_max<aun_red_buffer[i])
            un_max=aun_red_buffer[i];
        }

        //take 25 sets of samples before calculating the heart rate.
        for( i=75; i<100; i++ )
        {
          un_prev_data=aun_red_buffer[i-1];
          while(digitalRead(10)==1);
          digitalWrite(9, !digitalRead(9));
          maxim_max30102_read_fifo((aun_red_buffer+i), (aun_ir_buffer+i));

          //calculate the brightness of the LED
          if(aun_red_buffer[i]>un_prev_data)
          {
            f_temp=aun_red_buffer[i]-un_prev_data;
            f_temp/=(un_max-un_min);
            f_temp*=MAX_BRIGHTNESS;
            f_temp=un_brightness-f_temp;
            if(f_temp<0)
              un_brightness=0;
            else
              un_brightness=(int)f_temp;
          }
          else
          {
            f_temp=un_prev_data-aun_red_buffer[i];
            f_temp/=(un_max-un_min);
            f_temp*=MAX_BRIGHTNESS;
            un_brightness+=(int)f_temp;
            if(un_brightness>MAX_BRIGHTNESS)
              un_brightness=MAX_BRIGHTNESS;
          }
    #if defined(ARDUINO_AVR_LILYPAD_USB)
          analogWrite(13, un_brightness);
    #endif

    #if defined(ARDUINO_AVR_FLORA8)
          LED.setPixelColor(0, un_brightness/BRIGHTNESS_DIVISOR, 0, 0);
          LED.show();
    #endif

          //send samples and calculation result to terminal program through UART
          Serial.print(F("red="));
          Serial.print(aun_red_buffer[i], DEC);
          Serial.print(F(", ir="));
          Serial.print(aun_ir_buffer[i], DEC);

          Serial.print(F(", HR="));
          Serial.print(n_heart_rate, DEC);

          Serial.print(F(", HRvalid="));
          Serial.print(ch_hr_valid, DEC);

          Serial.print(F(", SPO2="));
          Serial.print(n_spo2, DEC);

          Serial.print(F(", SPO2Valid="));
          Serial.println(ch_spo2_valid, DEC);
        }
        maxim_heart_rate_and_oxygen_saturation(aun_ir_buffer, n_ir_buffer_length, aun_red_buffer, &n_spo2, &ch_spo2_valid, &n_heart_rate, &ch_hr_valid);
      }

      display.clearDisplay();
      display.setTextSize(1);
      display.setTextColor(WHITE);
      display.setCursor(0,0);
      display.print("Temp: ");
      display.print(sensors.getTempCByIndex(0));
      display.print("C");
      display.setCursor(0,10);
      display.print("Temp: ");
      display.print(sensors.getTempFByIndex(0));
      display.print("F");
      display.setCursor(0,20);
      display.print("HR: ");
      display.print(n_heart_rate, DEC);
      display.setCursor(0,30);
      display.print("02: ");
      display.print(n_spo2, DEC);
      display.setCursor(0,50);
      display.setTextSize(2);
      display.print("BOX.E");
      display.display();
      display.clearDisplay();

    }

title: I2C and SPI using sensor and Oled display

Answers: 0


body:
I have the battery charger product https://www.adafruit.com/product/2124
and a teensy 4.0, that I would like to use to power it.
what, if any pin would I connect from bat, to the teensy?
Its my understanding that the Lion backpack is a voltage regulator, and thats it. it takes Vin, ground, and Vout.
I understand the 5v output goes to the 5volt pin of the teensy.
the gnd goes to gnd. should Vin go someplace? Or should I leave it off?
Please assist.

title: how can i conect a lipo charger to a teensy 4.0?

Answers: 1

body:
The output voltage of the charger board is marked with `BAT`. You should connect it to the Vin pin of the Teensy, which then will convert the batteries 3.7-4.2V down to 3.3V.

Of course you need to connect the grounds of the charger board and the Teensy (on the charger board ground is marked with `G`).

The 5V pin on the charger board is no output. The board does not give you 5V. This is actually the pin for the charging voltage, which is 5V. Here it depends on how you want to charge the battery. If you use an external source, you can simply connect it's 5V to the board. If you want to use the USB jack of the Teensy, you can connect the boards 5V to the Teensys 5V. **But:** Be sure to cut the little trace between Vin and VUSB/5V at the back of the Teensy. You don't want to connect the battery voltage with an USB power source.


body: I am trying to build a cashless RFID based water dispensing unit. I am using Arduino mega 2560, PN532, relay, flow sensor. Here is the flow of the program in I2C mode; I have two functions, one to scan the card and the other for the flow sensor. As soon as the RFID card is placed on the NFC module, data stored in the card (i.e, date of expiry and balance amount) is obtained and is checked for validity. If the card is valid, then the relay is turned on. A flow sensor measures the quantity of water dispensed. As soon as the limit of 1000 ml is reached, the relay is turned off. The whole process happens serially, when the card scanning is complete, it waits for the entire 1000 ml of water to be dispensed. What I want to achieve is after one card is scanned, 1st relay with the flow sensor has to be turned on and simultaneously the scanning of the second card has to begin. If the first relay is busy, second relay has to be assigned to it. Can I achieve this using Arduino Mega? How do I manipulate the atmega to perform all these tasks at once?

title: How to multitask with interrupts on Arduino?

Answers: 2

body:
You do not necessarily need a build a "multitask with interrupts on Arduino".  Instead consider using a [state machine][1].  First define the problem by drawing a [state diagram][2]:

[![enter image description here][3]][3]

Consider all state you wish to be in.  Including your example "...after one card is scanned, 1st relay with the flow sensor has to be turned on and simultaneously the scanning of the second card has to begin...".  Once you have defined all states and the rules that need to be tested for before jumping to a new state you can start programming your state machine.

There are plenty of tutorials [including this one][4] on the web specifically for people who want to implement a state machine on an Arduino.  But, briefly, you will want to create a loop that will execute with out stopping over and over again as fast as possible.  This loop will (1) know what the current state is and (2) will repeatedly test to find out if the program can change to any of the possible next states. When you change states is when, if you need to, you perform tasks such at turning the water on or off.

If you forsake the state machine and only use interrupts, testing the code tends to be very difficult.  As controlling exactly when an interrupt occurs relative to other interrupts and the state of the processor becomes problematic and nearly impossible to reliably repeat.  This is why the state machine is suggested. Interrupts can still detect external events. But by using a state machine the program is in control of what happens next. Instead of leaving it up to luck.

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine
  [2]: https://en.wikipedia.org/wiki/Finite-state_machine#/media/File:Finite_state_machine_example_with_comments.svg
  [3]: https://i.stack.imgur.com/l79xX.png
  [4]: https://create.arduino.cc/projecthub/gusgonnet/using-finite-state-machines-fdba04

body:
There is no real multitask on Arduinos. The Arduino can only do one thing at a time.

But, you can do things sequentially, one after another, so fast, that a human will think, that it happens simultaneously. This involves a non-blocking coding style, which needs no interrupts

- Every delay in your code (at least the long onces) need to be removed. if you want to do timed things, you should use the coding principle from the `BlinkWithoutDelay` example, that comes with the Arduino IDE.

- Also no function should wait for something to happen. Think of a function, that waits for a command from the serial interface. Blocking code would wait indefinitely, until a command was received, preventing any other code from execute. Instead the function could exit fast, when there is currently no command to process, leaving time for the other code to execute.

The whole principle relies on the `loop()` function executing very fast, so that your code can still be reactive. This works for most of the situations. Only sometimes you need to react that fast, that you need interrupts. Your usecase doesn't seem to belong to the interrupt needed faction.


body: is it possible to switch internet connection from esp8266 wifi module to gsm sim 900A internet if the arduino detects that the esp have no internet connection and vise versa? Thanks

title: Internet switching

Answers: 0


body:
It has already been asked how many clients can connect to an ESP32 AP, but the answer is far from clear; the best one is from a year and half ago ([ESP32 AP max connections: 4 or 10?][1]) :

> The answer is as clear as any other EspressIf configuration data, it is 4 or maybe 5, or 8, or 12, 16 or even 20 (the same as a ESP8266!)

As I'm trying to move a project from the ESP8266 because it does not have enough AP connections, two questions can be asked :

1. what is the maximum number of AP connections supported by the 4.0 ESP-IDF framework ?

2. can it be increased in any way ?

Thank you.

  [1]: https://arduino.stackexchange.com/questions/54459/esp32-ap-max-connections-4-or-10

title: Increasing ESP32 AP max connections

Answers: 2

body:
According to [the documentation](https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/network/esp_wifi.html#_CPPv416wifi_ap_config_t):

> `uint8_t max_connection`
>
> Max number of stations allowed to connect in, default 4, max 4

The WiFi interface and AP can support up to 10 connections in its internal structures, but that is only practical for WiFi Mesh usage (which doesn't use all 7 layers of the ISO model), and for actual WiFi station connections, which entails the allocation of far more resources (IP addresses, ARP tables, etc) only a maximum of 4 are supported.

If you need more connections I suggest you invest in a *real* access point / router which can deal with the network management for you (i.e., an access point or router which can do the DHCP and other networking housekeeping for you, leaving your ESP32 free to be a simple station).

body:
After some extensive testing with several modules (not just blindly trusting the documentation), here's what I found.

Short answer : **maximum 10 AP connections** for the ESP32 running ESP-IDF 4.0 (updated around 1st of march 2020), and **no, it can't be increased** (easily).

Details :

 - The maximum number of AP connections is defined somewhere in libnet80211, and can't be modified since I have no access to the source code.
 - when the 11th station tries to connect, libnet80211 prints `I (39682043) wifi: max connection, deauth!`, more or less like the ESP8266 for the 5th station
 - Changine the `ESP_WIFI_MAX_CONN_NUM` (defined in esp_wifi_types.h:258) from 10 to anything else ends up in unpredictable behavior (I'm labelling this as unpredictable since without the libnet80211 code, it can't be reliably assessed).

I'm not giving up on increasing the number of stations yet, so maybe there'll be an update to this answer.


body:
 I tried to connect xampp/mysql to arduino but connection fails.
mysql is running on port 3306.
I searched a lot on the internet but could not understand where is the problem!
Would you please help me...

    #include <Ethernet.h>
    #include <MySQL_Connection.h>

    byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    IPAddress server_addr(127,0,0,1);  // IP of the MySQL *server* here
    char user[] = "root";              // MySQL user login username
    char password[] = "";        // MySQL user login password

    EthernetClient client;
    MySQL_Connection conn((Client *)&client);

    void setup() {
      Serial.begin(9600);
      while (!Serial); // wait for serial port to connect
      Ethernet.begin(mac_addr);
      Serial.println("Connecting...");
      if (conn.connect(server_addr, 3306, user, password)) {
        delay(1000);
         Serial.println("Connection stablished.");
        // You would add your code here to run a query once on startup.
      }
      else
        Serial.println("Connection failed.");
      conn.close();
    }

    void loop() {
    }

title: arduino connection to mysql fails

Answers: 0


body:
I am hoping to control a 60V DC input source dynamically using my Arduino so that the output voltage could vary between 0v to 60v. At first i was looking into digital potential meter, however I couldn't find any digital pot that can support 60V DC input voltage.
I have came across a few articles with similar situation (but theirs with lower voltage).

Could anyone suggest any solution to my problem?
Thanks. Any help is much appreciated.

title: Dynamically control the output voltage of a 60V DC input

Answers: 1

body:
Try ZMPT101B. Easy to use and very cheap

[Active Single Phase Voltage Transformer Module AC Output Voltage Sensor for Arduino Mega ZMPT101B 2mA][1]

  [1]: https://www.aliexpress.com/item/4000193055897.html?src


body:
![Imgur](https://i.imgur.com/r9wYwGP.gif)

For some reason, my 3.3v on my Arduino is fluctuating a lot, and I am not sure why.
The multimeter is measuring dc voltage and is connected between GND and 3.3v of an Arduino Mega.

The multimeter works fine. Connecting between 5v and GND gives 5V on multimeter.

title: Why does my Arduino 3.3v fluctuate?

Answers: 1

body:
Arduino output voltages may "fluctuate" a few mV but what you showing us in that gif is really unstable.

What you should be doing is:

1. Disconnect everything from Arduino except the power source
2. measure the voltage again;

Is it stable? the problem was because of pulling too much current that causing voltage drop and instability .

Is it unstable?

3. Try checking with another MM and/or change auto-range to manual.

Is it stable when measuring the voltage with another MM? something was wrong with your previous MM.

Still unstable?

4. Connect the Arduino to a 9V power adapter and disconnect the USB cable.

Measure the voltage again, if it's stable the problem was because of some error in the cable or USB power source.

Voltage is still unstable?

5. change the 3.3V voltage regulator.

It should fix the problem if not report back to do some more in-depth problem solving.


body:
The board ESP32-Dev-WROOM-32D cannot establish a bluetooth connection due to the task watchdog. Here's my code:

    #include "BluetoothSerial.h"
    //check if Bluetooth is enabled
    #if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
    #error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
    #endif

    BluetoothSerial SerialBT;

    void setup() {
      Serial.begin(115200);
      SerialBT.begin("ESP32test");
      Serial.println("The device started!");
    }
The program runs fine until `SerialBT.begin("ESP32test");` where it freezes, and does not continue to run. The message `The device started!` is not printed. Instead, the task watchdog gets triggered after some time: `E (24791) task_wdt: Task watchdog got triggered.`

Is there any way to turn off the task watchdog? Or is there any other issue?

title: Task watchdog gets triggered during Bluetooth initialization

Answers: 1

body:
`SerialBT.begin("ESP32test")` is hanging, and because ESP32 doesn't deal well with code that hangs, so it complains about it.

ESP32 runs a Real-Time OS ([FreeRTOS](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/freertos.html)).
The fact that it is a real-time OS means that execution of code needs to be guaranteed to finish within a certain time-frame. You'll often see RTOS functions containing the time limit in which that a blocking function should finish executing, such as:

```c
    uart_wait_tx_done(uart_num, 100); // wait timeout is 100 RTOS ticks (TickType_t)
```
(from [ESP-IDF docs](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/uart.html))

FreeRTOS comes with a task API. Each task can execute code, but they need to give other tasks the chance to execute code too. I think that when a task blocks, it doesn't allow other tasks to do work on the same CPU. (but I can't find sources to back this up)

`setup()` runs in one of the RTOS tasks, and when `SerialBT.begin()` blocks the task for too long, the task watch dog complains that the task is hanging.
If the task is blocked by some kind of looping code, then it generally helps to run `vTaskDelay()` to yield the task to the task watchdog for a bit.

Because your task is blocked by a single call, there isn't much to do about it, given that `SerialBT.begin()` doesn't seem allow you to specify when it should time out.


body:
Good day! How to set sensor Data parameters?

Like the data only set for example it starts with minimum value of 3 and ends with maximum value of 6 and it will turn on led 1 and if minimum value of 1 and maximum value of 2 turn on led 2 just like that?

My actual code for that:

    float basa = scale.get_units();
    if( basa >= 4 )
    {
      digitalWrite(led1, HIGH);
    }
    else if( basa >= 2 )
    {
      digitalWrite(led2, HIGH);
    }

This code shows that if ever it reaches value of 4 the value of 2 will react also so my question is how set sensor data value like it will only react Value1 - Value2 like that.

thank you

title: How to Set Sensor Data Parameters?

Answers: 1

body:
For example:

    float basa = scale.get_units();

    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);

    if( basa >= 2 && basa < 4 )
    {
      digitalWrite(led2, HIGH);
    }

    if( basa >= 4 )
    {
      digitalWrite(led1, HIGH);
    }

**EDIT: as suggested by @chrisl (see comments)**

If understand you problem correctly, you try to light up 2 LEDs according to the value you read from a scale. IMHO you want to assign three intervals (ranges) like so:

    (-INF, 2) : none of the LEDs is switched on
    [2, 4)    : only LED 2 is switched on
    [4, +INF) : only LED 1 is switched on

* `[x` or `x]` means the x belongs to the interval.
* `(x` or `x)` means the x does not belong to the interval.
* `+INF` and `-INF` are the positive or negative infinity.

My code does the following:

I use the observation, that the intervals do not intersect and the union of the intervals are the complete real number space. (Although your scale has a more narrow range: (0-?kg). The program can handle a wider range compared to the the scale, so it is not a problem.)

If the first condition `(-INF, 2)` is `true`, none of the others would be and we can be sure that the LEDs I switched off with the `digitalWrite(ledX, LOW);
` statements will stay off. If the value is in the range of `[2, 4)` I switch on LED2 and can be sure that the other LED stays off because the condition `basa >= 4` can not be `true`. And if the value is in the range of  `[4, +INF)` I switch on LED1 and can be sure that LED 2 has not been switched on because the condition `basa >= 2 && basa < 4` can not be `true`.


body:
I've tried many codes for this to work but anything isn't helping at all, so my code should work like this: If a sound sensor (3 pins, A2) sends 5 signals into the Arduino within 10 seconds (the time gap of every signal varies, but doesn't matter as long as it sends 5 signals), the LED (13) will light up. This is my recent code if it could help

    int led=13;
    int sensor=A2;

    void setup()
    {
       pinMode(led, OUTPUT);
        pinMode(sensor, INPUT);
        Serial.begin(9600);
    }

    void loop()
    {
        unsigned long StartMillis = millis();
        unsigned long CurrentMillis = millis();
        int signal_count=digitalRead(sensor);
        int signal_limit=5;
        Serial.println(signal_count);

        while ((CurrentMillis - StartMillis)==5000)
        if (digitalRead(sensor)=0)
        {     signal_count ++;
            Serial.println(signal_count);
        }
        if (signal_count>signal_limit) {
            digitalWrite(led, HIGH);
        }
        else {
        digitalWrite(led,LOW);
        }
    }

title: Sound sensor signals with time bracket

Answers: 1

body:
Your handling of `millis()` is wrong. With these two lines:

    unsigned long StartMillis = millis();
    unsigned long CurrentMillis = millis();

`StartMillis` will always have the same value as `CurrentMillis`. (Ok, I guess its possible for `millis()` to return a value that's increased by 1 the second time it's called, but that is **extremely** unlikely. The 2 lines takes much less than a millisecond to execute.)

Your

    while ((CurrentMillis - StartMillis)==5000)

will never evaluate to true, so the code in the while block will never execute.

This `if` statement is also wrong:

    if (digitalRead(sensor)=0)

You want `==` (comparison) not `=` assignment. I'm surprised the compiler even allowed that to compile, since you are trying to set the function `digitalRead(sensor)` to 0, which doesn't make sense.

Change that code to read:

    if (digitalRead(sensor)==0)

(Assuming you want the body of the if statement to execute when your sensor value is 0.)


body:
I am planning to build a little game and I would need to move a small magnet inside a rectangular area. Ideally I would be able to control movement arbitrarily e.g. using a joystick.
I am trying to find a way of doing this, something like an actuator, I guess, but allowing movement in 2D.
Any suggestions on which parts to use?

Edit : in brief, what I'm trying to do is this. I have a piece of plywood, underneath which I want to put a magnet. The magnet will be moveable using a joystick (everything controlled through an Arduino) and will be used to move a magnetised figurine on the other side of the plywood. I guess in term of precision of movement I am not looking for extreme precision, having something accurate to 2-3mm would be absolutely fine. Haven't really thought of speed... But not looking for extreme high speeds.

title: Moving an object in an area

Answers: 1

body:
First you need to think about your axes configuration, then about the actual implementation. I for example can directly think of 2 options:

- You could arrange your axes perpendicular to each other, like a Cartesian coordinate system. Here you might need more parts to build it, than with other arrangements, though it is a sturdy system and the positions and paths are easily to calculate. For implementation there are 2 common ways, both using stepper motors in most cases:

    - You could let the magnet travel on the 2 perpendicular axes pulled by a belt and stepper motor for each axis. As you have to mount one axes onto the other, you might need to use 2 stepper motors (one for each side) for the first axis (depending on your dimensions, how smooth the axes glide and how much force is introduced by dragging the figurine). This approach is mostly used by 3D Printers, since they need rather fast movement, which is also rather precise, but don't need to accommodate high forces.

    - Instead of belts and pulleys you could use threaded rods for each axis. The magnet is mounted on nuts on these rods. Rotating the rots will move the magnet over the axis, since the magnet is fixed in it's orientation. The precision is highly dependent on the used rods, but all in all it is often more precise, than belts. But it is also way slower.

- You could use only rotational axes, like a SCARA robot. It has a rod on a rotational axis and another axis at the end of it. This approach might use less parts, than the Cartesian approach, but you need good servos to have precise and jitter-free positioning (though you could also go for a geared stepper motor here). Also the arm of the robot can look out under the field quite a bit, when positioning it to the far one side.

---

All of the above approaches can be way more precise, than you need it. They are all viable options.

I personally would go the first way, Cartesian axes with belts and pulleys. The principle is straight forward and you can easily hide it under your piece of plywood (including a margin for all the mechanical stuff of course).