body:
I am trying to read data from a two-way I/O uart pin of a sim card on Arduino. It is attached to the GPRS Arduino shield (with SIM900 modem). I believe I have a baud rate issue.

I am supposed to receive ATR (Answer to Reset) bytes which should be easily recongnized but all I get is a almost-random stream of bytes.

I soldered a wire on the SIM I/O pin and attached it to arduino's software serial RX, I set the baud rate to the same baud rate of the modem which goes up to 115,2K and read. Here's my code

    #include <SoftwareSerial.h>
    SoftwareSerial IO(9, 10);
    void setup() {
    Serial.begin(115200);
    IO.begin(115200); // my said wire on SIM card's I/O    enter code here
    }
    void loop() {
    if (IO.available())
    Serial.print(IO.read(),HEX);
    }

and here's the output after a cold reset :
[![enter image description here][1]][1]

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

I also tried other baud rate within the SIM900 range of baud rates, still almost same.

Any idea why it's not showing bytes correctly? I appreciate it if anyone could help.

title: Reading incoming/outgoing bytes from SIM card / ATR

Answers: 0


body:
I recently made a project where output is coming from the differential between data reading and reference value. It works on my Proteus simulation but there is no PWM output on my real world device.

Here is my code listing

    for (z = 0; z <= output2; z++)
      if (output2 >= 30) {
       toggle == HIGH;
       en = !en;
      }
    if (en == true) {
      OCR1A = map(z, 0, 255, 0, ICR1); ;
      OCR1B = 0;
    } else {
      OCR1A=0;
      OCR1B = map(z, 0, 255, 0, ICR1);
    }
    if (output2 < 30) {
      en = !en;
      analogWrite(9, 0);
      analogWrite(10, 0);
    }

title: There is no PWM output

Answers: 1

body:
I’m not sure what you’re trying to accomplish, but you’re writing a constant `0` to the analog output.

>     if (output2 < 30) {
>       en = !en;
>       analogWrite(9, 0);
>       analogWrite(10, 0);
>     }

To quote the [analogWrite() doc](https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/)

> Syntax
>
> analogWrite(pin, value)
>
> Parameters
>
> pin: the pin to write to. Allowed data types: int.
>
> value: the duty cycle: between 0 (always off) and 255 (always on). Allowed data types: int

If you want to see an output, you have to write a value between 0 and 255.


body:
I am having trouble understanding exactly what is going on in a circuit where when a button is pressed an LED goes on. Also, I have the Arduino UNO.

The schematic can be seen at:

[2:36][1] of this video: [Arduino Tutorials: Control a LED with a Button][2].

[![Fritzing of complete circuit][3]][3]

So, the part that I don’t understand is, how come when the button is clicked and the current can pass through, the current doesn’t go through the pull down resistor and instead goes along the input wire?

[![Pull down resistor on input][4]][4]

I’m a beginner but do understand concepts like voltage, amps, resistors, Ohm’s law, etc. So answers don’t have to be super simple, but simple enough that I can understand them. Thanks!

  [1]: https://youtu.be/ksNbEuhO4fU&t=156
  [2]: https://youtu.be/ksNbEuhO4fU
  [3]: https://i.stack.imgur.com/t6Nmy.png "Fritzing of complete circuit"
  [4]: https://i.stack.imgur.com/Gl4XP.png "Pull down resistor on input"

title: Why does current flow along a wire instead of a resistor right next to it?

Answers: 2

body:
the answer is within the question,
Electrons will quite happily travel along a wire until they hit resistence as in a resistor.
where there is less resistence too flow that is the path they will take.
The path of least resistence you might say.

body:
> So, the part that I don’t understand is, how come when the button is clicked and the current can pass through, the current doesn’t go through the pull down resistor and instead goes along the input wire?

Simple: It *does* go through the pull down resistor. But  it *also* goes down the "input" wire.

For simplicity you can imagine that the input is simply a very large resistor. Say, 1MΩ.

The circuit can then be simplified as:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/IMf1I.png)

<!-- End schematic -->

Contrary to popular belief, current does *not* take the path of least resistance. It takes *all possible* paths. The quantity of current through each path is proportional to the resistance of the paths.

In this example we have two paths - one with 10kΩ and one with 1MΩ.  That's a ratio of 1:100, and the current will be split accordingly.

You can calculate the current that flows through each resistor simple using Ohm's Law because the wires and switch are (in an ideal world) just not there. The 5V is directly connected across each of the resistors.

So for the 10kΩ resistor the current through is is:

         V      5
    I = --- = ----- = 0.0005 = 500µA
         R    10000

And for the 1MΩ it is of course 100x smaller (I'll let you do the maths for that if you want to check), so 5µA.

The full current that the circuit takes is 505µA, with it split between the two resistors.

With the Arduino instead of the 1MΩ resistor it's exactly the same (though the current values may vary somewhat).  500µA flows through the 10kΩ resistor, and "some tiny current" flows through the Arduino.

However, with all that said, the Arduino really doesn't care about the current. All it cares about is the voltage. With the button pressed both the input and the 10kΩ resistor are connected directly to the 5V supply - so the Arduino reads that as "HIGH". When you release the button the input is now connected to ground through the 10kΩ resistor, but there's no current to flow, so there's no voltage across the resistor (the voltage across a resistor is proportional to the current flowing through the resistor - Ohm's Law), so it's as if the input is connected directly to ground - and the Arduino reads that as "LOW".

To be more technically accurate the input of the Arduino is actually more akin to a tiny capacitor.  When you apply 5V to the input it charges that capacitor up. Once it reaches 60% of 5V the Arduino recognises it as a "HIGH" signal.

When you release the button that capacitor is then connected to ground through the resistor, and it discharges through that resistor. Once it drops to 30% of 5V the Arduino sees it as being "LOW".

If you don't have the pull-down resistor, when you remove the 5V from the input that capacitor is still charged. So the Arduino still sees it as a HIGH. The charge in the capacitor will slowly bleed away until it's low enough to be seen as low.

But, (and it's a *big* but), the capacitor is very sensitive and can be charged up again by ambient energy around the place (radio waves, static electricity, etc). It can harvest enough energy from the environment to get back up to the 60% of 5V and be seen as "HIGH" again. This is known as "Floating", and is something you do *not* want in your circuit. The input "flaps around" between HIGH and LOW with no control.  Which is why the pull-down resistor is absolutely essential.


body:
Can I supply an Arduino Nano 5 V 1 A unregulated in pin 27?

It has a PIR sensor, a LDR sensor and switch drive high power MOSFET trigger module connected to it.

title: Arduino Nano input voltage

Answers: 0


body:
I'm using an ESP32 WROOM board to capture some data in the field and send it over using arduino json. However, the complete process of sending and receiving confirmation takes up around 12 seconds and my ESP is frozen in that time. As a result, I lose the data in that time window. Is there a way to reduce the upload time of the ESP or maybe continue taking data while it is uploading?

Here is my data sending code for reference.
<!-- language-all: lang-cpp -->

    jsonBuffer.clear();
    JsonObject &rootObject = jsonBuffer.createObject();
    JsonObject &dataObject = rootObject.createNestedObject("data");
    JsonArray &X1dataObject = dataObject.createNestedArray("X1");
    JsonArray &Y1dataObject = dataObject.createNestedArray("Y1");
    JsonArray &Z1dataObject = dataObject.createNestedArray("Z1");

    if (wifiMulti.run() == WL_CONNECTED) {
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }

    if (send_flag) {
      send_flag = false;
      int connection_iterator = 0;
      int connection_iterator2 = 0;
      for (int iterator = 0; iterator < SAMPLE_SIZE; iterator++) {
        X1dataObject.add(X1dataArray[iterator]);
        Y1dataObject.add(Y1dataArray[iterator]);
        Z1dataObject.add(Z1dataArray[iterator]);
      }

      rootObject["coreid"] = String(low, HEX) + String(high, HEX);
      //rootObject["coreid_high"] = String(high, HEX);
      rootObject["sample_time"] = int(time_taken);
      rootObject["firmware_version"] = FIRMWARE_UPDATE_VERSION;
      rootObject.prettyPrintTo(Serial);
      Serial.print("connecting to ");
      Serial.println(host);
      while ((!client.connect(host, httpsPort)) && !setup_mode) {
        connection_iterator++;
        Serial.println("connection failed! Retrying..");
        digitalWrite(LED2, HIGH);
        delay(5000);
        digitalWrite(LED2, LOW);
        delay(5000);
        if (connection_iterator >= 10)
          ESP.restart();
      }
      if (client.verify(fingerprint, host)) {
        Serial.println("certificate matches");
      } else {
        Serial.println("certificate doesn't match");
      }
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.print("requesting URL: ");
      Serial.println(url);
      client.println(String("POST ") + url + " HTTP/1.0");
      client.println(String("Host: ") + host);
      client.println("Cache-Control: no-cache");
      client.println("Content-Type: application/json");
      client.print("Content-Length: ");
      client.println(rootObject.measureLength());
      client.println();
      //rootObject.printTo(client);
      Serial.println("NUMBER OF INTERRUPTS:");
      Serial.println(interruptCounter);
      Serial.println("request sent");
      while ((client.connected()) && !setup_mode) {
        connection_iterator2++;

        String line = client.readStringUntil('\n');
        if (line == "\r") {
          Serial.println("headers received");
          break;
        }
        Serial.println("Waiting for response");
        digitalWrite(LED2, HIGH);
        delay(1000);
        digitalWrite(LED2, LOW);
        delay(1000);
        if (connection_iterator2 >= 20)
          break;

      }
      String line = client.readStringUntil('\n');
      if (line.startsWith("{")) {
        Serial.println("esp8266/Arduino CI successfull!");
      } else {
        Serial.println("esp8266/Arduino CI has failed");
      }
      Serial.println("reply was:");
      Serial.println("==========");
      Serial.println(line);
      Serial.println("==========");
      Serial.println("closing connection");
      digitalWrite(LED_BUILTIN, LOW);
      // readRegister(INT_SOURCE, 1, &dummy_read);
    }

title: Reducing json upload time

Answers: 0


body:
I'm writing some code that compares information from two Arduino Unos by an Arduino Mega 2560. The problem that I'm having is that when I read the information coming in through `Serial1` and `Serial2` on my `if` statements, I get both inputs out on my serial monitor for the Mega, but if I try to compare them after I have read them it comes out not working the way it is intended. I don't know if I might be missing some syntax on my code or if I'm doing this wrong but I would appreciate any help I can get.

    byte inData;

    byte inDataTwo;

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial2.begin(9600);

      while (!Serial)
      {
        ; // wait for serial port to connect. Needed for native USB port only
      }
    }

    void loop()
    {
      if (Serial1.available()>0 )
      {
          inData = Serial1.read();
          Serial.print(char(inData));
      }
      if (Serial2.available()>0)
      {
        inDataTwo = Serial2.read();
        Serial.print(char(inDataTwo));
      }
      if(inData == inDataTwo)
      {
        Serial.print("true");
      }
      else
      {
        Serial.print("False");
      }
    }`

title: How can I compare two serial port readings on Arduino Mega?

Answers: 1

body:
I think your code is implemented wrong in general. Even if it worked "like intended" it would not behave like you might want it to.

The first problem is, that you are polling for bytes that are received **asynchronuously**. That means that  two byte sequences must not only be equal, they must also be sent "at the same time" if they should pass your comparison test. As the atmega will `loop()` very fast, there is only very little tolerance in timing.

Secondly, the variables you write received values to are not reset, meaning that once they have the same value they will pass the if statement until another byte has been received. Actually they aren't initialized and therefore will be `0` at the very beginning. So I wonder why you don't get your `Serial` interface flushed with `true`. Is this actually the entire code?

As a solution I suggest accumulating received bytes into a buffer and waiting for a soecific termination byte (often `/n`). If a termination character has been received, perform the comparison on that buffer.


body:
I’m trying to use Arduino Nano to run my 5 V PC fan, which, I know it sounds crazy, it’ll be mounted on a piece of Tupperware that’ll control the airflow through it via the fan. However I have no idea how to code the Arduino, but I do know how to code other things when I’ve done it in class. The setup is a 5 V rechargeable lithium ion portable battery connected to the switch which would be connected to the Arduino, and when the switch is triggered/flipped it would allow power to the Arduino, boot it up, and trigger the code that would tell the fan to run at specific intervals. The idea for intervals is a result of the battery only having 23 hrs and 10 minutes of continuous battery life while powering the fan. The pseudocode would look something like:

> Press bump switch, it turns on the Nano with the ensuing program. Twice an hour, the Nano starts the fan. The fan runs for 20 seconds to 30 seconds each time the fan is started. After a set of 48 on/off cycles have completed (24 hours), the Nano is set to sleep mode in order to save power. In order to restart cycles, user must press bump switch again.

I’m pretty sure I have the hardware side of things down but if I don’t please do inform me.

I’ve attached a picture of what it’ll approximately look like, with the battery at the left, switch in the middle, then the Arduino (not seen in picture), then the fan.

[![Photo of LiPo battery, switch and fan][1]][1]

I know this is asking a lot when I don’t even know where to get started with the coding, but I’d be sincerely eternally grateful.

  [1]: https://i.stack.imgur.com/K0bqg.jpg "Photo of LiPo battery, switch and fan"

title: Help with coding Arduino Nano to run fan through slide switch at specific intervals

Answers: 1

body:
You can't run the fan directly from an Arduino pin. The fan will require to much current for that to work. Instead connect the fan, via a transistor/mosfet to the Arduino.

Also add a (flyback-)diode to the fan, as turning of the fan can create huge (but short) voltage spikes, which can damage the transistor/mosfet.

Pseudo code would be something like:

    for( byte i=0; i<48; i++ )
    {
      digitalWrite(fanPin, HIGH);
      delay(20000);
      digitalWrite(fanPin, LOW);
      delay(1780000);
    }

You could also put the Arduino in sleep mode, during those half hours, as well. You could use the [LowPowerSleep](https://www.arduino.cc/en/Reference/LowPowerSleep) library. Then replace the `delay(ms)` with `LowPower.sleep(ms)`.

Lastly, some powerbank will automatically shut down, if the detect nothing is using power. The Arduino, without the fan on, will use so little current (compared to charging a phone) that such a powerbank would shut of.


body:
Hey guys I have run my example with esp8266 2.4.2 version now I'm getting following error while compiling- C:\Users\Shree\Desktop\FirebaseDemo_ESP8266ex\FirebaseDemo_ESP8266ex.ino:21:29: fatal error: FirebaseArduino.h: No such file or directory #include <FirebaseArduino.h> ^ compilation terminated. exit status 1 Error compiling for board NodeMCU 1.0 (ESP-12E Module).

I'm trying to run FirebaseDemo_ESP8266 example but getting problem to compile that code. plzzz help me to solve this issue.

title: Error while compiling CODE

Answers: 0


body:
I've been struggling with some code that was failing to "begin()" any devices on my i2c bus. I've uploaded a scanner program from arduino playground which lists the addresses of any i2c modules found.  With a single sensor connected the whole arduino freezes but when I unplug the wires from the a4 and a5 pins it continues. Plug them back on and it locks. I've tried with the SDA / SCL wires reversed as I've seen mention of things being backward.

Anyone know what I'm missing?

title: Lost with Nano and i2c

Answers: 0


body:
I am new to Arduino project. I used MQ7 flying fish sensor to sense the CO.

[![Photo of MQ7 (top)][1]][1]

[![Photo of MQ7 (bottom)][2]][2]

Ok now I connected everything as mentioned in various tutorials, such as [Arduino CO Monitor Using MQ-7 Sensor][3].

Also wrote this code based on the following tutorial

    const int mq7Pin=0;//the AOUT pin of the CO sensor goes into analog pin A0 of the arduino

    int mq7value;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);//sets the baud rate
      pinMode(mq7Pin, INPUT);
    }

    void Heat(){
      Serial.println("Heating sensor");
      analogWrite(mq7Pin,255);
      delay(60000);
      Serial.println("Reducing the voltage");
      analogWrite(mq7Pin,71); //HIGH*1.4v/5v => 255*1400/5000
      delay(90000);
    }

    void Read(){
      mq7value=analogRead(mq7Pin);
    }

    void Print(){
      Serial.print("CO : ");
      Serial.println(mq7value);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Heat();
      Read();
      Print();
      delay(60000);
    }

After this I got the following output:

    Heating sensor

    Reducing the voltage

    CO : 82

    Heating sensor

    Reducing the voltage

    CO : 246

I used the sensor in a hall and I got `82` in clean air.

After that I used smokes from incense sticks, and I got `246` as sensor value.

So my question is in what format did sensor returned these values? Are they in PPM format?

If not, how can I convert it?

  [1]: https://i.stack.imgur.com/neoN3.jpg "Photo of MQ7 (top)"
  [2]: https://i.stack.imgur.com/JRfP4.jpg "Photo of MQ7 (bottom)"
  [3]: https://www.instructables.com/id/Arduino-CO-Monitor-Using-MQ-7-Sensor/

title: MQ7 Flying Fish output format

Answers: 0


body:
Can I get help to connect Arduino Mega 2560 and servo motor in Proteus 7.8
correctly because I tried this connection, in the image below, with `sweep.ino.hex` in the Arduino software examples but did not work!

[![Connection between Arduino Mega 2560 and servo motor][1]][1]

  [1]: https://i.stack.imgur.com/xQ8IL.jpg "Connection between Arduino Mega 2560 and servo motor"

Answers: 0


body:
I want to try this example, [A Simple Function for Reading CSV Text Files][1], in order to read a .csv file from an SD card, but I don't have the SD card reader module and can't find it in my country.

What I have found everywhere is this sound module, [WTV020-SD][2], and I wonder if I can use that to read a single .csv file from it, using the SD Arduino library. I checked the module's documentation and there's nothing about it in there.

  [1]: https://forum.arduino.cc/index.php?topic=340849.0
  [2]: https://dlnmh9ip6v2uc.cloudfront.net/datasheets/Widgets/WTV020SD.pdf

title: Can I use WTV020 sound module as SD card reader?

Answers: 1

body:
It seems unlikely, for if you compare the schematic of the WTV020-SD (card reader part only) from the data sheet that you provided:

[![WTV020-SD (card reader part only) schematic][1]][1]

to the schematic of a bog standard SD card reader:

[![Standard SD card reader schematic][2]][2]

they are not the same. Instead of interfacing directly to the Arduino, as the standard SD card reader does, the WTV020-SD has additional logic, in the form of a WTV020SD-20S IC.

Therefore the code on the Arduino forums is highly unlikely to work.

  [1]: https://i.stack.imgur.com/1vRTv.png "WTV020-SD (card reader part only) schematic"
  [2]: https://i.stack.imgur.com/lHG42.jpg "Standard SD card reader schematic"


body:
I am trying to create a circuit that will turn my motor when I clap. When the first limit switch is low, and there is only one clap, a solenoid pin is supposed to be engaged (currently an LED), but when I clap once without pressing the limit switch, my LED turns on.

Also, I can't seem to get my code to work properly with the limit switches, to control my motor.

I am not sure what is wrong, can someone help?

I have an Arduino Uno with the following code:

```
#define sound_Sensor 2
#define EN1 9
#define IN1 8
#define IN2 7
#define solenoid_pin 6
#define LimSwitch1 4
#define LimSwitch2 3

int lastSoundValue;
int soundValue;
long lastNoiseTime = 0;
long currentNoiseTime = 0;
int solenoidPinStatus = LOW;
int status_motor = LOW;
int clap_interval = 200;
int claps = 0;
int pos1 = 1;
int pos2 = 1;

void setup() {
  pinMode(sound_Sensor, INPUT);
  pinMode(EN1, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(solenoid_pin, OUTPUT);
  pinMode(LimSwitch1, INPUT);
  pinMode(LimSwitch2, INPUT);
}

void loop() {

  soundValue = digitalRead(sound_Sensor);
  currentNoiseTime = millis();
  if (soundValue == 1 && lastSoundValue == 0 && (currentNoiseTime > lastNoiseTime + 200))
  {
      if (claps == 0) // allow first to register without much condition
      {
          claps = 1;
          lastNoiseTime = currentNoiseTime;
      }
      else
      {
          if (currentNoiseTime > lastNoiseTime + clap_interval)
          {
              claps++;
              lastNoiseTime = currentNoiseTime;
          }
      }
      Serial.print(claps);
  }
  else
  {
      if (currentNoiseTime > (lastNoiseTime + 3 * clap_interval)) // no claps for a longer duration time to print and/or reset clap
      {
          if (claps > 0)
          {
              while(status_motor == LOW){
                  if (digitalRead(LimSwitch1) == LOW && claps == 1)
                  {
                    solenoidPinStatus = HIGH;
                    digitalWrite(solenoid_pin, HIGH);
                  }

                 if (digitalRead(LimSwitch1) == LOW)
                 {
                    pos1 = 2;
                    status_motor = HIGH;
                    digitalWrite(IN1, HIGH); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    analogWrite(EN1, 200); //Set Speed of Motor
                  }
                 else if (digitalRead(LimSwitch2) == LOW)
                 {
                    pos2 = 2;
                    status_motor = HIGH;
                    digitalWrite(IN1, HIGH); //Turns on Motor99++
                    digitalWrite(IN2, LOW);
                    analogWrite(EN1, 200); //Set Speed of Motor
                 }
              }

              while(status_motor == HIGH){
                if (pos1 == 2 && digitalRead(LimSwitch2) == LOW)
                {
                    status_motor = LOW;
                    digitalWrite(IN1, LOW); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    pos1 = 1;
                }

                else if (pos2 == 2 && digitalRead(LimSwitch1) == LOW)
                {
                    status_motor = LOW;
                    digitalWrite(IN1, LOW); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    pos2 = 1;
                }
              }
          }
             claps = 0; ///reset
      }
  }

// if (solenoidPinStatus == HIGH && status_motor == LOW && digitalRead(LimSwitch1) == LOW)
// {
//   solenoidPinStatus = LOW;
//   digitalWrite(solenoid_pin, LOW);
// }
  lastSoundValue = soundValue;
}
```
Sorry my wire diagram may not be the easiest to look at...

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

title: My Code turns on my LED even when my switch is not pressed

Answers: 1

body:
I think your problem might be connected to wiring.

This is one of the ways you can correctly connect a switch to Pin 8.

[![Arduino with switch][1]][1]

In this case you need to configure Pin 8 as INPUT_PULLUP to use internal "pullup" resistor. When switch is not pressed Pin8 is connected to 5V through that resistor and value on the pin is HIGH. When you press the switch it connects Pin 8 to ground (the resistor prevents a short) and that way value on Pin 8 is LOW.

This is code that works correctly with the design above

    void setup()
    {
      pinMode(8, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop()
    {
      if (digitalRead(8) == HIGH)
      {
        Serial.println("It's HIGH");
      }
      else
      {
        Serial.println("It's LOW");
      }

      delay(1000);
    }

If you do not configure Pin 8 as INPUT_PULLUP but just normal INPUT (as you did in your code) when the button is not pressed Pin 8 is "floating" (it's not connected to anything) and on a "floating" pin values are random.

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


body:
Is it possible to program a custom description so that my python program can know exactly what USB port to connect to for that specific programming?

It should be able to find any board with that program so the best approach is if a custom description can be programmed with the active program being uploaded.

I want to make sure my setup can handle multiple Arduino boards and always know what USB to use for each specific use.

This finds a general Arduino device:

    for port in serial.tools.list_ports.comports():
     if "Arduino" in port.description:
      print "Arduino device!"

But I want something like this:

    for port in serial.tools.list_ports.comports():
     if "proximity_sensor" in port.description:
      print "My specific Arduino program!"

title: Programming the serial description

Answers: 1

body:
On a normal Arduino board, no, it's not possible from a sketch POV. With a Leonardo or similar ATMega32U4 based board it may be possible to give it a unique VID/PID combination, and even possibly custom manufacturer and product strings. You may be able to do it by creating a custom board definition in boards.txt (or maybe manipulation of the AVR core) - but I have never tried that sort of thing with Arduino, so I cannot vouch for how easy it would be.

However (*shameless self-promotion coming here...*) if you were to switch away from Arduino and use a chipKIT board like the Lenny (or any of the other chipKIT boards with a direct USB connection, such as the Fubarino boards) then it is possible to craft a completely custom USB profile from within your sketch, including VID/PID, Manufacturer and Product strings, and even what devices the board implements. For example:

    USBFS usbDevice;
    USBManager USB(usbDevice, 0xf055, 0x1234, "Espentech", "My Little Widget");
    CDCACM USBSerial;

    void setup() {
        USB.addDevice(USBSerial);
        USB.begin();
    }

    void loop() {
        USBSerial.println(millis());
        delay(1000);
    }

Which results in:

    [  661.328155] usb 2-1.2.7: new full-speed USB device number 10 using ehci-pci
    [  661.458613] usb 2-1.2.7: New USB device found, idVendor=f055, idProduct=1234
    [  661.458616] usb 2-1.2.7: New USB device strings: Mfr=1, Product=2, SerialNumber=3
    [  661.458619] usb 2-1.2.7: Product: My Little Widget
    [  661.458621] usb 2-1.2.7: Manufacturer: Espentech
    [  661.458623] usb 2-1.2.7: SerialNumber: CK2660A05312F3
    [  661.459181] cdc_acm 2-1.2.7:1.0: ttyACM0: USB ACM device


body:
I was testing analog output from a microphone (Max9814) with an Arduino Uno, which came with nice results. The output provided by the microphone is converted into sound and is loud and clear.

Setup: (Max to Uno)

 - Pin Vdd to 3,3V
 - Pin GND to GND
 - Pin Out to A0

---

However when I tried to set it up with an ESP12e instead of an Uno, I got a lot of 'noise' and no clear sound at all.

Here I used the following setup: (Max to ESP)

 - Pin Vdd to VCC (VCC is measured at 3.3v with a multimeter)
 - Pin GND to GND
 - Pin Out to AD0

**A little 'side step'**

The problem arised that the analog output from the microphone delivered a voltage of around 1.24, while the ESP12e analog has 1v as max input. This made the analogRead max out all the time. For this reason I put a 10k OHM resistor between the OUT and AD0 combined with a 20k OHM resistor between gnd and AD0. This resulted into nice analog readings (instead of 1024, around 400-500 all the time).

However, like mentioned before, a lot of noise is in between and the sound is not clear. (I also tried to work with 'sample windows', here is the 'filtering mechanism' which can be found on many sites/questions and works perfectly fine):

    //(global logic is set to take n samples and than print the line)
    //Tried n of 5 to 20
    //Also instead of just samples tried the micros variant instead of just samples which is also found on many sites to create a time window to record.
    unsigned int sample = analogRead(A0);
    if (sample < 1024) {  // toss out spurious readings
      if (sample > signalMax) {
        signalMax = sample;  // save just the max levels
      } else if(sample < signalMin) {
        signalMin = sample;  // save just the min levels
      }
    }

    unsigned int peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
    Serial.println(peakToPeak);

Does somebody have a clue why the Arduino gives such clear and good sound, while the ESP12e does not. (The analog values do not 'seem' to differ much in the levels)

title: Analog reading with noise - Arduino Uno VS ESP12e

Answers: 1

body:
The ESP8266 is an incredibly (electrically) noisy environment.

Because you can't use anything except the internal voltage reference, which is in turn driven from the internal noisy power, you can't get anything even vaguely approaching stable readings.

It is recommended to disable the WiFI completely ("Modem Sleep") when doing ADC readings to reduce noise.

However, the ADC was never intended for this kind of work. Its primary role is for monitoring the battery voltage of your hardware - and as such it really doesn't care that much about noise, since you can average a number of samples for greater accuracy (something you can't really do with audio).


body:
I have an ESP32 and want to connect it to the WLAN at my office. Based on my current knowledge of the Arduino, we use the `WiFiClass` to connect to a WLAN and then use a `WiFiClient` to use the WiFi for data transfer.

In order to connect to the WLAN at my office, a certificate is needed. I have asked the network guys to issue a x.509 certificate and plan to use the `WiFiSecureClient` class.

The problem is that my `WiFi.begin(ssid)` method never leaves the following `while` loop:

    Wifi.begin(ssid); // my office needs a certificate to connect to the wifi at the first place
    while (WiFi.status() != WL_CONNECTED)
    {
    delay(500);
    Serial.print(".");
    }

Note that to connect to my office network, no password is needed. The x.509 certificate is enough for the connection to establish.

Only after a WiFi connection is established, I can set the `WiFiSecureClient` parameters of the CA. But to connect to the WiFi, I need the certificate.

This is very confusing. Could someone please clarify a way our for me in this situation.

title: WiFi Connection With a Enterprise WLAN

Answers: 1

body:
The Arduino API for ESP32 does not support your desired configuration.

The ESP32 is capable, but there is no easy "Arduino" interface to configure it.

Instead you will have to directly interface with the ESP32 SDK and configure things manually.  That won't be easy.

[This example code](https://github.com/espressif/esp-idf/tree/master/examples/wifi/wpa2_enterprise) shows you how it can be done - however that code is not designed to run in the Arduino environment, so you will first need to understand exactly what it is doing and then adapt it to suit.


body:
I'm working on this piano project. When I push a button one of the led light is suppose to turn on and a tone comes out of the piezo. The LCD screen is suppose to print out a sentence but I can't get it to work.

Here is a picture of the board ( everything works except the LCD) I think the problems lies in the power supply but I'm not sure. This is the first time I use a big breadboard. [![Image of the board][1]][1]

Here is my code:

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(13,12,11,10,9,8);

    int p1 = 1;
    int p2 = 2;
    int p3 = 3;
    int p4 = 4;

    int C,D,E,F;
    int buzz = 5;

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

      lcd.print("hello, world!");

      Serial.begin(9600);
      pinMode(p1,INPUT);
      pinMode(p2,INPUT);
      pinMode(p3,INPUT);
      pinMode(p4,INPUT);

    }

    void loop()
    {

      lcd.setCursor(0, 1);

      lcd.print(millis() / 1000);

      C = digitalRead(p1);
      D = digitalRead(p2);
      E = digitalRead(p3);
      F = digitalRead(p4);

      if(C == 1){

        tone(buzz,523);
      }else if(D == 1){
        tone(buzz,587);
      }else if(E == 1){
        tone(buzz,659);
      }else if(F == 1){
        tone(buzz,698);

      }else{
        noTone(buzz);
      }
      delay(50);
    }

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

title: Problem with LCD

Answers: 2

body: The LCD is not powered, there are 2 separated power rails... use a wire to connect both rails.

body:
the power rails are separated in the middle of the breadboard. bridge them with jumper wires

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

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


body:
Android Arduino Mega SerialPort1 SerialPort2 SerialPort3

Is it possible to connect three Android tablets to the Arduino mega through three SerialPort? Rx1 Tx1; Rx2 Tx2; Rx3 Tx3

I managed to connect only one device directly through the cable, but this is only one device.

title: Connect three android to one arduino mega

Answers: 0


body:
Is there anyway to send a string from an Arduino UNO to a ESP8266-01 (one with only 8 pins RX, TX, CH-PD, vcc, ground, reset, GPIO0, GPIO2) without using without using AT commands.  I've looked everywhere and from what I can see UART doesn't work and SoftwareSerial uses only AT commands.  I am at my wits end.  Can anyone help here? please.
I have tried Serial.write but only writes String and Esp8266 only receives ints.

I found some code I thought might work but so far I can see that the arduino is sending <100.00:200:00>, but on the esp8266 all I get is four backwards question marks

this is the code on the Arduino UNO

    #include <SoftwareSerial.h>

    SoftwareSerial ESPserial(2, 3); // TX | RX
     float water = 100.00;
     float battery = 200.00;
    void setup()
    {
        Serial.begin(9600);     // communication with the host computer
        //while (!Serial)   { ; }

        // Start the software serial for communication with the ESP8266
        ESPserial.begin(57600);

    }

    void loop()
    {
       ESPserial.print("<");
              ESPserial.print(water,2);
              ESPserial.print(":");
              ESPserial.print(battery,2);
          ESPserial.print(">");
          Serial.print("<");
              Serial.print(water,2);
             Serial.print(":");
              Serial.print(battery,2);
          Serial.print(">");
         delay(10000);
    }

and here is the code on the ESP8266

    #include <SoftwareSerial.h>
    #include <string.h>

    SoftwareSerial ESPSerial(2,0);

    const byte numChars = 32;
    char receivedChars[numChars];
    boolean newData = false;

    String water;
    String battery;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      ESPSerial.begin(57600);
      delay(10);

    }

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

     water= getValue(receivedChars, ':', 0);
      battery = getValue(receivedChars, ':', 1);
    Serial.println(water);
    }

    void recvWithStartEndMarkers() {
        static boolean recvInProgress = false;
        static byte ndx = 0;
        char startMarker = '<';
        char endMarker = '>';
        char rc;

        while (ESPSerial.available() > 0 && newData == false) {
            rc = ESPSerial.read();

            if (recvInProgress == true) {
                if (rc != endMarker) {
                    receivedChars[ndx] = rc;
                    ndx++;
                    if (ndx >= numChars) {
                        ndx = numChars - 1;
                    }
                }
                else {
                    receivedChars[ndx] = '\0'; // terminate the string
                    recvInProgress = false;
                    ndx = 0;
                    newData = true;
                }
            }

            else if (rc == startMarker) {
                recvInProgress = true;
            }
        }

The Arduino sends writes every 10 seconds and the esp prints the ???? every 10 seconds but with a lag.

I am not sure what the pin out to pin in should be.  Right now I have the Arduino 2(TX) attached to the GPIO0 and the Arduino 3(RX) attached to the GPIO2.

Can someone look at my code and see what I am doing wrong.  I thought I would send over two values because eventually I want to show water level and battery level.

title: Send data string from Arduino UNO to ESP8266-01

Answers: 2

body:
I figured this out.
send code is

Arduino Uno side

     f = String('<')+String("Hi")+String(',')+String(waterSensorOutValue)+String(',')+String(sensorBatValue)+String('>');

        Serial.print(f);

ESP side

    const byte numChars = 32; char receivedChars[numChars]; char tempChars[numChars];        // temporary array for use when parsing // variables to hold the parsed data char messageFromPC[numChars] = {0}; float floatFromPC = 0; float floatFromPC2 = 0; boolean newData = false; //end stuff ti bring in string String f;  long itt = 500;
        long itt2 = 500;

    void loop() {

      //new stuff string recvWithStartEndMarkers();
        if (newData == true) {
            strcpy(tempChars, receivedChars);
                // this temporary copy is necessary to protect the original data
                //   because strtok() used in parseData() replaces the commas with \0
            parseData();
            showParsedData();
            newData = false;
        } }

    void recvWithStartEndMarkers() {
        static boolean recvInProgress = false;
        static byte ndx = 0;
        char startMarker = '<';
        char endMarker = '>';
        char rc;

        while (Serial.available() > 0 && newData == false) {
            rc = Serial.read();

            if (recvInProgress == true) {
                if (rc != endMarker) {
                    receivedChars[ndx] = rc;
                    ndx++;
                    if (ndx >= numChars) {
                        ndx = numChars - 1;
                    }
                }
                else {
                    receivedChars[ndx] = '\0'; // terminate the string
                    recvInProgress = false;
                    ndx = 0;
                    newData = true;
                }
            }

            else if (rc == startMarker) {
                recvInProgress = true;
            }
        } }

    //============

    void parseData() {      // split the data into its parts

        char * strtokIndx; // this is used by strtok() as an index

        strtokIndx = strtok(tempChars,",");      // get the first part - the string
        strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC

        strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
        floatFromPC = atoi(strtokIndx);     // convert this part to an integer

        strtokIndx = strtok(NULL, ",");
        floatFromPC2 = atoi(strtokIndx);     // convert this part to a float

    }

    //============

    void showParsedData() {
        Serial.print("Message ");
        Serial.println(messageFromPC);
        Serial.print("Float ");
        Serial.println(floatFromPC);
        Serial.print("Float ");
        Serial.println(floatFromPC2); } //end new stuff string

Then connect to wifi and upload to ThingSpeak.

I had to get rid of Softwareserial and connect the RX on the Arduino Uno to the TX on the ESP8266-01 and the TX on the Arduino Uno to the RX on the ESP8266-01.

Everything worked great till I changed from an Arduino UNO R3 to an Arduino Pro Mini for size and energy conservation.

With the wiring the same (I think) and the code the same the string (f) doesn't get sent over to the ESP.  I don't see the TX led flashing on the Pro Mini when it should be transferring string(f) and nothing gets uploaded to ThingSpeak.  Not sure why but I will post another question for that one.  Thanks for everyone's help.

body:
Sending data between Arduino and NodeMcu (Serial Communication)

youtube link  (in French):

https://youtu.be/0TXmi9EgaCs


body:
I am trying to send SMSs using a GSM module with Arduino Mega. I have followed a tutorial and downloaded the SIM908IDE100 library. I am using the function

`SendSMS(String&, const char [27]);`.

It works fine when I type:

`sms.SendSMS("1234567890","Text message");`

where "1234567890" is the telephone number I want to send the SMS to and "Text message" is the text of the SMS.

If I instead try to pass to the function a String containing the telephone number

`String number = "1234567890";
sms.SendSMS(number,"Text message");`

I get the following error:

`exit status 1
no matching function for call to 'SMSGSM::SendSMS(String&, const char [27]);'`

I don't understand what String followed by an ampersand means. What am I supposed to pass the function as its first argument?

title: Problem with String& argument of a function

Answers: 1

body:
The function prototype in [sms.h][1] is

    char SendSMS(char *number_str, char *message_str);

if `number` is `String`, you should have

    sms.SendSMS((char*) number.c_str(),"Text message");

`c_str()` is a function of the Strinng class. It returns a pointer to internal char array of the String object.

The cast to `char*` is necessary because the author of the library didn't make the parameter constant with `const char*`. (It is a good practice, to declare pointers and references as constants.)

The error message `no matching function for call to 'SMSGSM::SendSMS(String&, const char [27]);` shows the arguments you try to use. `String&` is reference to some instance of the `String` type

  [1]: https://github.com/fffaraz/gpst/blob/master/gsm-shield-arduino/branches/SIM908IDE100/sms.h


body:
I have tried it several times myself but i never could send or receive it properly. I am asking myself if it is possible and if so could someone explain how?

Cheers.

title: Is it possible to send a float Array over I2c

Answers: 1

body:
Below is a simple rewrite of the Master Writer/Slave Receiver Wire Tutorial, https://www.arduino.cc/en/Tutorial/MasterWriter, for a vector of floating-point numbers.

**Master Writer Sketch**

    #include <Wire.h>

    const int DEVICE = 8;

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

    void loop() {
      const int VEC_MAX = 6;
      float vec[VEC_MAX];
      uint8_t* vp = (uint8_t*) vec;

      Wire.requestFrom(DEVICE, sizeof(vec));
      while (Wire.available()) {
        *vp++ = Wire.read();
      }

      for (int i = 0; i < VEC_MAX; i++) {
        Serial.println(vec[i]);
      }

      delay(500);
    }

**Slave Receiver Sketch**

    #include <Wire.h>

    const int DEVICE = 8;
    const int VEC_MAX = 6;
    float vec[VEC_MAX] = { ... };

    void setup() {
      Wire.begin(DEVICE);
      Wire.onRequest(requestEvent);
    }

    void loop() {
      delay(100);
    }

    void requestEvent() {
      Wire.write((uint8_t*) vec, sizeof(vec));
    }

> Is it possible to send a float Array over I2c

So I would answer - Yes.


body:
I'm executing this code to control a LED with GSM SIM900 message but there are two problems. First, it receives messages sometimes and some times doesn't. The second is that it doesn't execute the `if` conditions that are on the GSM message when received.

Is there a problem with my GSM module? Can any one help?

    #include <SoftwareSerial.h>
    SoftwareSerial gsm(9,10);
    String msg;
    const int LED = 13;

    void setup() {
      gsm.begin(9600);
      Serial.begin(9600);
      Serial.println("PUMP CONTROL");
      Serial.println("t : to receive text");
      delay(1000);

      pinMode(LED, OUTPUT);
      digitalWrite(LED, LOW);
    }

    void loop() {
      if (Serial.available()>0)
      switch(Serial.read())
      {
        case 't':
        showSMS();
        break;
      }

      while(gsm.available() > 0)
      {
        Serial.write(gsm.read());
      }
      if ( msg == "ON")
      {
        Serial.println("ON");
        digitalWrite(LED, HIGH);
         Serial.println("ON1");
        delay(1000);
      } else if (msg == "OFF")
      {
        digitalWrite(LED, LOW);
        delay(1000);
      }
      if(msg != "") msg = "";
    }

    void showSMS()
    {
     gsm.print("AT+CMGF=1\r");
     gsm.print("AT+CNMI=2,2,0,0,0\r");
     delay(1000);
     msg = "";
     while(gsm.available() > 0)
     {
      msg += gsm.read();
     }
     Serial.println(msg);
    }

title: Conditions with GSM module SIM900 doesn't execute

Answers: 1

body:
I’ve solved the condition problems by making the condition with the ASCII code of ON and OFF.

I replaced:

    if ( msg == “ON”)

with

    if(msg.indexOf("ON")>=0)

and replaced:

    else if (msg == "OFF")

with

    if(msg.indexOf("OFF")>=0)


body:
I'm running a sample code from ESP32 examples and I'm scanning available BLE devices. I can see device MAC address etc. But for few devices I can't see their names.
I am using ESP-WROOM-32 with hardware support checked out directly from their github (some bugs were fixed earlier on github than via lib manager)

When I use LightBlue app for discovery of BLE Devices I can see names for more devices that ESP. What can I change to see the names correctly? OR Can how can I parse device name from the data I'm receiving?

This callback code

    class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
        void onResult(BLEAdvertisedDevice advertisedDevice) {
          Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
          Serial.print(" RSSI: ");
          Serial.println(advertisedDevice.getRSSI());
        }
    };

produces this output:

    Advertised Device: Name: , Address: 1d:0c:c7:3a:fb:c6, manufacturer data: 4c0009060378c0a81f12, payload: 1073609632
     RSSI: -75

title: ESP32 bluetooth discovery parse names

Answers: 1

body:
Bluetooth has two ways of dealing with device names. A device can optionally choose to advertise its device name. It also has to respond to a "get device name" request. The former is passive, and is what you normally see when scanning. The latter is active and requires you to connect to the device and make a request. If the device doesn't advertise the device name then the only way you can get the name is to make a GATT "Name Characteristic" request to the device. The ESP32 doesn't (AFAIK) do that automatically because these things are designed to be "light weight". Your heavier-weight "reference" software can go off and do more things because it's a full-blown application.

You can sometimes see the difference in the devices because your reference application might populate the list of devices with a combination of MAC addresses and names, and then replace the MAC addresses with names in a later step. Also it probably caches names that it has queried in the past.


body:
How can I hook up four (adafruit) MMA8451 accelerometers (using I2C protocol) using one Arduino Mega? What I'm confused about is I only have one SDA and SCL on the Arduino Mega obviously. So how can I connect these all? Multiplexer? I need four because I have one on each leg of a robot. Or is perhaps this impractical to put an accelerometer on each leg of robot? I'm a little new to electronics so please explain in depth if you could. Thanks.

Note to moderators: I just would really love an answer to this even if this doesn't meet the super strict question guidelines. It seems every time I post here there's always that one person who takes it down for any number of trivial reasons. Please let me get an answer at least. Thank you!

title: How can I hook up multiple MMA8451 accelerometers, (I2C protocol) using one Arduino Mega?

Answers: 4

body:
Brief explanation: When you talk to the slave device through I2C you start with (slave) device address. Then you send the message. It is like calling your colleague in an office with many other people. You say: "John", and when he is aware you continue with message, like "let's go for coffee".

This arrangement allows for adding up to 127 devices on one I2C bus. Each device must have different address (sorry, you cannot have two John's in the office, it will cause conflict). Generally two different type of devices will have different I2C addresses, but it may happen you need to use two (or more) of the same (like in your example). In this case, see below.

Many devices with I2C interface allows for address change. Using this facility you are able to communicate with many of the same devices through the same pair of cables.
You can check if your chosen accelerometer has possibility for address change: On picture below there is one with Address tab. When jumper is not fitted, you will get one address, when is fitted, the address of this device will be different, allowing of two of this accelerometers on one I2C bus. Unfortunately in this example there will be possibility of maximum of two of the same devices.
[![Accel][1]][1]

Of course there are devices with more than two possible addresses, you need to search for them.
And, yes, it is fine to use one Arduino to communicate with many I2C devices.

EDIT:
Looking after some of Adafruit accelerometers, I have found this page: [https://learn.adafruit.com/i2c-addresses][2]

And small off topic note: If you struggling on finding I2C with more than 2 addresses, check if it is easier to use SPI protocol. In this case you need (edited to correct bus lines names after user CrossRoads comment) MISO, MOSI, SCK and CS (chip select) wires. Chip select is individually connected to each slave device. This allows selecting particular device without addressing issue.

  [1]: https://i.stack.imgur.com/OuGrb.png
  [2]: https://learn.adafruit.com/i2c-addresses

body:
Talking about I2C protocol. The slave Address is of 7 Bits that means one I2c can handle 127 Slave I2C devices of different address. So you can connect 127 devices with Single I2C Port just make sure there slave address is different from each other.

Some I2C devices are provided with the option to select salve address by setting some pins high and low. If you are using some identical sensors you are set their slave address different.

body:
The general technique for addressing multiple I2C devices is:

1. If the device(s) have only one address: use an I2C bus multiplexer.
2. If the device(s) have two addresses controlled by an addressing pin: use digital output pins from the Arduino to select which device to address, e.g., set the control pin for the selected device low and others high and use the corresponding address to address the device.

With MMA8451Q, factory default it has two distinct I2C addresses 0x1C and 0x1D, controlled by the SA0 pin, use digital output pins on the Arduino Mega to address the selected device (address 0x1C) by setting the corresponding output pin low for the selected device and the control pin for the others to high (address 0x1D). Use address 0x1C to interact with the selected device.

Cheers!

body: Simple just connect all SCK and SDL accelerometer lines together and then u just need to get a specific code address in your use to get a data from any of the accelerometers


body:
I'd like to be able to import a number of components (e.g Arduinos, MPU6050s, displays, motor drivers, LEDs, etc) into an app of some sort then be able to wire those components to each other for the purpose of being able to refer to this crude schematic at a later point or to share it with others. I tried importing things into Eagle, but that seemed like an absolute overkill (if Eagle can be used for something like this, what would the best approach be?). Does software that solves that particular issue exist? Think of it like wireframing for hobby electronics projects...

Please forgive the absolute layman explanation.

title: Looking for software allowing for Arduino-based project "mocking" / "wireframing"

Answers: 0


body:
I use this code to turn on/off a small 5v dc motor. How can I modify it so that the arduino writes the potentiometer value to the motor when it is in ON state ?

```
int speed = analogRead(pot) / 4;
ButtonState = !digitalRead(Switch);

if (ButtonState != lastButtonState)
{
     if (ButtonState == 1)
     {
         if (motorstate == 1)
         {
             motorstate = 0;
         }
         else
         {
             motorstate = 1;
         }
     }
     lastButtonState = ButtonState;
}

digitalWrite(enable, motorstate);
delay(20);
```

title: Modifying a code

Answers: 1

body:
(this is not an answer, but just a comment, used to use code alignment).

This sketch (which I aligned in your code) can be rewritten to

    int speed = analogRead(pot) / 4;
    ButtonState = !digitalRead(Switch);

    if (ButtonState != lastButtonState)
    {
         if (ButtonState == 1)
         {
             motorstate = (motorstate == 1 ? 0 : 1);
         }

         lastButtonState = ButtonState;
    }

    digitalWrite(enable, motorstate);
    delay(20);

I suggest the best way to proceed is to add print statements and use the serial monitor to check what values you get and see what you expect (which is not fully clear).


body:
i'm new user with Arduino, i want to know if there is a tutorial to control the rotation of a motor like : with 4 buttons, the first to rotate +pi/2 the second to rotate -pi/2 the third to rotate +-pi and the fourth to stop the rotation
thanks a lot !!

title: Control motor DC with buttons

Answers: 0


body:
This is my first time doing this type of thing and I have no background in coding.

It will compile however the code won't upload and I've been working on this for days.

Any help you can provide would be very much appreciated.

Error messages:

    Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Uno"

    Sketch uses 1898 bytes (5%) of program storage space. Maximum is 32256 bytes.
    Global variables use 13 bytes (0%) of dynamic memory, leaving 2035 bytes for local variables. Maximum is 2048 bytes.
    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\CHRIST~1\AppData\Local\Temp\arduino_build_870585/sketch_apr18.ino.hex:i

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

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM4
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x9c
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x9c
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x9c
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x9c
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x9c
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x9c
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x9c
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x9c
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x9c
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x9c

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

Code:

    void setup() {
    //constants
    // set pin numbers:
    int buttonPin1 = 6; //pushbutton pins
    int buttonPin2 = 7;
    int buttonPin3 = 8;
    int buttonPin4 = 9;
    int buttonPin5 = 10;
    int buttonPin6 = 11;

    int const led1 = 0;      //led pins
    int const led2 = 1;
    int const led3 = 2;
    int const led4 = 3;
    int const led5 = 4;
    int const led6 = 5;

      //variables

      //led pins as outputs
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);

      //pushbuttons as inputs
      pinMode(buttonPin1, INPUT);
      pinMode(buttonPin2, INPUT);
      pinMode(buttonPin3, INPUT);
      pinMode(buttonPin4, INPUT);
      pinMode(buttonPin5, INPUT);
      pinMode(buttonPin6, INPUT);

      //activating leds
      digitalWrite(led1, LOW);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      digitalWrite(led5, LOW);
      digitalWrite(led6, LOW);

      //selecting leds to begin game

      int ran1 = random(0, 1);
      int ran2 = random(0, 1);
      int ran3 = random(0, 1);
      int ran4 = random(0, 1);
      int ran5 = random(0, 1);
      int ran6 = random(0, 1);

      //ensuring 6 led=LOW does not occur | approximatley .02 percent chance running random code twice
      if (ran1 == 0) {
        if (ran2 == 0) {
          if (ran3 == 0) {
            if (ran4 == 0) {
              if (ran5 == 0) {
                if (ran6 == 0) {
                  int ran1 = random(0, 1);
                  int ran2 = random(0, 1);
                  int ran3 = random(0, 1);
                  int ran4 = random(0, 1);
                  int ran5 = random(0, 1);
                  int ran6 = random(0, 1);
                }
              }
            }
          }
        }
      }

      if (ran1 == 1) {
        digitalWrite(led1, HIGH);
      }
      else {
        digitalWrite(led1, LOW);
      }
      if (ran2 == 1) {
        digitalWrite(led2, HIGH);
      }
      else {
        digitalWrite(led2, LOW);
      }
      if (ran3 == 1) {
        digitalWrite(led3, HIGH);
      }
      else {
        digitalWrite(led3, LOW);
      }
      if (ran4 == 1) {
        digitalWrite(led4, HIGH);
      }
      else {
        digitalWrite(led4, LOW);
      }
      if (ran5 == 1) {
        digitalWrite(led5, HIGH);
      }
      else {
        digitalWrite(led5, LOW);
      }
      if (ran6 == 1) {
        digitalWrite(led6, HIGH);
      }
      else {
        digitalWrite(led6, LOW);
      }

      int buttonState1 = 0;
      int buttonState2 = 0;
      int buttonState3 = 0;
      int buttonState4 = 0;
      int buttonState5 = 0;
      int buttonState6 = 0;

    }

    void loop() {

    //constants
    // set pin numbers:
    int buttonPin1 = 6; //pushbutton pins
    int buttonPin2 = 7;
    int buttonPin3 = 8;
    int buttonPin4 = 9;
    int buttonPin5 = 10;
    int buttonPin6 = 11;

    int const led1 = 0;      //led pins
    int const led2 = 1;
    int const led3 = 2;
    int const led4 = 3;
    int const led5 = 4;
    int const led6 = 5;

      int buttonState1 = 0;
      int buttonState2 = 0;
      int buttonState3 = 0;
      int buttonState4 = 0;
      int buttonState5 = 0;
      int buttonState6 = 0;

      //read each pushbutton
      buttonState1 = digitalRead(buttonPin1);
      buttonState2 = digitalRead(buttonPin2);
      buttonState3 = digitalRead(buttonPin3);
      buttonState4 = digitalRead(buttonPin4);
      buttonState5 = digitalRead(buttonPin5);
      buttonState6 = digitalRead(buttonPin6);

      // check if the pushbutton is pressed
      //button for leds 3 and 6
      if (buttonState1 == HIGH) {
        if (led3 == HIGH) {
          digitalWrite(led3, LOW);
        }
        else {
          digitalWrite(led3, HIGH);
        }
        if (led5 == HIGH) {
          digitalWrite(led6, LOW);
        }
        else {
          digitalWrite(led6, HIGH);

        }
      }
      //button for leds 1 and 4
      if (buttonState2 == HIGH) {
        if (led1 == HIGH) {
          digitalWrite(led1, LOW);
        }
        else {
          digitalWrite(led1, HIGH);
        }
        if (led4 == HIGH) {
          digitalWrite(led4, LOW);
        }
        else {
          digitalWrite(led4, HIGH);
        }
      }
      //button for leds 2 and 5
      if (buttonState3 == HIGH) {
        if (led2 == HIGH) {
          digitalWrite(led2, LOW);
        }
        else {
          digitalWrite(led2, HIGH);
        }
        if (led5 == HIGH) {
          digitalWrite(led5, LOW);
        }
        else {
          digitalWrite(led5, HIGH);
        }
      }
      //button for leds 2 and 6
      if (buttonState4 == HIGH) {
        if (led2 == HIGH) {
          digitalWrite(led2, LOW);
        }
        else {
          digitalWrite(led2, HIGH);
        }
        if (led6 == HIGH) {
          digitalWrite(led6, LOW);
        }
        else {
          digitalWrite(led6, HIGH);
        }
      }
      //button for leds 1 and 5
      if (buttonState5 == HIGH) {
        if (led1 == HIGH) {
          digitalWrite(led1, LOW);
        }
        else {
          digitalWrite(led1, HIGH);
        }
        if (led5 == HIGH) {
          digitalWrite(led5, LOW);
        }
        else {
          digitalWrite(led5, HIGH);
        }
      }
      //button for leds 3 and 4
      if (buttonState6 == HIGH) {
        if (led3 == HIGH) {
          digitalWrite(led3, LOW);
        }
        else {
          digitalWrite(led3, HIGH);
        }
        if (led4 == HIGH) {
          digitalWrite(led4, LOW);
        }
        else {
          digitalWrite(led4, HIGH);
        }
      }
      //flash all lights once for winning
      if (led1 == LOW) {
        if (led2 == LOW) {
          if (led3 == LOW) {
            if (led4 == LOW) {
              if (led5 == LOW) {
                if (led6 == LOW) {
                  digitalWrite(led1, HIGH);
                  delay(1500);
                  digitalWrite(led1, LOW);
                  digitalWrite(led2, HIGH);
                  delay(1500);
                  digitalWrite(led2, LOW);
                  digitalWrite(led3, HIGH);
                  delay(1500);
                  digitalWrite(led3, LOW);
                  digitalWrite(led4, HIGH);
                  delay(1500);
                  digitalWrite(led4, LOW);
                  digitalWrite(led5, HIGH);
                  delay(1500);
                  digitalWrite(led5, LOW);
                  digitalWrite(led6, HIGH);
                  delay(1500);
                  digitalWrite(led6, LOW);
                }
              }
            }
          }
        }
      }
    }

title: Arduino Light Puzzle Help

Answers: 0


body:
So i have a D1 mini that I want to connect to the wifi.
I found the following code on the internet that is supposed to start a web server, that you can visit and then connect to the chosen wifi through the website. It will then remember the settings and try to connect to that wifi next time before it starts a web server - which is just what I need!
The problem is that when I connect to the wifi the d1 mini thinks it did just than - but when I visit my router and check it is not connected.

I cannot figure out why it thinks it's connected but is not, can anyone help me?

    #include <FS.h>                   //this needs to be first, or it all crashes and burns...
    #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
    #include <DNSServer.h>
    #include <ESP8266WebServer.h>
    #include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

    void setup() {

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

      //WiFiManager

      WiFiManager wifiManager;

      //reset settings - for testing
      wifiManager.resetSettings();

      IPAddress _ip = IPAddress(192, 168, 0, 35);
      IPAddress _gw = IPAddress(192, 168, 0, 1);
      IPAddress _sn = IPAddress(255, 255, 255, 0);

      wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
      if (!wifiManager.autoConnect("WemosAP", "ConfigureMe")) {
        Serial.println("failed to connect, we should reset as see if it connects");
        delay(3000);
        ESP.reset();
        delay(5000);
      }
      //if you get here you have connected to the WiFi
      Serial.println("connected...yeey :)");
      Serial.println("local ip");
      Serial.println(WiFi.localIP());
    }
    void loop() {
    }

btw: the ip 192.168.0.35 is free, and I have checked both the gateway and the subnet mask from my laptop by running ipconfig in cmd.

title: D1 mini / esp8266 WifiManager

Answers: 1

body:
So it seems like the code is just broken. I found an example from the WifiManager library that is called "autoconnect". This just seems to do the exact same thing, just by also working:

    #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

    //needed for library
    #include <DNSServer.h>
    #include <ESP8266WebServer.h>
    #include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

    void configModeCallback (WiFiManager *myWiFiManager) {
      Serial.println("Entered config mode");
      Serial.println(WiFi.softAPIP());
      //if you used auto generated SSID, print it
      Serial.println(myWiFiManager->getConfigPortalSSID());
    }

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);

      //WiFiManager
      //Local intialization. Once its business is done, there is no need to keep it around
      WiFiManager wifiManager;
      //reset settings - for testing
      //wifiManager.resetSettings();

      //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
      wifiManager.setAPCallback(configModeCallback);

      //fetches ssid and pass and tries to connect
      //if it does not connect it starts an access point with the specified name
      //here  "AutoConnectAP"
      //and goes into a blocking loop awaiting configuration
      if(!wifiManager.autoConnect()) {
        Serial.println("failed to connect and hit timeout");
        //reset and try again, or maybe put it to deep sleep
        ESP.reset();
        delay(1000);
      }

      //if you get here you have connected to the WiFi
      Serial.println("connected...yeey :)");

    }

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

    }


body:
I am a newbie to micro controllers and struggling to figure out how to fix this issue. When using an older Arduino micro controller it works fine, but when I use a new board (Arduino Uno Rev 2 Wifi) it gives me this error:

    cannot convert 'bool' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus)'

At this line :

    digitalWrite(pin_enable_line, !digitalRead(pin_enable_line));

Library I am using is: `ReceiveOnlySoftwareSerial`.

title: cannot convert 'bool' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus) on Arduino Uno Rev 2 Wifi not working

Answers: 1

body:
The `digitalRead` method doesn't return a Boolean value. It returns an Integer.

From what I remember inside Arduino.h values of `LOW` and `HIGH` are defined as being simply Integer `0` and `1`.

    #define HIGH 0x1
    #define LOW 0x0

I think that was changed to an Enum called `PinStatus` but Enum can be treated as an Integer.

This means that you have to store results of `digitalRead` inside Integer variable.

    int value = digitalRead(8);

It was designed that way to easily cast values between Integer and Boolean. By (very smart) design choice Integer value of `0` (`LOW`) will be cast to `false` and every other value (for example `1` or `HIGH`) will be cast to `true`.

The operator `!` (Boolean NOT) can be used only with Boolean variables so the compiler needs to perform several "implicit casts". When it's smart enough it will assume you are know what you are doing and it will add the cast by itself.

By reading the error I see that the issue is happening when compiler tries to convert Boolean value into Integer. So this is implicitly evaluated correctly as a Boolean value

    !digitalRead(pin_enable_line)

But when you try to put it inside a place for PinStatus you get the exception

    cannot convert 'bool' to 'PinStatus'

Try adding an "explicit cast" to PinStatus:

    digitalWrite(pin_enable_line, (PinStatus)!digitalRead(pin_enable_line));

It should fix the issue.
But I suggest splitting the code into several lines and adding a temporary variable. It makes debugging much easier. Trust the code optimizer that's built into the compiler. It will understand what you want to do and actual machine code will be the same.

  [1]: https://en.wikipedia.org/wiki/Code_smell


body:
I want to use an Arduino (maybe Nano, maybe MEGA) in my motorcycle (a new KTM with lots of electronics).
I checked my test circuit (with the MEGA) and it uses about 100mA (with 5V connected to the 5V pin).

Edit: the bike has a 12v battery and when it's on the generator pushes this up to about 14.3v.

For my first tests I used a 3 terminals DC/DC Regulator with output 5V for the Arduino power supply. If the ignition is on the Arduino works. As soon as I start the bike the Arduino restarts every couple of seconds.

Currently I used the BP5293 DC/DC Regulator because it has 2% precision. Currently I don't have any capacitors on the input or output terminals of that regulator.

I guess I have the following options:

a) Use the BP5293 and add capacitors on the input and/or output terminals. In the datasheet an output capacitor of about 10-330uF is recommended. For the input it recommends a capacitor but without any value given.

b) Use another regulator to 5V

c) Use a regulator to i.e. 7V and then connect that to the Arduino power input and let the Arduino do the filtering of the input.

What is the proper solution and what are suitable values for the capacitors?

I have 100nF ceramic capacitors and Low ESR electrolyte capacitors with 6.3V, 16V and 35V from 68uF up to 3300uF in stock. Obviously I could just try but I prefer to know how it should be done.

title: How to filter the power supply for an Arduino in a vehicle (car, motorcycle)?

Answers: 1

body:
The solution depend on what causes the reset.

It might be EMI interference on the RESET, in this case a stronger pull-up might help. The standard pull-up for nano is 1kohm which should be enough but if you use a clone the value might be higher.

If the reset comes from power drops then only a higher capacitor on the regulator input would not be enough since you also have other consumers on the 12V line that will suck the energy stored in the input capacitor.

Feed the capacitor and the regulator input through a diode, anode to 12v, cathode to capacitor/regulator. This will stop the energy stored in the capacitor to go back to the 12V line.


body:
I made a smart blind stick for my class project. It uses an ultrasonic sensor to detect obstacles and I was asked this question in VIVA...

Why is it necessary for giving a digital high for 10 μS on the trigger (`Trig`) pin of an ultrasonic sensor ?

Why 10 μS only?

I changed it to 5 μS then to 20 μS and to 50 μS and it still works fine! Why so?

title: Triggering an ultrasonic sensor

Answers: 1

body:
The specification1 says (emphasis is mine):

>  using IO trigger distance, the high signal to ***at least*** 10us.

So, longer than 10 μS is not a problem.

With respect to less than 10 μS, well 5 μS may also work, but it is out-of-spec and therefore not guaranteed to work and so may not always work correctly, or as expected.

From [Source 1][1]:

> [![Timing diagram#1][2]][2]

From [Source 2][3]:

> [![Timing diagram#2][4]][4]

----

As to why must it be 10 μS, well that is *probably* (at a guess) down to the design of the logic upon the silicon and the resultant propagation delay through the logic gates. Most, if not all, logic ICs specify a minimum amount of time required for a signal level, in order to allow the signal to propagate through the transistors that make up the logic, so that they switch correctly. PN junctions require a finite time for the electrons and holes to move, and when there are a number of them in sequential stages, that time is multiplied by the number of stages that the signal needs to propagate through. That is a very simplified way of looking at it.

To confirm this, you would need to speak to either the designers, or take a look at the mask used to fabricate the IC. Test simulations were probably run during the design phase, and they suggested a minimum trigger pulse of 10 μS. The figure could also be arrived at by simply looking at the design and counting the number of stages and multiplying that by the propagation delay per stage.

However, as Valbhav points out, the HC-SR04 is controlled by a STM8 (actually it is a STC11F), and after having looked at the [STM8 programming manual][5], it is more related to instruction cycles. The `Trig` pin is, I assume, an interrupt, and from section **3.2 CPU registers**

> When an interrupt occurs, the CPU registers (CC, X, Y, A, PC) are pushed onto the stack.
>This operation takes 9 CPU cycles and uses 9 bytes in RAM

So, 9 CPU cycles just *begin to* to service the interrupt, and then however many needed to actually do the rest. I can't find any timing diagrams in the Programming Manual which would show the minimum interrupt signal length.  This information, is however in the [Reference Manual][6]

The length of a CPU cycle will obviously depend upon the clock frequency., which according to this schematic, from [An Ultrasonic Shortcut – Getting the HC-SR04 Transducer Up and Running Fast!][7], is 4 MHz:

[![HC-SR04 schematic][8]][8]

So, 10 μS is 40 CPU cycles.

----

1 Sources for downloading HC-SR04 pdf datasheet:

 - [Source 1][1]
 - [Source 2][3]

> ### HC-SR04 Specifications
>
>  - Working Voltage: DC 5V
>  - Working Current: 15mA
>  - Working Frequency: 40Hz
>  - Max Range: 4m
>  - Min Range: 2cm
>  - Measuring Angle: 15 degree
>  - Trigger Input Signal: 10µS TTL pulse
>  - Echo Output Signal Input TTL lever signal and the range in proportion
>  - Dimension 45 * 20 * 15mm

  [1]: https://www.electroschematics.com/wp-content/uploads/2013/07/HCSR04-datasheet-version-1.pdf
  [2]: https://i.stack.imgur.com/vaaML.png "Timing diagram#1"
  [3]: https://www.electroschematics.com/wp-content/uploads/2013/07/HC-SR04-datasheet-version-2.pdf
  [4]: https://i.stack.imgur.com/pmS4c.png "Timing diagram#2"
  [5]: https://www.st.com/content/ccc/resource/technical/document/programming_manual/43/24/13/9a/89/df/45/ed/CD00161709.pdf/files/CD00161709.pdf/jcr:content/translations/en.CD00161709.pdf
  [6]: https://www.st.com/content/ccc/resource/technical/document/reference_manual/9a/1b/85/07/ca/eb/4f/dd/CD00190271.pdf/files/CD00190271.pdf/jcr:content/translations/en.CD00190271.pdf
  [7]: https://www.electroschematics.com/13975/an-ultrasonic-shortcut-getting-the-hc-sr04-transducer-up-and-running-fast/
  [8]: https://i.stack.imgur.com/So1mD.jpg "HC-SR04 schematic"


body:
I am playing with a minimal https server on an ESP01S, using `BearSSL::ESP8266WebServerSecure`.

 - With 2048bit RSA keys it takes ~5 seconds to serve a "hello" request.
 - Using 256bit EC keys it takes ~2 seconds.

I wonder whether it is possible to make key exchange faster without giving up on reasonable security level.

I am struggling with trying to set `ec_all_m15` implementation (see [Key Exchange][1]) to make it faster without any luck - I have actually no idea how to do it properly .

I tried something like

```
...
BearSSL::X509List *cert = new BearSSL::X509List(serverCert.c_str());
BearSSL::PrivateKey *key = new BearSSL::PrivateKey(serverKey.c_str());
server.setECCert(cert, BR_KEYTYPE_EC, key);
server.begin();
br_ssl_server_context sc;
br_ssl_server_init_full_ec(&sc, cert->getX509Certs(), 1, BR_KEYTYPE_EC, key->getEC());
br_ssl_engine_set_ec(&sc.eng, &br_ec_all_m15);
br_ssl_server_reset(&sc);
```
Could someone help pls?

  [1]: https://www.bearssl.org/support.html#key-exchange

title: ESP8266 BearSSL performance

Answers: 0


body:
I am trying to get a MEMS-module (ISM330DLC) to work together with an Arduino Uno but I can't get it to work. I am using the ism330dlc drivers.

ISM330dlc Drivers: https://github.com/STMicroelectronics/STMems_Standard_C_drivers/tree/master/ism330dlc_STdC

ISM330dlc Datasheet: http://www.farnell.com/datasheets/2339632.pdf

ISM330dlc Application Notes: https://www.st.com/content/ccc/resource/technical/document/application_note/group0/68/eb/a3/cd/2c/78/45/41/DM00468454/files/DM00468454.pdf/jcr:content/translations/en.DM00468454.pdf

I have switched out the voltage regulator to a 3.3V on the Arduino following this guide: https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion

I am using the STEVAL-MKI182V2 board for easier wiring.
This is the current wiring:

Arduino Pin<------------->STEVAL Pin

Pin 10 (SS)<------------->CS

Pin 11 (MOSI)<------------->SDA

Pin 12 (MISO)<------------->SDO

Pin 13 (SCK)<------------->SCL

SDx is connected to ground, SCx is connected to VddIO. The board is also connected to ground on the Arduino as well as <s>Vin</s> 3.3V.

Here is the code:

    /* SPI Pin config (There are other pins dedicated to SPI I think) */
    #define SSpin 10
    #define MOSIpin 11
    #define MISOpin 12
    #define SCKpin 13

    /* Variables used to store data */
    static axis3bit16_t data_raw_acceleration;
    static axis3bit16_t data_raw_angular_rate;
    static float acceleration_mg[3];
    static float angular_rate_mdps[3];

    static int32_t platform_write(void *handle, uint8_t Reg, uint8_t *Bufp, uint16_t len) {
      SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE3));
      digitalWrite(SSpin, LOW);
      SPI.transfer(Reg);
      SPI.transfer(Bufp);
      digitalWrite(SSpin, HIGH);
      SPI.endTransaction();
      return 0;
    }
    static int32_t platform_read(void *handle, uint8_t Reg, uint8_t     *Bufp, uint16_t len) {
      Reg |= 0x80; //Set bit 0 (MSB) in order to read
      SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE3));
      digitalWrite(SSpin, LOW);
      SPI.transfer(Reg);
      *Bufp = SPI.transfer(0x00); //Dummy send to get value from module
      digitalWrite(SSpin, HIGH);
      SPI.endTransaction();
      return 0;
    }

    /* Init mems driver interface */
    ism330dlc_ctx_t dev_ctx = {platform_write, platform_read, 0};
    //dev_ctx.write_reg = platform_write;
    //dev_ctx.read_reg = platform_read;
    //dev_ctx.handle = 0; //No handler needed

    void setup() {
      delay(100);
      Serial.begin(9600);
      pinMode(SSpin, OUTPUT);
      digitalWrite(SSpin, HIGH);

      /* Initialize SPI */
      SPI.begin();
      //SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));     //MSBFIRST, SPI_MODE3

      /* Needed for setup */
      static uint8_t whoamI, rst;

      /* Check if device ID is correct */
      whoamI = 0;
      ism330dlc_device_id_get(&dev_ctx, &whoamI);
      while (whoamI != ISM330DLC_ID) {
        Serial.print("Wrong device ID!! \n"); Serial.print("whoamI: ");     Serial.print(whoamI); Serial.print("\n\n"); delay(50);     ism330dlc_device_id_get(&dev_ctx, &whoamI);
      }

      /*Restore default config */
      ism330dlc_reset_set(&dev_ctx, PROPERTY_ENABLE);
      do {
        Serial.print("reset:"); Serial.print(rst); Serial.print("\n\n");
        ism330dlc_reset_get(&dev_ctx, &rst);
      } while (rst);

The problem is that whenever I run this code I get DeviceID 255 no matter what (ism330dlc device id is 106). One thing I noticed is that if I reset the Arduino and quickly insert the USB cable and upload the code (in the time interval of a second) I can get the right device ID, but then I can't restore the default configuration (i.e not read or write again). Any tips what might cause this? I have tried SPI.setClockDivider() as well as different SPI Modes.

UPDATE: Removing ground from GND, SCx and SDx makes me get the correct deviceID but I still get stuck on trying to restore default configurations.

title: Trying to use an Arduino Uno together with an ISM330DLC communicating through SPI

Answers: 0


body:
I'm trying to control my ~230 V fan from the Arduino.

Can anyone say the best possible ways to design a fan regulator that can be controlled by the Arduino using a low cost design.

title: Fan regulator control from Arduino

Answers: 5

body:
Its not exactly what you are looking for but it will help [Arduino-controlled-light-dimmer-The-circuit](https://www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit/).

Here is the sample project in which TRIAC is used with arduino for controlling the flow of current to the light. In your case Light or better we can say load is FAN. This will help you in controlling the FAN Speed. Relay only act as switch and it won't control FAN Speed.

body:
It depends on the motor.

To quote MarkT from [this post][1]:

> The simple advice is you can't.  Standard induction motors in domestic appliances cannot
safely be speed-controlled (some can be a little, but its not easy to find out by how much).
Get a DC fan

To quote dc42, from [this post][2]:

> What sort of motors do the fans have? If they use induction motors,
> then you won't be able to control the speed much using phase angle
> switching - the speed is tied to the supply frequency. If they are
> series-wound motors with brushes, then phase angle switching should
> work.
>
> The results you reported when you tried to use the velleman kit
> suggests to me that the fans may have induction motors.

----

  For more information, read:

 - [How to control AC 220V fan speed with arduino's PWM output..??](https://forum.arduino.cc/index.php?topic=100899.0) *and*;
 - [Changes in Dimming Circuitry!](http://forum.arduino.cc/index.php/topic,91274.0.html) *and*;
 - Learn about zero-crossing. This might help [How stuff works - dimmer switch](http://home.howstuffworks.com/dimmer-switch.htm).
 - [AC Fan Speed Control with Arduino](https://forum.arduino.cc/index.php?topic=75727.0)

  [1]: https://forum.arduino.cc/index.php?topic=100899.msg2790661#msg2790661
  [2]: https://forum.arduino.cc/index.php?topic=75727.msg576925#msg576925

body:
Finally i found it as a product available [here][1]
with the thyristor circuit and *electrical-contactless* ***servo (PWM or ANALOG input) motor*** ( to drive the input) will helps to drive the output from 0 to 220V. **smooth fan regulator can also do this with servo motor and without any external electrical component requirement** . If it is not efficient way with low cost design command or answer your way.  :-).

  [1]: https://robu.in/product/3000w-thyristor-scr-voltage-regulator-temperature-dimmer-speed-light-ac-220v/?gclid=Cj0KCQjw4-XlBRDuARIsAK96p3DJsjbkwTyPaNCDEJwJh2sTK-GFBiYKZua3WaEDRh4wZRD5LO1xS1kaAhuWEALw_wcB

body:
To control AC power for inductive load (motor) a Triac is used. The concept is called [phase cutting][1]. It works for a resistive load (heater) too.

[This module][2] is designed for phase cutting. It contains a zero crossing detector and a Triac. The control is done in MCU. The zero crossing detector is wired to an interrupt pin. The control signal for the Triac is wired to an output pin. In external interrupt function you set a timer interrupt to send a pulse to the Triac after some microseconds. Longer off time results in less power for the motor.

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

At 50 Hz AC, one pulse is 10 milliseconds. To cut a part of AC wave out, activate the Triac gate for 20 microseconds after 0 to 10 milliseconds. Triac turns self off the AC line at next zero crossing.

Robotdyn has [a library][4] for the module.

**EDIT**:

I bought the Robotdyn AC dimmer module to use it in my AC heater regulation project and I tested it with a incandescent light bulb and a fan. ([video on youtube][5])

The library by Robotdyn works, but it is designed to control many dimmers and uses a timer interrupt every 12 microseconds (yes, micros). The library sets the interrupts over MCU registers.

I wrote an arduino fade-in/out sketch using TimerOne library to demonstrate phase cutting with this module.

    #include <TimerOne.h>

    const byte INTERRUPT_PIN = 2;
    const byte TRIAC_PIN = 4;
    const byte TRIAC_PULSE_MICROS = 30;

    const int FADE_MAX = 9800;
    const int FADE_MIN = 2000;

    volatile bool triacOn;
    volatile int period = FADE_MIN; // microseconds cut out from AC pulse

    int fadeAmount = 10;

    void zeroCrossing() {
      triacOn = false; // triac tuns off self at zero crossing
      Timer1.setPeriod(period); // to call triacPulse() after off period
    }

    void triacPulse() {
      if (triacOn) { // stop pulse
        digitalWrite(TRIAC_PIN, LOW);
        Timer1.stop();
      } else { // start pulse
        digitalWrite(TRIAC_PIN, HIGH);
        triacOn = true;
        Timer1.setPeriod(TRIAC_PULSE_MICROS);
      }
    }

    void setup() {
      pinMode(TRIAC_PIN, OUTPUT);
      attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), zeroCrossing, RISING);
      Timer1.initialize();
      Timer1.attachInterrupt(triacPulse);
    }

    void loop() {
      period = period + fadeAmount;
      if (period <= FADE_MIN || period >= FADE_MAX) {
        fadeAmount = -fadeAmount;
      }
      delay(25);
    }

**EDIT 2** version with triac activated by 'pwm' pin

    const byte TRIAC_PIN = 9;
    const byte ZC_EI_PIN = 2;

    unsigned long topMicroseconds = 9700; // 10000 micros is between zero crossings
    int prescaler = 8;
    byte prescalerBits = _BV(CS11); // 8

    void zeroCrossing() {
      TCNT1 = 0; // reset the timer counter
    }

    void setup() {
      Serial.begin(115200);
      Serial.println("START");

      attachInterrupt(digitalPinToInterrupt(ZC_EI_PIN), zeroCrossing, RISING);

      pinMode(TRIAC_PIN, OUTPUT);
      uint32_t topPeriod = ((F_CPU / 1000000)* topMicroseconds) / prescaler ;
      ICR1 = topPeriod;
      OCR1A = topPeriod + 1; // full off
      // WGM mode 14 - Fast PWM w/TOP=ICR1
      TCCR1A = _BV(WGM11) | _BV(COM1A0) | _BV(COM1A1);
      TCCR1B = _BV(WGM13) | _BV(WGM12) | prescalerBits;
    }

    void loop() {
      if (Serial.available()) {
        unsigned long microseconds = Serial.parseInt();
        Serial.find("\n");
        uint32_t period = ((F_CPU / 1000000)* microseconds) / prescaler ;
        OCR1A = period;
      }
    }

on SAMD it is possible to setup this to start the timer on external interrupt over event, without an interrupt function. then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals

**EDIT 3:**

The TriacDimmer library version 1.1.0 for AVR Arduinos available in Library Manager works good with this dimmer. Fun fact: It uses timer1's input capture on pin 8 instead of external interrupt on pin 2 or 3.

  [1]: https://en.wikipedia.org/wiki/Phase-fired_controller
  [2]: https://robotdyn.com/ac-light-dimmer-module-1-channel-3-3v-5v-logic-ac-50-60hz-220v-110v.html
  [3]: https://i.stack.imgur.com/PMHdv.gif
  [4]: https://github.com/RobotDyn/AC-Light-Dimmer-Module-1-Channel-3.3V-5V-logic-AC-50-60hz-220V-110V
  [5]: https://www.youtube.com/watch?v=3gH2Eg5rLE0

body:
There is also the issue of isolation here, to keep the controller side from being connected to the mains for reasons of noise and safety.  The previous posters' comments about doing this with triacs or mosfets, and phase angle control are all true.  It is nearly impossible to control the speed of a single phase induction motor.   Anyway, the most elegant solution is to get a 3 phase fan motor and a variable frequency drive with low-voltage DC control input.  Run the pwm output from the Arduino through an opto-isolator (drive the internal led).  Use the DC reference on the speed control to power the output of the opto-isolator.  Run that through an rc lowpass filter to the speed control voltage input.  I think you could get out of this for around 200$US. Check surpluscenter.com.  there are many motors and drives out there.
-Hugh


body:
I am using Arduino for a RFID project where the LED must switch on after either 12 readings of the tag or 2 minute, the tag reading happen every 10 seconds. I can't seem to figure out a way to have the LED switch on only after the above mentioned conditions.

I have tried doing various if loop much to my failure, below is the code I am currently using:

    #include <RFID.h>
    #include <SPI.h>
    #define SS_PIN 10
    #define RST_PIN 9
    #define LED_PIN A0

    RFID rfid(SS_PIN, RST_PIN);
    int serNum[5];
    String cardno;
    int interval = 15000; // millisec
    long now = 0;
    long lasttime = millis();
    // change Reader ID to your name
    String readerID = "Reader_001";

    void setup() {
      Serial.begin(9600);
      SPI.begin();
      rfid.init();
      pinMode(A0, OUTPUT);
    }

    void loop() {
      now = millis();
      if (now > lasttime + interval) {
        lasttime = now;
        Serial.print(readerID);
        Serial.print(":");
        Serial.println("I am alive");
      }
      if (rfid.isCard()) {
        if (rfid.readCardSerial()) {
          lasttime = now;
          cardno = String(rfid.serNum[0]) +
                   String(rfid.serNum[1]) +
                   String(rfid.serNum[2]) +
                   String(rfid.serNum[3]) +
                   String(rfid.serNum[4]);

          Serial.print(readerID);
          Serial.print(":");
          Serial.println(cardno);
        }
      }
      rfid.halt();
      delay(10000);
    }

The expected outcome is the LED switching on after 2 minutes of contact between the tag and the reader.

title: Is there a way to have the LED switch on after 10 readings or say a minute?

Answers: 1

body:
You want to light the LED, when the same chip was read 12 consecutive times. So I would suggest something like this:

Inside your `void loop()` function you use the `millis()` coding style (refer to the `BlinkWithoutDelay` example, that comes with the Arduino IDE) to scan every 10s for a chip. Then you add a counter variable to count, how often the same chip was scanned. If this counter variable is >=12, you turn on the LED. If a different chip was scanned, you set the counter to 1 (since this chip was now scanned 1 time). This leads to a code something like this:

    #define READ_INTERVAL 10000
    int read_counter = 0;
    unsigned long read_timestamp=0;
    String last_identifier="";
    void loop(){
        if(millis()-read_timestamp>READ_INTERVAL){
            // Read the chip
            if(card_identifier == last_identifier)
                read_counter++;
            else
                read_counter = 1;
            if(read_counter>=12){
                digitalWrite(LED_PIN, HIGH);
            }
        }
    }

Be sure to use `unsigned long` with the `millis()` function, to prevent it from overflowing to a negative value.


body:
New to Arduino and was hoping to figure this out. I am working with a bill acceptor and getting the value once you insert the money. The code works fine with an older Arduino, but I am using Arduino Uno Wifi Rev2 and getting some major issues. I finally go it down to just this error and i cant figure this one out (Help Please!):

    invalid type argument of unary '*' (have 'uint8_t {aka unsigned char}')

On line:

    *digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));

Library that is giving the issue:

ReceiveOnlySoftwareSerial

Answers: 0


body:
In an ISR I want to keep things quick. At the same time I want to limit variable scope. Storage space is not a factor.

I have this line:

    const char trigs[] = "aAbBcCdDeEfFgGhHiIjJ";

When this is global, the resulting compile stats show:

    Sketch uses 3418 bytes (10%) of program storage space.
    Global variables use 431 bytes (21%) of dynamic memory.

When it's inside the function (to limit scope) I get:

    Sketch uses 3470 bytes (10%) of program storage space.
    Global variables use 431 bytes (21%) of dynamic memory.

The extra program space is 52 bytes, which is more than the size of the variables, so there must be extra code in there. That might be something to do with initialization checks... but why? Isn't a `const` already known? If there's a difference in where it's stored, why doesn't global variable space change?

If I prefix this as `static const` I'm back to the first behavior `(3418 / 431)`.

So the immediate answer is just to use `static const`, I suppose. But I'm still curious what's going on. Can someone elucidate?

title: Optimizing for speed using const, static, constexpr etc in a function

Answers: 1

body:
`const char trigs[]` is an auto - it's allocated on the stack at function entry time - and must be initialized at each invocation. The literal used to do that is stored in globals space, which is why the globals allocation doesn't change.

`static const char trigs[]` is allocated in globals space and used in place. The symbols' scope is still local, though, so `trigs[]` isn't visible outside the function.

So why does code space increase by 52 bytes? That seems a lot for copying a string from place to another. So I'll take a guess that the need to copy a string loads a library module that includes it and a few other functions as well.


body:
I hope the LED can fade out a period of time. Also, I hope I can switch off the LED immediately when it is fading, but I only can fade out.

    const int buttonPin = 2;
    const int ledPin = 9;
    const int fadingDelay = 20000;
    int buttonState = 0;
    boolean fadingState = false;
    void setup() {

    // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
    }
    void loop() {
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);

      // check whether the button was pressed
      if (buttonState == HIGH) {
        buttonState = LOW;
        // check the current LED status (on/off)
        if (fadingState == false) {
          // turn on the LED
            for (int i = 255; i >= 0; i -= 5) {
              if (buttonState == HIGH && fadingState == true) {
              analogWrite(ledPin, 0); //immediately off
              i=-1;
              }
            analogWrite(ledPin, i);
                 delay(fadingDelay);

        }
        fadingState = false;  // save the current LED state (on/off)
      }
    }
    }

title: Why can't I switch off the LED immediately using this sketch?

Answers: 1

body:
I can't see anywhere where you are assigning `fadingState as true`.I can't understand this part

    if (fadingState == false) {
          // turn on the LED
            for (int i = 255; i >= 0; i -= 5) {
              if (buttonState == HIGH && fadingState == true) {
              analogWrite(ledPin, 0); //immediately off
              i=-1;
              }
        analogWrite(ledPin, i);
        delay(fadingDelay);
        }

If you are entering in a `if` condition with statement `fadingState as false`. Then in `for loop` you are having a `if condition` in which `statement` is `fadingState == true`.If you are entering in as a False then why are you looking for True Condition.

Then if you manage to sort that add `break;` in that `if` condition so that when LED turns OFF you will exit that `for Loop`.

And Here you are setting the button state as low `buttonState = LOW` if first If condition, then in that nested `if` without reading the `buttonState` you still looking for it as `HIGH`.