body:
I am trying to create an electric meter reading setup for Arduino, and I have been searching for it and almost every posts available is using LDR sensor.

http://www.reuk.co.uk/wordpress/solar/flashing-led-on-electricity-meter/
https://jonarcher.info/2014/03/arduino-based-electricity-monitor/

And since it is using LDR, the system should be kept in a dark area, or that the LDR is taped to the flashing LED so that no other light source will interfere the sensor.

But I wanted to have a different setup, and what I am thinking is:

1. inside the electric meter, tap into the blinking LED
2. From the LED, connect it to an LLC (https://www.sparkfun.com/products/12009)
3. From the LLC, connect it to the Arduino
4. Arduino will sense/detect the pulse of the LED.

Is this a possible setup? Will it not fry the Arduino or the LLC? Will Arduino be able to detect the pulse?

If not, are there any other options? can I use discrete components instead? (I will be the one creating the circuit connection for the LED and Arduino, using resistor, diodes, etc.)

title: Electric meter pulse counting using LLC

Answers: 1

body:
When you aren't using the same power supply as the product you are interfacing with, it's usually a good idea of have some form of electrical isolation, which is what the LDR+LED was doing -- there was no way for a voltage spike to reach the Arduino, nor was there any way that different "ground" potentials could cause problems. (Imagine if the ground reference for the meter was floating at a high voltage with respect to earth-ground, but your Arduino power supply's negative line was referenced to earth ground.)

A good way to get electrical isolation is with an [opto-coupler][1], also called an opto-isolator, which is essentially an LED and a photo-transistor inside the same package. The LED side is completely electrically isolated from the photo-transistor side, but light can pass from the LED to the phototransistor.

You would connect the opto-coupler so that current passes through the LED side when the pulse happens, and with a pull-up or pull-down resistor on the phototransistor side, which gets pulled down or up (depending on the circuit) when the LED is on.

<!-- 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/iCJ4v.png)

<!-- End schematic -->

  [1]: https://en.wikipedia.org/wiki/Opto-isolator


body:
I have a fistful of Pro Mini clones with atmega168 ICs. Oddly they have 16MHz crystals. When I feed it nominal 3.7V (really 4V, but it will spend most time around 3.7) via the RAW pin, I see 2.6V on VCC and RST pins. Of course I’d like a bit more for my MOSFETs - what’s the cause of this? It’s a 1.4V drop, is this common for pro minis?

I can feed 3.3V to VCC with a regulator, but the 16MHz crystal is puzzling. Clocked for 16MHz?

title: Pro Mini atmega168 voltage woes

Answers: 1

body: Bypass the regulator, and connect the battery directly to the VCC pin. However, running at 16Mhz requires at least 3.8 Volts, according to the datasheet. Lower voltages may work, but aren't guarantied.


body:
I have an RGB LED strip which I want to control with my arduino uno, everything works fine, except for the green LEDs.
They cannot be dimmed to less than 50%, because they will simply turn off.

I have this test code in my setup:

    Serial.write("dimming green test started");
    for(int x = 255; x > 0; x--) {
        analogWrite(greenPin,x);
        Serial.write(" - g:");
        Serial.print(x);
        delay(6);
      }
      Serial.println();
      Serial.write("dimming green test done");
      Serial.println();

And the green LEDs are fully turned on in the beginning, and at about 127, the just turn off. All the other colors are perfectly dimmable.
I checked the energy usage, and green does only use a little more than the other colors, so that's not the problem.

**Are green LEDs not dimmable? Or is this just an optical effect?**

(I use a setup very similar to this one with one difference: but only use 5V, because my LED strip only needs 5V) [![setup][1]][1]

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

title: RGB LED strip green LEDs cannot be dimmed to less than 50%

Answers: 1

body:
`analogWrite` only works on pins that support PWM. Those are the pins with the `~` next to it.

On no-PWM pins, analogWrite will set the pin to LOW, for all values lower than 128, and HIGH for all the higher values. Which is what you are experiencing.


body:
**TL;DR:**

 - Arduinos are current hungry so I want to switch my microcontroller
 - code works on Uno, I change upload to ATtiny85, code doesn't compile
 - Wire.h breaks at the TWBR input
 - Should I keep trying to fix this or should I just use ATmega328P without the Arduino?

---

---

---

So I'm working on a project where I send data from an IMU (MPU6050) to a phone using Bluetooth LE (HC08) with a bit of signal filtering by a microcontroller in between. I've been using Pro Minis but the amperage consumption by these boards is ridiculous, so I'm trying to replace these with some ATtiny85's that I have laying around.

The problem is, the Wire.h library won't compile for the ATtiny85. It's also worth noting that the default MPU6050 code mandates use of an interrupt pin, which ATtiny's don't have, so I've modified the code to work without it (I'm not sure if that's part of the problem).

    #include <SoftwareSerial.h>
    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"
    #include "Wire.h"

    //==============================================================================
    // MPU6050 initialization code
    MPU6050 mpu;
    uint16_t packetSize;
    uint16_t fifoCount;
    uint8_t fifoBuffer[64];
    Quaternion q;
    VectorInt16 aa;
    VectorInt16 aaReal;
    VectorInt16 aaWorld;
    VectorFloat gravity;

    //==============================================================================
    // microcontroller initialization code
    int avg_counter = 0;
    int pts_to_avg = 15;
    int * x_array = (int*)malloc(sizeof(int) * 25);
    int * y_array = (int*)malloc(sizeof(int) * 25);
    int * z_array = (int*)malloc(sizeof(int) * 25);

    //==============================================================================
    // HC-08 initialization code
    const byte rxPin = 3;
    const byte txPin = 4;
    SoftwareSerial bleSerial(rxPin, txPin);

    //==============================================================================
    void setup() {
      // MPU6050 setup code ========================================================
      Wire.begin();
      TWBR = 24;
      mpu.initialize();
      mpu.dmpInitialize();
      mpu.setXAccelOffset(-1343);
      mpu.setYAccelOffset(-1155);
      mpu.setZAccelOffset(1033);
      mpu.setXGyroOffset(19);
      mpu.setYGyroOffset(-27);
      mpu.setZGyroOffset(16);
      mpu.setDMPEnabled(true);
      packetSize = mpu.dmpGetFIFOPacketSize();
      fifoCount = mpu.getFIFOCount();

      // microcontroller setup code ================================================

      // HC-08 setup code ==========================================================
      // make sure your HC-08 is set to the same baud as below!
      bleSerial.begin(19200);
      delay(100);
    }

    //==============================================================================
    void loop() {
      while(fifoCount < packetSize){
        fifoCount = mpu.getFIFOCount();
      }

      if(fifoCount == 1024){
        mpu.resetFIFO();
        bleSerial.println(F("FIFO overflow!"));
      }else{
        if(fifoCount % packetSize != 0){
          mpu.resetFIFO();
        }else{
          while(fifoCount >= packetSize){
            mpu.getFIFOBytes(fifoBuffer, packetSize);
            fifoCount -= packetSize;
          }

          mpu.dmpGetQuaternion(&q,fifoBuffer);
          mpu.dmpGetAccel(&aa, fifoBuffer);
          mpu.dmpGetGravity(&gravity, &q);
          mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
          mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);

          // points are averaged to keep the baud low w/o FIFO overflow
          if(avg_counter <= pts_to_avg){
            // add live data to this array and hold onto it to be averaged
            x_array[avg_counter] = aaWorld.x;
            y_array[avg_counter] = aaWorld.y;
            z_array[avg_counter] = aaWorld.z;
            avg_counter++;
          }else{
            // average data from the array
            int x_average=0;
            int y_average=0;
            int z_average=0;

            // sums the data in #_average
            for(int i = 0; i < avg_counter; i++){
              x_average += x_array[i];
              y_average += y_array[i];
              z_average += z_array[i];
            }

            // divides by avg_counter (which should == pts_to_avg)
            x_average /= avg_counter;
            y_average /= avg_counter;
            z_average /= avg_counter;

            // resets counter so the array data can be overwritten with future data
            avg_counter = 0;

            // prints data to serial port (if BT is connected, sends via BT)
            bleSerial.print(x_average);
            bleSerial.print(",");
            bleSerial.print(y_average);
            bleSerial.print(",");
            bleSerial.println(z_average);
          }
        }
      }
    }

When using Arduino as ISP, selecting "Board: ATtiny25/45/85", "Processor: ATtiny85", & "Clock: Internal 1MHz", the following error showed up:

    exit status 1
    'TWBR' was not declared in this scope

this error did *not* occur when compiling for the Uno. If you comment out TWBR, then you get an enormous error message (I'll only paste a bit):

    In file included from c:\users\auphynne\appdata\local\arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2\avr\include\avr\io.h:99:0,

                     from C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:25:

    C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:426:15: error: 'TWINT' undeclared (first use in this function)

        TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;

                   ^

    C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:426:28: error: 'TWSTA' undeclared (first use in this function)

        TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;

                                ^

    C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:426:40: error: 'TWEN' undeclared (first use in this function)

        TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;

                                            ^

    exit status 1
    Error compiling for board ATtiny25/45/85.

To try to remedy this, I went into

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\utility\twi.c

and hardcoded this line from

    // initialize twi prescaler and bit rate
    cbi(TWSR, TWPS0);
    cbi(TWSR, TWPS1);
    TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;

to

    // initialize twi prescaler and bit rate
    cbi(TWSR, TWPS0);
    cbi(TWSR, TWPS1);
    TWBR = 24;

and I still got the same gruesome error message.

Pins are what you'd expect, 5v power to both modules and grounded, plus:

 - Uno D4 -> HC08 RXD
 - Uno D3 -> HC08 TXD
 - Uno SCL -> MPU6050 SCL
 - Uno SDA -> MPU6050 SDA

(again note that the interrupt pin is not used, and this worked quite well when building on the Uno! I got data on my phone's BT serial terminal app so that doesn't seem to be the problem)

**Any ideas on how I can get Wire.h to compile on my ATtiny85?**

**Or... should I just abort and go with the ATmega328P** (without the accompanying Uno) since it comes in the Quad Flat SMD package? (footprint matters for the long term)

title: Wire.h library works on Uno but won't compile for ATtiny85

Answers: 2

body:
You get this error, because the ATTiny85 doesn't have full I2C hardware. It only as an USI (Universal Serial Interface). This can be utilized to do the rest of the I2C protocol via software. There are some libraries out there to do that, most of them are somewhat named `TinyWire`. There were dedicated libraries for master and slave operation named `TinyWireM` and `TinyWireS`. And I composed one library with both functionalities (and some more) in [TinyWire][1]. The last one - I think - is not usable for you, because the`SoftwareSerial` library needs the PinChangeInterrupt to work, but TinyWire uses it for detecting stop conditions on the I2C bus.

So for your case you can use the [TinyWireM][2] library. Note that the master operations need exact timing. Using to much interrupts in this time can cause problems in transmission. Test it and disable interrupts, if it is needed.

  [1]: https://github.com/lucullusTheOnly/TinyWire
  [2]: https://github.com/adafruit/TinyWireM

body:
If you want Wire.h library to work on attiny85 use:

https://github.com/SpenceKonde/ATTinyCore

I did and it compiles.


body:
[![Fritzing circuit][1]][1]

Hi there,

I have an Adafruit Huzzah Feather project laid out as you can see in the diagram above.

Currently I am having trouble getting it to reliably reset and start the sketch. More often than not I receive garbage in the serial monitor and the sketch doesn't begin.

The baud rate is set to 115200 and when the sketch occasionally I begin to see the expected behaviour and serial messages.

I have done some tests to see if the serial connection is causing a problem. I uploaded a sketch with and without `Serial.begin(115200);`. Without this the sketch behaves as expected (I'm flashing an LED sequence to know when the loop has begun). When I add serial communication back I get about 50/50 success rate when resetting.

Here are some thoughts about what could be the problem:

1. A problem with circuitry. Not sure if something is causing the board to occasionally activate the bootloader? After reading some of the FAQs I'm wondering if I'm accidentally pulling a GPIO pin low. However time has been spent making sure the problematic GPIO pins (0, 2 15) aren't being used.
2. Possible problem with the board itself - but this is unlikely because there are two of them with exactly the same problem.
3. Problem with the code. (https://pastebin.com/VAEreu6b)

Any thoughts and suggestions are very welcome at this stage.

Best,
Gareth

EDIT: Forgot to add code. Now here: https://pastebin.com/VAEreu6b

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

title: Adafruit Huzzah Feather not resetting and serial monitor garbage

Answers: 0


body:
I am trying to send temperature read from DS18B20 to a web server. I know two things: to read a temperature, and to send something to web server. What I don't know is how to convert float that temperature reading function is giving to me to string that I need to send to the server.

I am reading temperature with OneWire and DallasTemperature libraries (just a standard sketch ending with:

    sensors.requestTemperatures();
    Serial.println(sensors.getTempCByIndex(0));//sensors.getTempCBy... returns float, from my understanding

I am sending data via ethernet shield, and important part is:

     client.println("GET /led-ekran-vremenska-prognoza/?temp1=" + String(sensors.getTempCByIndex(0)) + "&temp2=" + String(dht.readTemperature()) + "&humidity="+String(dht.readHumidity())+"&secret=111 HTTP/1.1");

I know that the problem is that String(sensors.getTempCByIndex(0)) is not converting to right value. Arduino just stops working there, if that makes sense. At least serial communication stops working, since I don't see any more output...

Basically, TL:DR, I think that the question is how to convert float to string in Arduino? I have read a million topics on this but still cant figure it out, especially sicne it works for temp2 and humidity in example above.

title: DS18B20 sending variable via Enthernet shield

Answers: 1

body:
> Having re-read the question just before posting this answer, I find it odd that the DHT temp and humidity (also floats) work for you - how odd

Use `dtostrf`

    char tStr[9] = { 0 }; // buffer to store the string - length 9, because at most you need 8 chars "-23.5678" , plus null terminator
    dtostrf(sensors.getTempCByIndex(0), 7, 3, tStr)

Note: `dtostrf` returns char pointer to `tStr`

The 7, 3 is ... 7 = total length of string, 3 = number of decimal digits - So depending on your resolution, you can change those values

    Resolution     Arguments to dtostrf
     9             5, 1                  -nn.n
    10             6, 2                  -nn.nn
    11             7, 3                  -nn.nnn
    12             8, 4                  -nn.nnnn

Of course, you can use any arguments for any resolution, the table just shows what you would need if you wanted to show the exact data coming in

For example, I use resolution 12, but I'm not really interested in displaying more than tenths of a degree - so I use `5,1` for the format


body:
I am working on a school project, basically I have to create a lock system that opens a fictive gate when the correct code is entered. We have been asked to simulate our system before actually building it. So, I made the following circuit in Proteus(Labcenter Electronics' simulation software):

[![][1]][1]

Here's what my system should do: A variable contains the correct code and the user must type a code on the keypad, and if it is correct, a green LED turns on and the LCD screen displays "Acces Granted!" if the code is wrong, the screen will display "Access refused!". It's a basic system, but I'm trying to make it as simple/short as possible(I have to explain it in an oral presentation, so the simpler the better) and for some reason, I can't get my code to work. Ideally, I'd like to have the LCD display a * for each character typed, liked on a real security system, but I haven't managed to do that either. I've been working on it for hours, trying different variants and etc.. but nothing seems to work the way I want to. BTW, my circuit works perfectly fine and the initialisation part of my code is therefore correct as well. Can anyone help me figure out what's wrong with my code and how I can make it better?

Here's my code so far:

<!-- language: lang-c++ -->

    #include <LiquidCrystal.h>
    #include <Keypad.h>

    //define LED pins
    #define redLED 11
    #define greenLED 10

    String codeSerrure = "87362";   //correct code that opens the imaginative gate
    String enteredCode = "";
    int keyPressed;

    const byte rows = 4;
    const byte cols = 3;

    char touches_digicode [rows] [cols] = {

      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };

    byte rowPins [rows] = {25, 26, 27, 28};
    byte colPins [cols] = {24, 23, 22};

    Keypad leDigicode = Keypad( makeKeymap(touches_digicode), rowPins, colPins, rows, cols);
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    void setup(){
      lcd.begin(16, 2);
      pinMode(redLED, OUTPUT);
      pinMode(greenLED, OUTPUT);
      digitalWrite(redLED, HIGH);
    }

    void loop(){
      lcd.setCursor(0,0);
      lcd.print(" Entrez le code");

      keyPressed = leDigicode.getKey();
      enteredCode += String(keyPressed);
      if(enteredCode.length() >= 5){
        if(enteredCode == codeSerrure){
          digitalWrite(greenLED, HIGH);
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("  Acces autorise!");
          delay(4000);
          digitalWrite(greenLED, LOW);
          digitalWrite(redLED, HIGH);
          enteredCode = "";
        }
        else{
          digitalWrite(redLED, HIGH);
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("  Acces refuse!");
          delay(4000);
          enteredCode = "";
        }
      }
      if(keyPressed == "#"){
        lcd.clear();
        enteredCode = "";
      }
    }

The problem is that when I run this code in the simulation software, the LCD displays "Acces refuse!" and the red LED is on. No matter what keys I press (on the keypad) nothing happens. So the problem is that my code jumps straight to the else statement, inferring that the password typed is wrong (although no password was actually typed). I think the error is in here:

<!-- language: lang-c++ -->

    keyPressed = leDigicode.getKey();
      enteredCode += String(keyPressed);
      if(enteredCode.length() >= 5){
        if(enteredCode == codeSerrure){

Btw, forgive the french words, I am french. Also, I forgot to say, the # key should, clear the entered code. Any explanations, code samples or links would help.

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

title: Keypad password check issue

Answers: 2

body:
The `getKey()` Funktion returns the define `NO_KEY` if no key was pressed, which is set in Keys.h as the NULL char (char with the value 0). In every loop cycle you are adding one character with value 0 to your string. But all functions, that handle strings, will stop, when they find a character with value 0 (it is the delimiter of C strings). Also a string with many NULL chars in it will not be matched to a string only consisting oft digits.

So you should check the return value of getKey for the NO_KEY define:

    if(keyPressed != NO_KEY){
      enteredCode += String(keyPressed);
    }

This avoids adding NULL chars to your string.

body:
After reading all of your comments, I made some changes to my code and I was able to figure out a few other things that weren't working before. I think, because of the way I had coded my password checking function it made all the rest more complicated. I have also implemented the erase key feature, so a press of the * or # keys, erase the entered code. I still need to implement the feature that displays a * on the lcd each time the user presses a key, but I a not sure of what way to do this. Anyways, here's my working code if you're interested:

    #include <LiquidCrystal.h>
    #include <Keypad.h>

    //define LED pins
    #define redLED 11
    #define greenLED 10

    String codeSerrure = "87362";
    String enteredCode = "";
    char keyPressed;

    const byte rows = 4;
    const byte cols = 3;

    char touches_digicode [rows] [cols] = {

      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };

    byte rowPins [rows] = {25, 26, 27, 28};
    byte colPins [cols] = {24, 23, 22};

    Keypad leDigicode = Keypad( makeKeymap(touches_digicode), rowPins, colPins, rows, cols);
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    void setup(){
      lcd.begin(16, 2);
      pinMode(redLED, OUTPUT);
      pinMode(greenLED, OUTPUT);
      digitalWrite(redLED, HIGH);
    }

    void loop(){
      lcd.setCursor(0,0);
      lcd.print(" Entrez le code");

      keyPressed = leDigicode.getKey();
      if(keyPressed != NO_KEY){
        if(keyPressed == 0x23 || keyPressed == 0x2A){
          lcd.clear();
          enteredCode = "";
        }
        else{
          enteredCode += String(keyPressed);
        }
      }

      if(enteredCode == codeSerrure){
          digitalWrite(greenLED, HIGH);
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("  Acces autorise!");
          delay(4000);
          digitalWrite(greenLED, LOW);
          digitalWrite(redLED, HIGH);
          enteredCode = "";
          lcd.clear();
      }
      else if(enteredCode.length() >= 5){
          digitalWrite(redLED, HIGH);
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("  Acces refuse!");
          delay(4000);
          enteredCode = "";
          lcd.clear();
      }
    }

Thank you to everyone for the help (I'm a noobie)! I'm aware that my code is problably not the best way to do what I'm trying to do, so any suggestions and upgrades to the code you could give me are very welcome. Thanks again!

**The final version of my code with all the features working can be found in [this thread][1], for those interested.**

  [1]: https://stackoverflow.com/questions/49016981/arduino-mega2560-keypad-password-check/49048637#49048637


body:
Forgive me, I'm sure this is a total noob question, but I have never seen it actually addressed in any example or demo.

When using something like a MinIMU-9 board (https://www.pololu.com/product/2738/), does it matter what position you mount the board on your project?  I mean, does it have to be positioned so the proper axes line up with the axes of your vehicle, or is there some calibration to set that alignment?

For a ground vehicle where I will concerned primarily with only one axis, are all axes interchangeable?

title: Does the position in which you mount an IMU matter?

Answers: 1

body:
If the axes of measurement don't line up with the axes of motion, then comparing the IMU outputs to vehicle-relative (VR) coordinates will require some vector arithmetic to convert one to the other. It can be done, but requires some engineering time to code it and processor time to run.

It wasn't clear to me at a quick read whether your chosen IMU can do the coordinate translation itself, or your MCU has to do it. In either case, the computation will always reduce the accuracy of the original data, maybe a lot, maybe inconsequential, but expect some degradation.

Bottom line is: if you can line them up, things get simpler.


body:
I am trying to send a 16 bit command to a Half bridge (data sheet here http://www.onsemi.com/pub/Collateral/NCV7719-D.PDF) to open one of the transistors to turn on an LED. at the bottom of the data sheet (page 13) it says which bit needs to be a 1 or a 0 in order to activate the half bridge. This is the code I wrote but it isn't work (I'm assuming I'm not sending the 16 bits properly). Can someone figure out why this isn't working?

    #include <SPI.h>

    void setup() {
      // put your setup code here, to run once:
      pinMode(10,OUTPUT);
      pinMode(8,OUTPUT);
      digitalWrite(8,HIGH);
      SPI.begin();

    }

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

      //pulling pin low to decide to write to device
      digitalWrite(10,LOW);

      //function to send information
      //truning on half bridge 4
      SPI.transfer(0000010000000000);
    delay(500);
      //finish transfering data
      digitalWrite(10,HIGH);

    }

title: sending 16 bit command via SPI to a NCV7719 (half bridge)

Answers: 1

body:
SPI writes in 8-bit bytes. So the writes need to look like this:

<!-- language: lang-c++ -->

      SPI.transfer(0b00000100);  // first byte
      SPI.transfer(0b00000000);  // second byte

Possibly in the other order depending on which byte the device expects first.


body:
I want to cause the external interrupt on digital pin 2 (`PD2` on ATmega328). I have chosen *any logic change* mode. Here is my code:

    void setup()
    {
        DDRD &= ~( 1 << DDD2 );//PD2 on input mode
        EICRA |= ( 1 << ISC00 );//any logic change
        PORTD |= ( 1 << PORTD2 );//pull-up enable
        EIMSK |= ( 1 << INT0 );//turns on INT0

        DDRD |= ( 1 << DDD5 );//PD5 on output mode
        PORTD |= ( 1 << PORTD5 );//turn on PD5

        SREG |= ( 1 << 7 );//global interrupts enabled
    }

    void loop()
    {

    }

    ISR( INT0_vect )
    {
        if( ( PIND & ( 1 << PIND5 ) ) > 0 )//if turned on
        {
             PORTD &= ~( 1 << PORTD5 );//turn off led
        }
        //and vice-versa
        else
        {
             PORTD |= ( 1 << PORTD5 );
        }
    }

Here is how I connect things.

*NOTE:* I did not find an ordinary button which just connects two contacts ( which I actually use ). Here if I understand correctly the button in the picture connects left pair and right pair of contacts so everything is connected when pushed and disconnects them from each other when released.

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

The problem is when I push the button no interrupt occurs. What am I doing wrong?

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

title: Trigger external interrupt on Arduino Uno R3 with an LED and a button

Answers: 1

body:
Pin 2 is pulled up by internal R then pulled up when button is pressed?
Connect button to GND.


body:
I'm building a basic program that when a button is pressed, a buzzer comes on.

I would like however to make it so that the buzzer stops after a short period of time (e.g. 5-7 seconds).

Here is the code I have so far which is pretty basic I know forgive me but I have no clue on how to go forward.

    // Setting The Pin Numbers
    const int touchsensor = 2;     // the number of the touchsensor pin
    const int buzzer =  4;         // the number of the LED pin

    // variables:
    int touchsensorState = 0;      // variable for reading the touchsensor status

    void setup() {
      // initialize the buzzer as an output:
      pinMode(buzzer, OUTPUT);
      // initialize the touchsensor as an input:
      pinMode(touchsensor, INPUT);
    }

    void loop() {
      // read state of the pushbutton value:
      touchsensorState = digitalRead(touchsensor);

      // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
      if (touchsensorState == HIGH) {
        // buzzer will emit sound:
        digitalWrite(buzzer, HIGH);
      } else {
        // buzzer will not sound:
        digitalWrite(buzzer, LOW);
      }
    }

title: Stop Arduino Timer after some seconds

Answers: 2

body:
You can time this with the `millis()` function. Refer to the BlinkWithoutDelay example from the Arduino IDE.

Then you set a timestamp, when the button is pressed:

<!-- language: c -->

    if(touchsensorState == HIGH) timestamp = millis();

And then you are checking this timestamp against the current time:

<!-- language: c -->

    if(millis() - timestamp > duration){
      digitalWrite(buzzer, HIGH);
    } else {
      digitalWrite(buzzer, LOW);
    }

`duration` is the timespan during which the buzzer should stay on after the button was released. If you want to turn it of, regardless of the button state, you can add a boolean flag to your if-statement, to set the timestamp only, when the button was pressed first:

<!-- language: c -->

    if(!button_pressed && touchsensorState == HIGH){
      timestamp = millis();
      button_pressed = true;
    }

In this case you have to reset the `button_pressed` variable to `false`, when you are turning of the buzzer in the `millis()`-else-statement

body:
You set a `timestamp = millis()` when the button is pushed and then you disable the buzzer only when `millis() - timestamp > timeout`

    if (touchsensorState == HIGH) {
        // buzzer will emit sound:
        digitalWrite(buzzer, HIGH);
        timestamp = millis();
    }
    if(millis() - timestamp > timeout) {
        // buzzer will not sound:
        digitalWrite(buzzer, LOW);
    }


body:
I'm trying to communicate with an MPU6500 sensor via SPI as I need the fastest possible update rate. I have trouble finding an easy to understand sample code, or perhaps a lightweight library how to configure and initialize the sensor and read gyro / accelerometer data via SPI.

So far I started adapting the code and info found at https://playground.arduino.cc/Main/MPU-6050 thought it would be fairly easy to use SPI instead of I2C "Wire", and adapt the configuration and registers based on the datasheet, but I realized there's too many possible pitfalls.

Any recommendations?

title: MPU6500 via SPI

Answers: 1

body:
For anyone who has not yet figured this out, its very simple.

Basically, for SPI communication with the sensor MPU 6500, its a bit different from what I2C has to offer.

In I2C, basically you will find the data packet is as follows:

(7 bit Slave Address + Read/Write Bit), but in SPI it is as follows:

(Read/Write Bit + 7 Bit Register Address), notice we dont even need the slave address in SPI as the Chip Select is connected from processor(Master) to Sensor(Slave).

So for SPI, lets say you want to write a value 64 to register 0x6B, then:
Transmission_data[2];
Transmission_data[0] = 0x6B;
Transmission_data[1] = 64;

Lets say you want to read a value from register 0x43, which is GYRO_X_High Byte value, then,
Transmission_data[1];
Transmission_data[0] = 0x43 | 0x80; // you need to or it with 0x80(decimal = 128)

Thanks...Hope this helps someone in need of help for SPI as I struggled too in finding this information.


body:
I have searched several questions and through google but could not find a solution. I am simply trying to send a float number from python3 with struct to arduino or if there is any other ways other than processing a char array at the arduino side because it is very slow in my opinion..

My arduino code:

    void setup() {
      // initialize the serial communication:
      Serial.begin(9600);
    }

    void loop() {

      unsigned long t = millis();
      float x = analogRead(A3);
      float y = analogRead(A2);
      float c = Serial.read();
      Serial.println(c);
      //Serial.print(t/1000.0);
      //Serial.print(" , ");
      //Serial.print(x);
      //Serial.print(" , ");
      //Serial.println(y);

      // wait a bit for the analog-to-digital converter to stabilize after the last
      // reading:
      //delayMicroseconds(200);
      //delay(2);
      delay(250);
    }

My python3 code :

    import serial

    import struct

    arduino = serial.Serial('/dev/ttyACM0', 9600)
    data = arduino.write(struct.pack('f', 111.32))
    while True:
    #    arduino.write(b"123")
        data = arduino.write(struct.pack('f', 111.32))

Getting the serial output as :

    163.00
    222.00
    66.00
    215.00
    163.00
    222.00
    66.00
    215.00
    163.00
    222.00
    66.00
    215.00
    163.00

How can i solve my problem ?

EDIT : I changed the arduino code according to the answer the new arduino code is

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

    void loop(){
      while(Serial.available() >= 3){

        f = Serial.read() << 24;
        f = ((unsigned long) f) | (Serial.read() << 16);
        f = ((unsigned long) f) | (Serial.read() << 8);
        f = ((unsigned long) f) | Serial.read();
        Serial.println(f);
      }
      Serial.println(f);
    }

However, the output is now as such:

    ovf
    ovf
    ovf
    ovf
    ovf
    ovf
    ovf
    4294941184.00
    4294941184.00
    4294941184.00
    4294941184.00
    4294941184.00
    4294941184.00
    4294941184.00

title: How to send float numbers from python3 with struct to arduino

Answers: 2

body:
There is no way around dealing with serial bytewise, since the communication over serial relies on bytes as a unit. You can write the received bytes directly to the float variable. That is faster, than save them to a char array first:

    float f = Serial.read() << 24;
    f = ((unsigned long) f) | (Serial.read() << 16);
    f = ((unsigned long) f) | (Serial.read() << 8);
    f = ((unsigned long) f) | Serial.read();

With this the bytes of the float value have to be send with the order from most significant to least significant. I don't know, how the data is formatted, if you send a struct over python. The casting to `unsigned long` is important here to do the bitwise OR (`unsigned long` and `float` have both 4 bytes). (I tried it and it works for me)

Also be aware, that you shouldn't read from Serial, when there is no received byte in the buffer. You can check this with `Serial.available()`. If there is no new byte in the buffer the `Serial.read()` function returns an integer with value `-1`

EDIT:
The code above works, if you transmit the data directly as byte. In your comment you wrote, that you want to write `arduino.write(b"111.32")` in python. Here you are transmitting an ASCII string representation of the float number `111.32`. This is not as fast as transmitting byte data (since you may need way more bytes for one float than 4). In this case you can use either `Serial.parseFloat()` to get the float from the serial buffer (but ensure, that all bytes for this number have been received with `Serial.available()`) or you can save the bytes to a string and using `String.toFloat()` to get the float out of it.

Since you wanted to do it the fast way, you should transmit the numbers as byte data. To do this in python, have a look at the answer of [this question][1]. It explains the python code for it (be sure, that you get the ordering of the bytes the same in python and Arduino).

  [1]: https://arduino.stackexchange.com/questions/3753/how-to-send-numbers-to-arduino-uno-via-python-3-and-the-module-serial

body:
I found a better way dealing with the conversion from char to float (note that you yourself have to add the `setup()` function for initiating Serial):

    float f;
    byte *fdata = (byte *) &f;
    int num = 0;

    void loop()
    {
      if(Serial.available()){
        char c = Serial.read();
        if(c == 'B'){
          fdata[3] = c;
          num = 1;
        } else if(num == 1){
          fdata[2] = c;
          num++;
        } else if(num == 2){
          fdata[1] = c;
          num++;
        } else if(num == 3){
          fdata[0] = c;
          num = 0;
          Serial.write(fdata, 4);
          Serial.println(f);
        }
      }
    }

First we are defining our float variable `f` and then a pointer of type `byte` named `fdata`. We are setting this pointer to point to our float variable. Now you can treat this pointer as an array. Since the type of the pointer is `byte`, we can access the first byte of `f` with typing `fdata[0]`. The other bytes can be accessed through `fdata[1]`, `fdata[2]` and `fdata[3]`.

In the loop example we are checking, if there is any byte in the buffer and read it. If it is the value of the character 'B' (which I used as a trigger, that your float starts, since the float number `111.32` starts with this value) we copy it to the last (most significant) byte of the array (aka float variable `f`). One after another we are doing the same with the other bytes.

When we received the last of the 4 bytes, we write the value back to Serial, once as pure byte data and once as ASCII encoded string.

In Python you can use the code, you already used:

<!-- language: lang-py -->

    arduino.write(struct.pack('>f',111.32))

You can read the output of the above sketch back with

<!-- language: lang-py -->

    arduino.readline()

PS: From my tries I guess the previous problem with getting `ovf` was, that the byte order was reversed (which simply would have been solved by using `<f` for the struct in python). But I personally like this way better, because it uses less casting.


body:
1. One port of my motor shield (i.e M1 & M2) is not driving the stepper motor as it should.stepper motor jitters at its position.
2. While the other port (M3 & M4) works fine but it makes stepper motor too hot and also it's respective motor driver L293D IC.
3. While all the ports of motor shield works fine with DC Motor.

I am making CNC plotter using this setup.
I am powering motor shield with 12 V adapter and Arduino is connected with USB cable.

This is the code I am using :

    #include <Servo.h>
    #include <AFMotor.h>

    #define LINE_BUFFER_LENGTH 512

    char STEP = MICROSTEP ;

    // Servo position for Up and Down
    const int penZUp = 115;
    const int penZDown = 83;

    // Servo on PWM pin 10
    const int penServoPin =10 ;

    // Should be right for DVD steppers, but is not too important here
    const int stepsPerRevolution = 48;

    // create servo object to control a servo
    Servo penServo;

    // Initialize steppers for X- and Y-axis using this Arduino pins for the L293D H-bridge
    AF_Stepper myStepperY(stepsPerRevolution,1);
    AF_Stepper myStepperX(stepsPerRevolution,2);

    /* Structures, global variables    */
    struct point {
      float x;
      float y;
      float z;
    };

    // Current position of plothead
    struct point actuatorPos;

    //  Drawing settings, should be OK
    float StepInc = 1;
    int StepDelay = 0;
    int LineDelay =0;
    int penDelay = 50;

    // Motor steps to go 1 millimeter.
    // Use test sketch to go 100 steps. Measure the length of line.
    // Calculate steps per mm. Enter here.
    float StepsPerMillimeterX = 100.0;
    float StepsPerMillimeterY = 100.0;

    // Drawing robot limits, in mm
    // OK to start with. Could go up to 50 mm if calibrated well.
    float Xmin = 0;
    float Xmax = 40;
    float Ymin = 0;
    float Ymax = 40;
    float Zmin = 0;
    float Zmax = 1;

    float Xpos = Xmin;
    float Ypos = Ymin;
    float Zpos = Zmax;

    // Set to true to get debug output.
    boolean verbose = false;

    //  Needs to interpret
    //  G1 for moving
    //  G4 P300 (wait 150ms)
    //  M300 S30 (pen down)
    //  M300 S50 (pen up)
    //  Discard anything with a (
    //  Discard any other command!

    /**********************
     * void setup() - Initialisations
     ***********************/
    void setup() {
      //  Setup

      Serial.begin( 9600 );

      penServo.attach(penServoPin);
      penServo.write(penZUp);
      delay(100);

      // Decrease if necessary
      myStepperX.setSpeed(600);

      myStepperY.setSpeed(600);

      //  Set & move to initial default position
      // TBD

      //  Notifications!!!
      Serial.println("Mini CNC Plotter alive and kicking!");
      Serial.print("X range is from ");
      Serial.print(Xmin);
      Serial.print(" to ");
      Serial.print(Xmax);
      Serial.println(" mm.");
      Serial.print("Y range is from ");
      Serial.print(Ymin);
      Serial.print(" to ");
      Serial.print(Ymax);
      Serial.println(" mm.");
    }

    /**********************
     * void loop() - Main loop
     ***********************/
    void loop()
    {

      delay(100);
      char line[ LINE_BUFFER_LENGTH ];
      char c;
      int lineIndex;
      bool lineIsComment, lineSemiColon;

      lineIndex = 0;
      lineSemiColon = false;
      lineIsComment = false;

      while (1) {

        // Serial reception - Mostly from Grbl, added semicolon support
        while ( Serial.available()>0 ) {
          c = Serial.read();
          if (( c == '\n') || (c == '\r') ) {             // End of line reached
            if ( lineIndex > 0 ) {                        // Line is complete. Then execute!
              line[ lineIndex ] = '\0';                   // Terminate string
              if (verbose) {
                Serial.print( "Received : ");
                Serial.println( line );
              }
              processIncomingLine( line, lineIndex );
              lineIndex = 0;
            }
            else {
              // Empty or comment line. Skip block.
            }
            lineIsComment = false;
            lineSemiColon = false;
            Serial.println("ok");
          }
          else {
            if ( (lineIsComment) || (lineSemiColon) ) {   // Throw away all comment characters
              if ( c == ')' )  lineIsComment = false;     // End of comment. Resume line.
            }
            else {
              if ( c <= ' ' ) {                           // Throw away whitepace and control characters
              }
              else if ( c == '/' ) {                    // Block delete not supported. Ignore character.
              }
              else if ( c == '(' ) {                    // Enable comments flag and ignore all characters until ')' or EOL.
                lineIsComment = true;
              }
              else if ( c == ';' ) {
                lineSemiColon = true;
              }
              else if ( lineIndex >= LINE_BUFFER_LENGTH-1 ) {
                Serial.println( "ERROR - lineBuffer overflow" );
                lineIsComment = false;
                lineSemiColon = false;
              }
              else if ( c >= 'a' && c <= 'z' ) {        // Upcase lowercase
                line[ lineIndex++ ] = c-'a'+'A';
              }
              else {
                line[ lineIndex++ ] = c;
              }
            }
          }
        }
      }
    }

    void processIncomingLine( char* line, int charNB ) {
      int currentIndex = 0;
      char buffer[ 64 ];                                 // Hope that 64 is enough for 1 parameter
      struct point newPos;

      newPos.x = 0.0;
      newPos.y = 0.0;

      //  Needs to interpret
      //  G1 for moving
      //  G4 P300 (wait 150ms)
      //  G1 X60 Y30
      //  G1 X30 Y50
      //  M300 S30 (pen down)
      //  M300 S50 (pen up)
      //  Discard anything with a (
      //  Discard any other command!

      while( currentIndex < charNB ) {
        switch ( line[ currentIndex++ ] ) {              // Select command, if any
        case 'U':
          penUp();
          break;
        case 'D':
          penDown();
          break;
        case 'G':
          buffer[0] = line[ currentIndex++ ];          // /!\ Dirty - Only works with 2 digit commands
          //      buffer[1] = line[ currentIndex++ ];
          //      buffer[2] = '\0';
          buffer[1] = '\0';

          switch ( atoi( buffer ) ){                   // Select G command
          case 0:                                   // G00 & G01 - Movement or fast movement. Same here
          case 1:
            // /!\ Dirty - Suppose that X is before Y
            char* indexX = strchr( line+currentIndex, 'X' );  // Get X/Y position in the string (if any)
            char* indexY = strchr( line+currentIndex, 'Y' );
            if ( indexY <= 0 ) {
              newPos.x = atof( indexX + 1);
              newPos.y = actuatorPos.y;
            }
            else if ( indexX <= 0 ) {
              newPos.y = atof( indexY + 1);
              newPos.x = actuatorPos.x;
            }
            else {
              newPos.y = atof( indexY + 1);
              indexY = '\0';
              newPos.x = atof( indexX + 1);
            }
            drawLine(newPos.x, newPos.y );
            //        Serial.println("ok");
            actuatorPos.x = newPos.x;
            actuatorPos.y = newPos.y;
            break;
          }
          break;
        case 'M':
          buffer[0] = line[ currentIndex++ ];        // /!\ Dirty - Only works with 3 digit commands
          buffer[1] = line[ currentIndex++ ];
          buffer[2] = line[ currentIndex++ ];
          buffer[3] = '\0';
          switch ( atoi( buffer ) ){
          case 300:
            {
              char* indexS = strchr( line+currentIndex, 'S' );
              float Spos = atof( indexS + 1);
              //         Serial.println("ok");
              if (Spos == 30) {
                penDown();
              }
              if (Spos == 50) {
                penUp();
              }
              break;
            }
          case 114:                                // M114 - Repport position
            Serial.print( "Absolute position : X = " );
            Serial.print( actuatorPos.x );
            Serial.print( "  -  Y = " );
            Serial.println( actuatorPos.y );
            break;
          default:
            Serial.print( "Command not recognized : M");
            Serial.println( buffer );
          }
        }
      }

    }

    /*********************************
     * Draw a line from (x0;y0) to (x1;y1).
     * int (x1;y1) : Starting coordinates
     * int (x2;y2) : Ending coordinates
     **********************************/
    void drawLine(float x1, float y1) {

      if (verbose)
      {
        Serial.print("fx1, fy1: ");
        Serial.print(x1);
        Serial.print(",");
        Serial.print(y1);
        Serial.println("");
      }

      //  Bring instructions within limits
      if (x1 >= Xmax) {
        x1 = Xmax;
      }
      if (x1 <= Xmin) {
        x1 = Xmin;
      }
      if (y1 >= Ymax) {
        y1 = Ymax;
      }
      if (y1 <= Ymin) {
        y1 = Ymin;
      }

      if (verbose)
      {
        Serial.print("Xpos, Ypos: ");
        Serial.print(Xpos);
        Serial.print(",");
        Serial.print(Ypos);
        Serial.println("");
      }

      if (verbose)
      {
        Serial.print("x1, y1: ");
        Serial.print(x1);
        Serial.print(",");
        Serial.print(y1);
        Serial.println("");
      }

      //  Convert coordinates to steps
      x1 = (int)(x1*StepsPerMillimeterX);
      y1 = (int)(y1*StepsPerMillimeterY);
      float x0 = Xpos;
      float y0 = Ypos;

      //  Let's find out the change for the coordinates
      long dx = abs(x1-x0);
      long dy = abs(y1-y0);
      int sx = x0<x1 ? StepInc : -StepInc;
      int sy = y0<y1 ? StepInc : -StepInc;

      long i;
      long over = 0;

      if (dx > dy) {
        for (i=0; i<dx; ++i) {
          myStepperX.onestep(sx,STEP);
          over+=dy;
          if (over>=dx) {
            over-=dx;
            myStepperY.onestep(sy,STEP);
          }
        delay(StepDelay);
        }
      }
      else {
        for (i=0; i<dy; ++i) {
          myStepperY.onestep(sy,STEP);
          over+=dx;
          if (over>=dy) {
            over-=dy;
            myStepperX.onestep(sx,STEP);
          }
          delay(StepDelay);
        }
      }

      if (verbose)
      {
        Serial.print("dx, dy:");
        Serial.print(dx);
        Serial.print(",");
        Serial.print(dy);
        Serial.println("");
      }

      if (verbose)
      {
        Serial.print("Going to (");
        Serial.print(x0);
        Serial.print(",");
        Serial.print(y0);
        Serial.println(")");
      }

      //  Delay before any next lines are submitted
      delay(LineDelay);
      //  Update the positions
      Xpos = x1;
      Ypos = y1;
    }

    //  Raises pen
    void penUp() {
      penServo.write(penZUp);
      delay(penDelay);
      Zpos=Zmax;
      digitalWrite(15, LOW);
        digitalWrite(16, HIGH);
      if (verbose) {
        Serial.println("Pen up!");

      }
    }
    //  Lowers pen
    void penDown() {
      penServo.write(penZDown);
      delay(penDelay);
      Zpos=Zmin;
      digitalWrite(15, HIGH);
        digitalWrite(16, LOW);
      if (verbose) {
        Serial.println("Pen down.");

      }
    }

This are the connections I made:

[![connections][1]][1]

I tried replacing motors with each other but the case remains same just the motor now connected to the port(which is not working ) starts jittering and another one works but gets too hot.

  [1]: https://i.stack.imgur.com/XlyUg.jpg

title: One port of motor shield doesn't operating stepper motor

Answers: 1

body:
I ran into the same issue yesterday. The problem is that one of the pins of the M1 Port touches the housing of the usb-jack and shortens Vcc to Gnd. Try to put some tape around the housing...

bye

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

  [1]: https://i.stack.imgur.com/hXexE.jpg


body:
I would like to get the serial numbers of SD cards, with follow code:

<!-- language: lang-c++ -->

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

    // set up variables using the SD utility library functions:
    Sd2Card card;
    SdVolume volume;
    SdFile root;

    cid_t cid;  // *****at the top with the other globals (for get cid)

    // change this to match your SD shield or module;
    // Arduino Ethernet shield: pin 4
    // Adafruit SD shields and modules: pin 10
    // Sparkfun SD shield: pin 8
    const int chipSelect = 4;

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.print("\nInitializing SD card...");

      // we'll use the initialization code from the utility libraries
      // since we're just testing if the card is working!
      if (!card.init(SPI_HALF_SPEED, chipSelect)) {
        Serial.println("initialization failed. Things to check:");
        Serial.println("* is a card inserted?");
        Serial.println("* is your wiring correct?");
        Serial.println("* did you change the chipSelect pin to match your shield or module?");
        return;
      } else {
        Serial.println("Wiring is correct and a card is present.");
      }

      // print the type of card
      Serial.print("\nCard type: ");
      switch (card.type()) {
        case SD_CARD_TYPE_SD1:
          Serial.println("SD1");
          break;
        case SD_CARD_TYPE_SD2:
          Serial.println("SD2");
          break;
        case SD_CARD_TYPE_SDHC:
          Serial.println("SDHC");
          break;
        default:
          Serial.println("Unknown");
      }

      // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
      if (!volume.init(card)) {
        Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
        return;
      }

      // print the type and size of the first FAT-type volume
      uint32_t volumesize;
      Serial.print("\nVolume type is FAT");
      Serial.println(volume.fatType(), DEC);
      Serial.println();

      volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
      volumesize *= volume.clusterCount();       // we'll have a lot of clusters
      volumesize *= 512;                            // SD card blocks are always 512 bytes
      Serial.print("Volume size (bytes): ");
      Serial.println(volumesize);
      Serial.print("Volume size (Kbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);
      Serial.print("Volume size (Mbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);

      Serial.println();

      // *****list all files in the card with date and size
      //Serial.println("\nFiles found on the card (name, date and size in bytes): ");
      //root.openRoot(volume);
      //root.ls(LS_R | LS_DATE | LS_SIZE);

      card.readCID(&cid);
      Serial.print("Serial number: "); Serial.println(cid.src); // psn is the serial number field of the struct

    }

    void loop(void) {

    }

I tried to get serial from SD card but I only get this "Serial number: 2065301974". I really need it in hex format, for example "0x0033515c".

Also, I would like to get the complete CID like this:

    CID: 0x1B, 0x53, 0x4D, 0x30, 0x30, 0x30, 0x30, 0x30, 0x10, 0x45, 0x5D, 0x04, 0xE5, 0x00, 0xF9, 0x69

title: Read CID from SD card with ESP8266

Answers: 2

body:
To print the serial number in hex [Serial.println][1] accepts a format parameter:

    Serial.println(cid.psn, HEX);

The cid variable is a struct so you can access the the other fields via the structure. But if you really want to access the raw bytes you could cast cid to a pointer then access the individual bytes:

    uint8_t *rawcid = reinterpret_cast<uint8_t*>(&cid);
    Serial.println(*(cid+3), HEX); // print the 4th byte

Be aware that casting like this can be tricky and you will likely shoot yourself in the foot more than once.

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/println/

body:
`cid_t` is a structure that has all sorts of information in it in different formats.  The serial number (`psn`) is just a 32-bit unsigned integer.  You can print it as hex by printing it as hex.

    Serial.println(cid.psn, HEX);

If you want to get the raw data of the structure (which I assume may correspond to the raw data read from the card, but don't quote me on that) you can access the struct as 8-bit values:

    uint8_t *p = (uint8_t *)&cid;
    for (int i = 0; i < sizeof(cid); i++) {
        Serial.print("0x");
        Serial.print(p[i], HEX);
        Serial.print(" ");
    }
    Serial.println();


body:
[![Power from 5V USB wall adapter][1]][1]

  [1]: https://i.stack.imgur.com/7Hecn.jpg

I want to power the UNO with the USB power adapter (the charger of a phone), the adapter delivers 5.0 volts and comes from the wall (in the photo a regulator is added). However, the legs of the USB adapter look the same, can I plug it to the wall indistinctly like I do when I charge the phone, or do I need to know which leg is + and which one is - ? (I don't have measurement equipment).

title: Can't identify + or - in the 5v USB wall adapter, does it matter?

Answers: 2

body:
It does not matter which orientation you plug it into the mains plug.

The power supply produces the same 5V regardless, and the USB plug has a fixed/standard polarity on the pinout.

body:
Power (which comes from your wall outlet), is AC, which means alternating current. It changes 50 or 60 times per second from direction, so this is the reason it does not matter if you plug it reversed or not. Some countries have plugs which can be plugged in normally or 180 degrees rotated (but you cannot see what is 0 or 180 degrees since these are symmetrical).

The circuit inside the adapter makes sure the AC is converted to DC, where it matters what is Plus or Minus.


body:
When I send an SMS like this:

>Tilt:090
>
>Azimuth:120

First time an SMS is read, the servo rotates to the correct position, but after they change a small angle, it's like noise.

I do following things to stop that change:

* First try with motor driver

* Capacitor circuit use

Here is my code:

<!-- language: lang-c++ -->

    #include <AFMotor.h>
    #include <Sim800l.h>
    #include <SoftwareSerial.h>
    #include <Servo.h>

    Sim800l Sim800l; //to declare the library
    Servo Tilt;
    Servo Azimuth;

    String text; // to storage the text of the sms
    uint8_t index; // to indicate the message to read.
    int t, pos, old_pos, pos1, old_pos1; // to indicate the int value.

    void setup()
    {
        Tilt.attach(9); // attaches the servo on pin 5 to the servoH object
        Azimuth.attach(10); // attaches the servo on pin 6 to the servoV object
        Serial.begin(9600); // only for debug the results .
        Sim800l.begin(); // initializate the library.
        index = 1; //  position in the prefered memory storage.
    }

    void Tilt_servo()
    {
        if (old_pos > pos) {
            for (int q = old_pos; q > pos; q--) {
                Tilt.write(q);
                delay(20);
                Serial.println("position dicreasing");
            }
        }
        else if (old_pos < pos) {
            for (int q = old_pos; q < pos; q++) {
                Tilt.write(q);
                delay(20);
                Serial.println("position increasing");
            }
        }
        else {
            Tilt.write(pos);
        }
    }

    void Azimuth_servo()
    {
        if (old_pos1 > pos1) {
            for (int d = old_pos1; d > pos1; d--) {
                Azimuth.write(d);
                delay(20);
                Serial.println("position1 dicreasing");
            }
        }
        else if (old_pos < pos) {
            for (int d = old_pos1; d < pos1; d++) {
                Azimuth.write(d);
                delay(20);
                Serial.println("position1 increasing");
            }
        }
        else {
            Azimuth.write(pos1);
        }
    }

    void loop()
    {
        delay(1000);

        Serial.println("---------------------------------------------------------------------------");
        old_pos = pos;
        old_pos1 = pos1;

        Serial.println("old_pos:");
        Serial.println(old_pos);
        Serial.println("old_pos1:");
        Serial.println(old_pos1);

        text = Sim800l.readSms(index);
        Serial.println(text);
        String W = text.substring(33, 45); // filter phone number...
        Serial.println(W);
        String y = text.substring(20, 30); // filter REC UNREAD
        Serial.println(y);

        if (y == "REC UNREAD") {

            String s = text.substring(74, 79); // filter the "Tilt:"
            Serial.println(s);
            String p = text.substring(79, 82); // filter the position
            int t = p.toInt(); // convert position as int value
            Serial.println(t);
            pos = t;

            String v = text.substring(83, 91); // filter the "Azimuth:" letter
            Serial.println(v);
            String u = text.substring(91, 94); // filter the position as string
            int b = u.toInt(); // convert position as int value
            Serial.println(b);
            pos1 = b;

            if (s == "Tilt:" && v == "Azimuth:") {

                Tilt_servo();
                delay(1000);
                Serial.println("done....Tilt...");
                Serial.println(pos);
                Azimuth_servo();
                delay(1000);
                Serial.println("done....Azimuth...");
                Serial.println(pos1);
            }
            //Sim800l.delAllSms();
            //delay(5000);
        }

        else {
            Tilt.write(pos);
            Azimuth.write(pos1);
        }

        delay(1000);
        Sim800l.delAllSms();
        delay(5000);
        Serial.println("---------------------------------------------------------------------------");
    }

title: Servo position is always changing

Answers: 0


body:
So I have a circuit that works well when it's on a breadboard and without removing any pins I'm able to upload sketches, but for some reason when I transition it to a protoboard I can no longer upload sketches.

My circuit consists of an MPU6050, an Arduino Pro Mini, and a HC-08 BLE module. I've tried protoboarding this circuit twice with Arduino Pro Minis and once with an Arduino Nano, and now I'm not able to upload sketches to any of these three circuits.

I'm using perfboard (not stripboard, so yes I have already connected the jumper wires to the header pins) and know that the circuit partially works since the IMU, Arduino, and BLE LEDs all light and you can connect to the BLE on a mobile terminal app.

The error I get is:

    avrdude: stk500_getsync(): not in sync: resp=0x00,

 - I use SoftwareSerial.h so NO pins are connected to the Arduinos 0 and 1 pins.
 - I've already tried restarting the IDE
 - I've tried disconnecting/reconnecting the USB cable
 - There's only one COM# port so I'm sure I'm using the right one.

I'm so stumped because this error message *did not occur* when I was playing with the *same* circuit on a breadboard...

**Any ideas on how I can fix this or what I'm doing wrong?**

title: Can't reprogram Arduino on protoboard (perfboard), but could program the same circuit on breadboard

Answers: 0


body:
I want to build a very simple device, which has a bunch of buttons for switching "settings" and LED lights to show which "setting" it is on.  I also want it to record the times of the transitions between settings so that I can later connect it to a computer through USB and retrieve the timestamps of the setting changes, i.e. when the buttons were pressed.

What is the best way to do this?  Is it with Arduino or some other way?  If it is with Arduino, what would I need to buy, and what would I need to read?

title: How to create a device with buttons that records when they are pressed

Answers: 2

body:
Arduino is ideal for it. Buy Arduino or Genuino UNO with Starter Kit. Starter kits contain buttons, LEDs, resistors, breadboard and example projects brochure.

link: [Getting Started with Arduino][1]

  [1]: https://www.arduino.cc/en/Guide/HomePage

body:
All is reasonably easy.

- Buttons: use separate buttons, or think about a small 4x4 matrix keypad.
- LED: WS8212 etc or use your own separate LEDs (very cheap)
- Record times: store them on a SD card
- USB: It is possible to send texts via USART which can connect via USB; also you can consider putting the SD card directly in your computer.


body:
I have the sketch from James Waldby ([Read RC receiver channels using Interrupt instead of PulseIn][1]) working beautifully. I want to use a switch on my TX to start and stop a sequence of lights (emulating guns firing on a ship model). But first, I need the delayed flash routine to work. I have tried a loop counting millis() differences to separate the sequences, but the delays don't delay.

     void loop(){
      rc_read_values();//Mr. Waldby's interrupt routine
      currentMillis = millis();
      previousMillis = currentMillis;
      if(fireGun ==1){
        interval = 3000;
      }else{
        interval = 1500;
      }
      interval = 3000;
      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

    //if(fireGun ==1){
      analogWrite(led, 255);
      delay(50);
    /* a real gun flash doesn't cut right off; it fades away.
      This sequence simulates that  */
      while(brightness > 0){

        // change the brightness for next time through the loop:
        brightness = brightness - fadeAmount;
        analogWrite(led, brightness);
        delay( 7);
      }
      brightness = 80;
    }

  [1]: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein

The intention here is to flash the led every 3 seconds. The flash loop works fine, but the 3 second delay doesn't.

The delay routine works ok in a sketch by itself.

Any thoughts about what I might be doing wrong?

title: other interrupts in rc channel reader

Answers: 1

body:
>       currentMillis = millis();
      previousMillis = currentMillis;

So currentMillis and previousMillis will always be exactly the same, right?

>       if (currentMillis - previousMillis >= interval) {

So if `0 >= interval` (which it won't be) do something?

Therefore your fading code will never be executed.


body:
I have different arrays of different sizes, and a list of pointers to the addresses of each array. How do I select each array using the list of pointers, and access it's elements. On Teensy 3.2 board.

    int * arr_list[3];
    const int arr_sizes[3] = {3,4,5};  // array of the array sizes
    const int ar1[3] = {12,2,8};       // arrays of  different sizes
    const int ar2[4] = {41,3,6,47};
    const int ar3[5] = {9,32,1,5,7};

    void map_arrays(){          // list of pointers with the addresses of the
                                // arrays
    arr_list[0] = (int*) &ar1;
    arr_list[1] = (int*) &ar2;
    arr_list[2] = (int*) &ar3;
    };

    int arr_number = 1;          // select array
    int a = arr_sizes[arr_number];    // the size of the selected array
    int *b = arr_list[arr_number];
    int test = 0;

    void setup() {

    Serial.begin(57600);  //serial monitor

    }

    void loop() {

    for (int i=0; i<a; i++) {     // for the selected arr_number iterate and
    test = b[i];                  // return the index elements

    }

    Serial.println("size =");
    Serial.println(a);
    Serial.println();
    delay(1000);
    Serial.println("index =");
    Serial.println(test);
    Serial.println();
    delay(500);

     }

title: Selecting different arrays using a list of pointers

Answers: 1

body:
You have it right, only fix initialization of test variables:

1. you do not call map_arrays() in setup()
2. you assign uninitialized arr_list item to b

>     const int* arr_list[3];
>     const int arr_sizes[3] = { 3, 4, 5 };  // array of the array sizes
>     const int ar1[3] = { 12, 2, 8 };       // arrays of  different sizes
>     const int ar2[4] = { 41, 3, 6, 47 };
>     const int ar3[5] = { 9, 32, 1, 5, 7 };
>
>     void map_arrays() {          // list of pointers with the addresses of the
>     // arrays
>       arr_list[0] = ar1;
>       arr_list[1] = ar2;
>       arr_list[2] = ar3;
>     }
>
>     int arr_number = 1;          // select array
>     int a = arr_sizes[arr_number];    // the size of the selected array
>     const int *b;
>     int test = 0;
>
>     void setup() {
>
>       Serial.begin(57600);  //serial monitor
>
>       map_arrays();
>
>       b = arr_list[arr_number];
>
>       for (int i = 0; i < a; i++) {     // for the selected arr_number iterate and
>         test = b[i];                 // return the index elements
>         Serial.println(test);
>       }
>
>       Serial.println("size =");
>       Serial.println(a);
>       Serial.println();
>       delay(1000);
>       Serial.println("index =");
>       Serial.println(test);
>       Serial.println();
>       delay(500);
>
>     }
>
>     void loop() {
>     }


body:
I am just getting started with arduino, but I am having an issue with some 3.3V, 8Mhz Arduino Pro Minis. I am using a SparkFun FT232RL USB to Serial breakout (https://www.sparkfun.com/products/12731) to communicate with the board, using Windows 7 and the Arduino IDE.

The Pro Minis were blank when I got them, I am able to upload a single program (Blink), which runs successfully, but I am unable to upload subsequent programs. I get the error:

    avrdude: stk500_recv(): programmer is not responding

Any idea what might be going on?

title: Can't re-write Arduino Pro Mini

Answers: 1

body: Connect the DTR pin from the FT232 to the Promini as well, that will allow the software autoreset to work. Promini has a 0.1uF cap between the DTR pin and Reset already.


body:
I'm attempting to use the arduino as an ICSP AVR to flash hundreds of ATMEGA's 90USB162.  I'm having some difficulties when trying to do the actual flashing of the chip.  I've go all the wires done properly and I'm able to read the signature.  My source is an Intel hex file and I'm reading it properly as I'm able to see each by as it is read from the arduino's memory.  Where I'm getting lost is the documentation states that I need to set the low byte first before I set the high byte for the same memory address.  Using the following as an example (underscores to break the data up) could someone help me descern what my SPI transaction bytes would look like?

    :_20_0000_00_16C100003CC100003AC1000038C1000036C1000034C1000032C1000030C10000_48

I know the colon is the start code, 20 is the hex value of number of data bytes,  0000 is the address, 00 is the record type,  the next 32 bytes is my data followed by the checksum.

I thought that I would loop over the data portion and increment the address every other byte

    uint16_t addr = 0;

    while (recordtype != endOfFile)
    {
      auto data[] = parseData();

      for(uint8_t index = 0; index < 32;)
      {
        SPITask.Send(0x40, 0x00, addr, data[index++]);//send low byte
        SPITask.Send(0x48, 0x00, addr, data[index++]);//send high byte
        SPITask.Send(0x4C, addr, addr, 0x00);//commit new bytes to address
        addr++;
      }
    }

I don't think this is right and some examples i'm loosely following comment that they are changing the address byte into a word, which makes some sense based on the command layouts of the data sheet (page 260) [90USB162 Data sheet][1].  Can anyone please provide some guidance in how to break up this data into high and low bytes.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/doc7707.pdf

title: parse intel hex into SPI commands for arduino ICSP AVR

Answers: 1

body:
I have some code that does [exactly what you want on GitHub](https://github.com/nickgammon/arduino_sketches/blob/master/Atmega_Hex_Uploader_Fixed_Filename/Atmega_Hex_Uploader_Fixed_Filename.ino).

Amongst other processors, it supports the At90USB162 chip. The code reads from an SD card in Intel hex format and writes to the chip at the press of a switch. This effectively is what you are trying to do.

Arduino forum moderator "Crossroads" (who has recently also [joined Stack Exchange](https://arduino.stackexchange.com/users/42539/crossroads)) has made [a board to do the programming](http://www.crossroadsfencing.com/BobuinoRev17/Programmer.html), hold the SD card, and have some status LEDs:

[![Board programmer][1]][1]

Here is my code to write to the flash:

<!-- language: lang-c++ -->

    // execute one programming instruction ... b1 is command, b2, b3, b4 are arguments
    //  processor may return a result on the 4th transfer, this is returned.
    byte program (const byte b1, const byte b2 = 0, const byte b3 = 0, const byte b4 = 0)
      {
      noInterrupts ();
      BB_SPITransfer (b1);
      BB_SPITransfer (b2);
      BB_SPITransfer (b3);
      byte b = BB_SPITransfer (b4);
      interrupts ();
      return b;
      } // end of program

    // write a byte to the flash memory buffer (ready for committing)
    void writeFlash (unsigned long addr, const byte data)
      {
      byte high = (addr & 1) ? 0x08 : 0;  // set if high byte wanted
      addr >>= 1;  // turn into word address
      program (loadProgramMemory | high, 0, lowByte (addr), data);
      } // end of writeFlash

---

Your loop looks a bit strange, the page size (before you need to commit) is 128 bytes (64 bytes), not 2 bytes.

See the datasheet:

[![Flash page size][2]][2]

  [1]: https://i.stack.imgur.com/NxuA3.jpg
  [2]: https://i.stack.imgur.com/41P7t.png


body:
I have this code and it is a reaction light game. When you press the button on pin 11 it starts the game and the lights should osculate back and forth. The main goal is to press the button when it hits the middle led and the osculating will slow down. I cannot get the leds to turn on help?

        int ledPin;
        int direction;
        int isChanging;
        unsigned long lastChange;

    void setup() {
       //set pins 2 to 10 to be output
      // and LEDs off
       int pin;
        for (pin = 2; pin <= 10; pin++) {
           pinMode(pin, OUTPUT);
           digitalWrite(pin, LOW);
        }
         //set pin 11 to be input
         pinMode(11, INPUT);

         ledPin = 2;
         direction = 1;
         lastChange = millis();
      }

     void loop() {
        if (isChanging) {
        if (millis() - lastChange > 500) {
            //turn off old LED
            digitalWrite(ledPin, LOW);
            //reset time
            lastChange = millis();
            //change the led
            ledPin = ledPin + direction;
            if (ledPin > 10) {
              direction = -1;
            ledPin = 9;
          } else (ledPin < 2); {
            direction = +1;
            ledPin = 3;
         }

           //turn on new LED
            digitalWrite(ledPin, HIGH);
         }
           //check for button
           if (digitalRead(11)) {
            isChanging = 0;
         }
         }
        else {
           //wait for them to let go of the button
           while (digitalRead(11)) {
         }
           //wait for it to be pressed again
           while (!digitalRead(11)) {
         }
           //wait for them to let go of the button
           while (digitalRead(11)) {
         }
        }
       }`

title: Arduino Reaction LED game

Answers: 1

body:
Your are not explicitly initializing the variable `isChanging`, so the compiler sets it to `0`. This means, that your code will directly go to the last else statement and cannot at any time reach the LED code, because you are not changing the variable in the else statement.

But I don't really understand, why you were using this variable in the first place. Try to use purely non-blocking code. For checking the button you can do something like this:

    boolean button_pressed = false;
    unsigned long button_timestamp = 0;

    void loop(){
      ...
      if(!button_pressed && digitalRead(11)){
        button_pressed = true;
        button_timestamp = millis();
      }
      if(button_pressed && millis() - button_timestamp > 50){
        if(digitalRead(11)){ // real button press
          button_pressed = false;
          // check, if the middle LED is ON and act accordingly
          // or, if the game hasn't started yet, start it
        } else { // just a bounce of the button, not a real button press
          button_pressed = false;
        }
      }

      // LED CODE
      if (millis() - lastChange > 500) {
        ...
      }
    }

Note, that this code will not wait for the button to be released, but reacting, when the button was held down for 50ms. You can change this value, to a one, that is more fitting your used button, but it is a good start point.

Also in your LED code, you have to replace the 500 in the millis statement with a variable, since you want to change the speed.

For handling starting the game with the same button, you can use a state variable, which contains a value of means "Game Stopped" or "Game Started".


body:
![enter image description here](https://i.stack.imgur.com/oMzIX.jpg) arduino didn't working properly. When i using a alarm program on pin 6 and a blinking led on pin 2 alarm sound beeps once and then goes down but when using only alarm program it works perfectly. I see that arduino can handle one pin perfectly but when it comes to use two pins together it can't handle properly

    float sinVal;
    int toneVal;
    void setup(){
        pinMode(7, OUTPUT);
        pinMode(2, OUTPUT);
    }
    void loop(){
        for(int x=0; x<180; x++)
            { //convert angle of sinusoidal to radian measure
            sinVal = (sin(x*(3.1412/180)));
            //generate sound of different frequencies by sinusoidal value
            toneVal = 2000+(int(sinVal*1000));
            //Set a frequency for Pin-out 8
            tone(7, toneVal);
            delay(2); }
        digitalWrite(2, HIGH);
        delay(100);
        digitalWrite(2, LOW);
        delay(200);
    }

title: arduino didn't working properly

Answers: 2

body: with this wiring setting pin 2 HIGH shorts pin 2 to ground and Arduino dies. you must use a resistor in series with LED. and better use one with the speaker too.

body: I'm not sure but its your power supply. I suggest to used another power supply on your arduino. Use 9V battery and connect it to Vin(+) and GND(-) and test if there is an improvement.


body:
I'm currently designing a battery operated device that has to write data to an EEPROM before shutting down, or in regular intervals to save data. Would it damage the EEPROM if it had to shut down while it is being written to?

The first possible case is when it is transmitting the data over I2C. That shouldn't affect it much. But if it gets powered down while it is actually writing the byte to its memory, I don't know whether it would save it correctly or corrupt it.

title: Write to EEPROM before shutdown

Answers: 1

body: According to the datasheet, an EEPROM write takes 3.3mS. If power drops below the level needed to complete the write, the data will be corrupted.


body:
I have an ATtiny and am trying to send a very large byte array stored in a separate `.h` file over SoftwareSerial:

    for (int i=0; i<numElements; i++) {
        softSerial.println(myList[i]);
    }

I imagine it will very slow, which is fine, but I'm getting a cryptic error when compiling:

    Firmware.ino.elf section `.data' will not fit in region `text'

It seems that this is due to the `println()` command running out of memory for some reason – if I comment out the `println()` command everything works fine. How to fix this?

title: SoftwareSerial runs out of "text" space on ATtiny

Answers: 3

body:
Your sketch doesn't fit into program memory of the ATtiny. If you comment out the `println` of the array, the compiler evaluates that the array is not used and doesn't attach it to the program. Then the program fits into memory.

**EDIT**
Chad suggests some good alternatives below, if you need to store more data than flash or `PROGMEM` will allow.

body:
There is not enough room in program memory for 140KB. ATiny only has 8KB for the whole program. So there is no way to fix this with your current hardware.

Options-

add a storage device (SD card, sram module, others....) where you can store the data, and then read it in small chunks and send it out

possibly use a arduino mega. It has 256KB of program space. you will still have to make sure you are not trying to store the whole byte array in an array since that would get stored in sram (which there is still only 8KB) but it could again to written in chunks to avoid this problem.

body:
The ATTiny only has a limited amount of RAM. A lot less that flash-memory.

Using a normal array, the entire contents of the array are placed into RAM (during initialization). Which is very limited.

I'd suggest, looking into [PROGMEM](https://www.arduino.cc/reference/en/language/variables/utilities/progmem/). This is a way to read the data directly from the flash-memory.


body:
I'm trying to get a program to use protothreading and I've got an error at the include statement for the pt.h library stating that there is no such file or directory. This is how it's written in the program:

    #include <pt.h>

title: Has pt.h library been removed from arduino?

Answers: 1

body:
`pt.h` has never, and will never, be part of the Arduino core distribution.  It is a completely separate third party library that you have to install yourself.

I think the library you want is [this one.](https://github.com/fernandomalmeida/protothreads-arduino)


body:
So this is the second time that I've had a circuit that worked perfectly on a breadboard, but as soon as I connected it to a perfboard and soldered the joints together, the Arduino stopped working and wouldn't let me upload sketches (though I could see a COM port for it).

I'm using lead-free solder for the first time, and had the temperature at 750 deg Fahrenheit, and I'm thinking that while I had quick joints to connect the Arduino to the perfboard, when bridging two joints with solder, the iron might have been heating the header pin for 4-10 seconds... Is that enough to break the board?

[![my perfboard joints][1]][1]

(note - I'm using jumper wires on the other side to connect everything up, and I've already checked the board's connections using a multimeter and they're all as intended, and there are no accidental shorts/bridges)

  [1]: https://i.stack.imgur.com/rVYSK.jpg

title: Did I overheat my Arduino while soldering to perfboard?

Answers: 2

body:
Bridging adjacent pins by heating for 10 seconds is not a great way of doing things. You are trying to cross the "solder resist" with solder, so you are basically fighting something.

I normally use some tinned copper wire to cross gaps like that. You should be able to keep the soldering times down to a couple of seconds.

> Did I overheat my Arduino ... ?

We can't really say from where we sit, but maybe.

> I could see a COM port for it

The Pro Mini doesn't have a USB chip, so how are you programming it?

---

> I am using an FTDI breakout board to program the Pro Mini, which then attaches to a USB cable.

Right, well you are seeing the COM port from the FTDI breakout board, not the Arduino as such. You would see that even if there was no Arduino there at all.

---

The soldering on one of your pins (5th from the bottom, on the right) looks a bit dodgy. It might just be the light.

As I said earlier, you possibly overheated the processor chip. I would use the technique I described rather than a 10-second heat.

See my question/answer: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board - that describes various tests you can do to check if the processor is still good.

body:
>I would like to clarify that my only question in ENTIRE post was: "Is that enough to break the board?"

The answer to that narrow question is that *heat from soldering with an iron* is extremely unlikely to have done this.  IC's are in practice (vs data sheet) quite heat tolerant, and further the pins you are soldering on are not even the pins of the IC or any electronic components, but rather those of the module headers.  You'd be more likely to melt the plastic web between those headers pins, but even that won't be a great problem since they are already in place. Or if you were soldering directly on the board, lifting a pad or trace - but you were not doing that.

Your actual problem is something else, *what that might be* is presently unanswerable due to the lack of detail in your question.


body:
    #define ANALOG_IN 0

    void setup() {

      Serial.begin(19200);

      analogReference(INTERNAL);

    }

    void loop() {

      int val = analogRead(ANALOG_IN);

      Serial.print(0xff, byte);

      Serial.print( (val >> 8) & 0xff, byte);

      Serial.print( val & 0xff, byte);

    }

This is my code and I'm getting this error for all 3 Serial.print commands. Please help.

title: expected primary expression before ')' token

Answers: 1

body:
Why are you putting `byte` there? That isn't in the [Serial.print reference page](https://www.arduino.cc/reference/en/language/functions/communication/serial/print/).

This compiles OK:

    #define ANALOG_IN 0

    void setup() {
      Serial.begin(19200);
      analogReference(INTERNAL);
    }

    void loop() {
      int val = analogRead(ANALOG_IN);
      Serial.print(0xff);
      Serial.print( (val >> 8) & 0xff);
      Serial.print( val & 0xff);
    }


body:
I'd like to know if there is any way to know what is the origin of an external interrupt by programming inside the ISR.

I know I can use a different ISR for each external interrupt and that works but I'm thinking if it's possible to use the same ISR for all external interrupts

If you check the origin pin and trigger condition inside ISR it's not a reliable way to do.

Is there any memory record which store the external interrupt activation?

This is a general question for any AVR microcontroller.

title: How to know the external interrupt origin from the ISR

Answers: 1

body:
> Is there any memory record which store the external interrupt
> activation?

There is, but I do not think it will be easy to exploit.

At low level, each interrupt is handled by a different ISR. So you will
have `INT0_vect` handling external interrupt 0 and `INT1_vect`
handling interrupt 1. These ISRs are all defined by the Arduino
core library. In your case, they will both call the same handler that
you defined. Thus, the information about which ISR fired is now on the
stack: it is the return address of your function.

The reason this information will not be easy to use is that you do not
know how far it is from the stack pointer. It depends on how much stuff
your own handler pushed onto the stack. You could disassemble it and
count, but then your code will be fragile, as the smallest change in the
handler (or compiler version) may change this count.

An easier approach may be to define your own `INT0_vect` and
`INT1_vect`, overriding those from the Arduino core. These new ISRs
will both call your handler, but they will pass it an argument to tell
which interrupt fired.

Or you can register a different handler for each interrupt, each calling
a common function. But this adds an extra level of function calls.


body:
not sure if this is the right place to post, but basically I am trying to make a Love-O-Meter, similar to the Arduino project example.

However, my method of determining the score is different. Instead of basing it on temperature, I am basing it on capacitance instead (Let me know if you think there are better ways to determine the score. I have tried body resistance, but it is too insensitive and I have also tried making it random but it doesnt make sense and its not as fun)

Another difference is that I want to make it only measure when both people place 1 of their hands on the foil and their other hand holding onto each other. However, the issue I have is Im not sure how to start measuring when the condition I mention happens.

Link to code: https://pastebin.com/bWyiDtfB (Using reference from here: https://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense) (The code starts measuring the capacitance when it detects that both foils have their hands placed on it, i.e.  when it detects that the capacitance exceeds a certain threshold, 200 for my case. It will then measure 100 samples and the score will be from the median of the 100 samples)
Link to fritzing diagram: https://i.stack.imgur.com/cOb7h.jpg (Ignore the black wire from A5)

title: Need help with Arduino Love-O-Meter

Answers: 0


body:
When I'm converting a string to a char array there are always some weird chars at the end.
I have to do it manualy because the convertTochar function crashes my ESP.

      String sssid = module.getCssid(); //String is stored in the eeporm
      char cssid[sssid.length()];
      Serial.println(sssid.length()); //prints correct length of 6
      //convert do ssid
      for( int i = 0; i<sizeof(cssid);i++){
        cssid[i] = sssid[i];
      }
      Serial.println(cssid); //prints myssid⸮?⸮2⸮?
    enter code here

If I'm printing the value directly fromm eeprom there are no wired characters.
Also the max eeprom size for the string is 10 bytes...

Why are these characters at the end of string?

title: remove weird chars from char array ESP32

Answers: 1

body:
You forgot to add one more character to the array to place a \0 (0 value byte) in. This denotes the end of a string. If you forget this, the string will continue until it finds the first 0 byte, which will probably be after the original string copy. This can be dangerous, because it might be in memory that is not containing useful data, and those weird character can be many if there is not a 0 soon or at all.

Note that the 6 bytes you get are the bytes EXCLUDING this 0 byte, so you need to allocate 7 bytes to store a string of length 6.

Instead of the for loop you can use the strcpy function which copies a function including the 0 string.

See [description][1]:

Description

The C library function char *strcpy(char *dest, const char *src) copies the string pointed to, by src to dest.

Declaration

Following is the declaration for strcpy() function.
char *strcpy(char *dest, const char *src)

Parameters

dest − This is the pointer to the destination array where the content is to be copied.

src − This is the string to be copied.

Return Value

This returns a pointer to the destination string dest.

Example

The following example shows the usage of strcpy() function.

    #include <stdio.h>
    #include <string.h>

    int main () {
       char src[40];
       char dest[100];

       memset(dest, '\0', sizeof(dest));
       strcpy(src, "This is tutorialspoint.com");
       strcpy(dest, src);

       printf("Final copied string : %s\n", dest);

       return(0);
    }

  [1]: https://www.tutorialspoint.com/c_standard_library/c_function_strcpy.htm


body:
I have this LoLin NodeMcu V3 board:

[![LoLin NodeMcu V3][1]][1]

  [1]: https://i.stack.imgur.com/4OMWg.jpg

What are the pins S3, S2, S1, SC, S0, SK?
Can I use them as GPIO in Arduino?

Thank you for your help!

title: Use LoLin V3 pins starting with 'S' in Arduino

Answers: 2

body:
My guess is those are the SDIO pins. They're meant for use with an SD card - 4 data pins, a clock pin, and a select pin.

To find out what more you can do with them you should ignore the fact that it's a "LoLin" and instead just look for documentation on the ESP8266 or ESP32 (whatever it is on there) that powers that board.

body:
These pins have 2 functions: They are the connections to an SD card and/or to its internal flash chip. The ESP8266 has the feature of when you set GPIO15 HIGH during bootup, it will load the program from SD card and execute it. See [here][1] for reference. On the normal board, these pins are however connected to an internal flash chip.

Signal name meanings:

* SK: Serial Clock
* SC: SPI Chip Select
* S0 to S3: Data lines (Quad-I/O mode).

This picture found [here][2] explains the pins:
[![lolinv3][3]][3]

But as @Majenko already said, only the chip documentation matters, which is here:

[![esp12][4]][4]

Now to answer the actual question: Can you use these pins for arbitrary purposes? That depends. On the board they are all internally connected to a Quad-SPI flash chip. If you re-assign these pins to GPIO pins during normal operation in Quad-SPI mode, the chip hang up as the you just cut off one of the important lines to flash chip. **However**, if you really want you can modify your chip and cut two connections from the flash chip. Quad-SPI uses 4 data lines, but you can also operate the chip in Dual-SPI with 2 data lines (refer to [here][5]).

That means that you are able to cut 2 of the 4 data lines, GPIO9 (SPI_HD, S2 on the board) and GPIO10 (SPI_WP, S3 on the board) on the PCB from the ESP8266 to the flash chip and then use these two GPIO pins arbitrarily. This is to avoid interference with the flash chip when you are driving random signals to it while the lines are still physically conencted to the flash chip. You will ofcourse need to tell your flash tool (`esptool.py`) to use Dual-SPI mode for all subsequent firmwares. See [here][6] for that.

All other Flash GPIO pins can not be re-purposed, these conenctions (such as SCLK, MISO, MOSI, CS) are always needed for the flash chip.

GPIO15, which is D8 on the board, is easier to repurpose: You just need to make sure it's LOW during startup as to not trigger the SD card bootup by using a pulldown resistor. After flash bootup you can re-purpose it for input and output. This is already done on the board for you and you just need to use `pinMode` to set it as INPUT or OUTPUT. This is also described in [here][1].

Obviously that's a lot of trouble to get 2 GPIO pins. If you just want more GPIO, you will find an I²C GPIO port expander such as the [MCP23017][7] much more suitable for that -- 16 more GPIOs at the cost of 2 GPIO pins (the I2C bus). If you're already using the I2C bus in a project then you don't even loose additional GPIOs, it's just one more device on the bus.

  [1]: https://www.forward.com.au/pfod/ESP8266/GPIOpins/index.html
  [2]: https://www.lelong.com.my/arduino-iot-lolin-nodemcu-v3-lua-based-esp8266-wifi-development-board-littlecraft-193816300-2019-07-Sale-P.htm
  [3]: https://i.stack.imgur.com/3wTDt.jpg
  [4]: https://i.stack.imgur.com/xkSjR.png
  [5]: https://electronics.stackexchange.com/questions/28792/what-is-dual-quad-i-o
  [6]: http://smarpl.com/content/esp8266-esp-201-module-freeing-gpio9-and-gpio10
  [7]: https://www.adafruit.com/product/732


body:
I'm using an ESP8266 with the Arduino library to read from a sensor([MPU9250][1] specifically). The readings are done via I2C but I'm using a library that abstracts these methods.

The wires are not soldered together so temporary disconnections are possible and after these disconnects the sensor readings freeze. I'm new to the world of I2C so my questions are:

- Do I have to re-init the connection after it disconnects or is there a way to continue on re-connection immediately?
- Is there a way to prevent this to happen (for example to stop reading when there's no connection) or should I just solder together the pins?

  [1]: https://www.invensense.com/wp-content/uploads/2015/02/RM-MPU-9250A-00-v1.6.pdf

title: If an I2C connection is lost for a short period of time will it work if the connection is live again?

Answers: 1

body:
When an I2C master starts a transmission or a request from a slave, it sends the slaves address and then check for an acknowledgement (ACK) from the slave (SDA LOW, when the clock has a HIGH pulse). When no slave is connected, or there is no slave with this address, then there isn't any circuit to pull SDA to LOW on the clock pulse, that is generated by the master. This is interpreted as No acknowledgement (NACK) and the transmission/request fails and should exit. So a disconnection between the transmission should not freeze your code (though I don't know what your library is doing exactly).

A quick google search gives me, that the esp8266 does not have hardware I2C, so your library does a pure software I2C. There are many pitfalls, which can block the I2C bus (especially, if one the lines is hold LOW by one of the involving circuits). Your library may or may not implement the correct I2C protocoll.

So to clearly answer your questions:

 1. You don't have to reinit connection. Your master transmission fails, if there is no slave, and should give you an error as return value. But be sure, that there isn't happening anything on the SDA or SCL lines, when it starts up again after reconnection. Master or slave can interpret voltage spikes as signal.
 2. If the library is implemented correctly, it will exit, when there is no ACK from the slave.

Look into the documentation of your library how it handles these events. And check the state of SDA and SCL, when a block occures. You can refer to [this site][1] for further information about I2C. It also gives some advice if your bus is blocked.

  [1]: http://www.i2c-bus.org/i2c-primer/analysing-obscure-problems/blocked-bus/


body:
at once, when i connect arduino uno to my computer, my computer shuts down, after that i cannot upload programs to my computer,the board is not working but the led is ON. Before this, i upload programs 4 to 5 times continuously. i upload program with no physical connections in arduino except motor shield which is also not connected to anything.
i used three boards, all of them got damaged.

my computer's USB port and USB cable is in good codition.
i already updated my drivers.

computer spec: dell inspiron 15 3567
               windows10 x64 bit

title: my arduino uno board is not working

Answers: 1

body:
Computer shutting down is often an indication that excess power is being drawn.
If you measure  between +5 and Gnd on the unpowered board with a meter set for resistance, do you get a reading in the 5Kohm range? Or something much lower? Much lower would be bad.


body: Is there any "easy" way to emulate USB keyboard or gamepad using digital pins on Arduino Mega? I looked at Uno-Joy/Mega-Joy, but I dont find firmware changes appealing.

title: Arduino: using digital pins to emulate USB device

Answers: 1

body:
There is (or was) an implementation of software-only USB for the Arduino. I think it was called V-USB, though I am having trouble finding it now.

I think it may be [this library](https://github.com/gloob/vusb-for-arduino) though nothing has happened with that for a number of years.

Personally, I wouldn't recommend it, though, and would suggest using a board with a real USB interface, such as the Arduino Leonardo, chipKIT Lenny, or Teensy 3.x.