body:
I have recently taken apart an old digital camera for its parts and I have found an image sensor inside it.

For those of you who don't know, an image sensor measures light; the shutter opens, light hits the sensor and the sensor converts this light into data to be stored as an image.

My question is how can I implement it into a project? What equipment do I need? It has a tape wire so I'm not really sure how I can use it. I have attached a photo of it also. Thanks!!

[![Image of photo sensor][1]][1]

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

title: How do I use an image sensor with an arduino uno?

Answers: 2

body: You need to find markings on it and figure out what the component actually is.  Then you can maybe find a datasheet for it that explains how it works and commmnicates.  Once you know that you can decide if that's something you can do with an Arduino.  Be prepared to learn that Arduino might not be big enough or fast enough to do anything with that particular sensor.

body:
> how can I implement it into a project?

Find its datasheet, understand how it works and code to it.

Just as what you would with any other devices. The challenge here is that you will be hard pressed to find any info about those kind of devices.


body: I have a FT232R that I want to use to flash my ATTiny85 bootloader in the Arduino IDE, can someone help me out on this? I don't want to get a AVR programmer.

title: Trying to flash ATTiny85 bootloader using FT232R in the Arduino IDE

Answers: 1

body:
A bootloader is a program that gets loaded into the bare microcontroller to handle a number of low level tasks. One of those tasks is the ability to load a program over UART (serial).

As such, the bootloader can be loaded into the microcontroller using a AVR programmer. Once this has occurred, you can then easily load in programs with the FT232R.

It is possible to use the bitbang mode on the FT232R to load the bootloader into an Arduino board, hence replacing the AVR programmer. So, it can work but it isn't easy.

As suggested by per1234, there is some instructions on how to do this to an Arduino Diecimila on the Adafruit website: [Programming the Arduino Bootloader][1]
In general the full page has a lot of useful information: [Full page][2]

  [1]: https://learn.adafruit.com/ftdi-friend/programming-the-arduino-bootloader
  [2]: https://learn.adafruit.com/ftdi-friend?view=all


body:
I'm trying to monitor the sensor values (range 0-1000) connected to Arduino UNO's 12th-pin. If the value stays below say 500, then it should SEND SMS. I tested the sensor and GSM shield seperately and both of them are working fine. But my program is not giving the sensor reading in the serial monitor nor sending the SMS. I'm pretty sure it got stuck at sendRequest() part of the code.

    // the setup routine runs once when you press reset:
    #include "Adafruit_FONA.h"

    #define FONA_TX 2
    #define FONA_RX 3
    #define FONA_RST 4

    // this is a large buffer for replies
    //char replybuffer[255];
    char buffer[50];
    char r[15];
    // We default to using software serial. If you want to use hardware serial
    // (because softserial isnt supported) comment out the following three lines
    // and uncomment the HardwareSerial line
    #include <SoftwareSerial.h>
    SoftwareSerial fonaSS = SoftwareSerial(FONA_TX,FONA_RX);
    SoftwareSerial *fonaSerial = &fonaSS;
    SoftwareSerial Sensor_Serial(12,13);

    // Hardware serial is also possible!
    //  HardwareSerial *fonaSerial = &Serial1;

    // Use this for FONA 800 and 808s
    //Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
    // Use this one for FONA 3G
    Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST);

    uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);

    uint8_t type;

    byte readCO[] = {0xFF, 0X01, 0X86, 0X00, 0X00, 0X70};
    byte response[] = {0,0,0,0,0,0};

    //multiplier for value. default is 1.
    int valMultiplier = 1;

    void setup() {
      while (!Serial);

      Serial.begin(9600);
      Sensor_Serial.begin(9600);    //Opens the virtual serial port with a baud of 9600
      Serial.println(F("FONA basic test"));
      Serial.println(F("Initializing....(May take 3 seconds)"));

      fonaSerial->begin(4800);
      if (! fona.begin(*fonaSerial)) {
        Serial.println(F("Couldn't find FONA"));
        while (1);
      }
      type = fona.type();
      Serial.println(F("FONA is OK"));
      Serial.print(F("Found "));
      switch (type) {
        case FONA800L:
          Serial.println(F("FONA 800L")); break;
        case FONA800H:
          Serial.println(F("FONA 800H")); break;
        case FONA808_V1:
          Serial.println(F("FONA 808 (v1)")); break;
        case FONA808_V2:
          Serial.println(F("FONA 808 (v2)")); break;
        case FONA3G_A:
          Serial.println(F("FONA 3G (American)")); break;
        case FONA3G_E:
          Serial.println(F("FONA 3G (European)")); break;
        default:
          Serial.println(F("???")); break;
      }

    }
    void loop()
    {
        sendRequest(readCO);
        float valCO = getValue(response);
        static unsigned long startTime = 0;
        if (valCO < 500)

       dtostrf(valCO, 3, 2, r); // I don't know how to covert the unsigned long variable to string and I know //this part does the float to string conversion
        sprintf(buffer, "%s High  Level", r);
        Serial.print("CO  = ");
        Serial.println(valCO);
        if (millis() - startTime > 1UL*60UL*1000UL) {  // Has it been 1 minute since the value was below 500?

          startTime = millis();
          fona.sendSMS("0XXXXXXX", buffer);
         }
      }

    void sendRequest(byte packet[])
    {
      while(!Sensor_Serial.available())  // If this part works the entire code works I think!!
    //keep sending request until we start to get a response
      {
        //Sensor_Serial.write(readCO,9);
        delay(50);
      }

      int timeout=0;  //set a timeoute counter
      while(Sensor_Serial.available() < 9 ) //Wait to get a 9 byte response
      {
        timeout++;
        if(timeout > 10)    //if it takes to long there was probably an error
          {
            while(Sensor_Serial.available())  //flush whatever we have
              Sensor_Serial.read();

              break;                        //exit and try again
          }
          delay(50);
      }

      for (int i=0; i < 9; i++)
      {
        response[i] = Sensor_Serial.read();
      }
    }

    unsigned long getValue(byte packet[])
    {
        int high = packet[2];                        //high byte for value is 3rd byte in packet in the packet
        int low = packet[3];                         //low byte for value is 4th byte in the packet

        unsigned long val = high*256 + low;                //Combine high byte and low byte with this formula to get value
        return val* valMultiplier;
    }
OUTPUT:
.
.
.
.
FONA is OK
Found FONA 3G (European)
 ---> AT+GSN
 <--- 8XXXXXXXXXXXXXX
Module IMEI: 8XXXXXXXXXXXX

I guess this part of the is waiting for like ever and not returning any response

    while(!Sensor_Serial.available())  //keep sending request until we start to get a response
      {
        Sensor_Serial.write(readCO,9);
        delay(50);
      }
Any help guys?

title: Program NOT responding to loop()- Arduino UNO+GSM + Sensor

Answers: 1

body:
You have multiple software serial ports and are expecting them to work like real ones.

**They don't.**

You can only have one of them "active" at a time (that is, ready to receive data). You need to switch between them with `Sensor_Serial.listen()` and `fonaSerial->listen()`.

In general it is bad to have more than one SoftwareSerial (and personally I think even one is bad) since they are very heavyweight and block all other operations while they are either sending or receiving data (which means your listening one cannot operate at all while your non-listening one happens to be sending).

If you have a requirement for more than one serial port you should really be using a board that has more than one serial port.


body: I thought that I read that using a PC running the Arduino IDE to "upload a sketch" to an esp8266 overwrites the original firmware (with the AT commands), and is actually "flashing the firmware" each time a "sketch" is uploaded. If I have that right, then why does the esp8266 WiFi still visible in available connections? There must be some code instructing the esp8266 to do this, but where is it? My sketch was simply the hello blinky thing and contained no #include statements. Where have I slipped?

title: When uploading a sketch to an esp8266, isn't that the same as "flashing firmware"?

Answers: 1

body:
Uploading a "sketch" is indeed "flashing firmware".

> why does the esp8266 WiFi still visible in available connections?

I'm not sure what you mean by that.


body:
I’am using IRF520 mosfet according to this [schema][1] to shut down Arduino by low level on output to 10K ohms resistor

Schema of my device is[![enter image description here][2]][2]

----------

The issue is that IRF520 took too much place

Is it possible to substitute IRF520 with smaller mosfet?

***Additional info:***

I measured average power consumption – it’s about 22 mA on 12V = 0.264W

IRF520 is for 70W max according to datasheets.

The base schema is

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

  [1]: https://www.zolalab.com.br/eletronica_projetos/auto_shutdown_enus.php
  [2]: https://i.stack.imgur.com/o4lK6.png
  [3]: https://i.stack.imgur.com/1xkrv.jpg

title: Alternative for IRF520 mosfet in Arduino shutdown schema

Answers: 1

body: For what you are trying to do, any transistor, bjt or MOSFET, would work. 2n2222 or 7000 for example. Irf5x0 is actually a poor choice here. It only worked due to the low load being switched.


body:
This is the atmega328p code that is supposed to send a predefined message repeatedly.
<!-- language-all: lang-cpp -->

    #include <avr/io.h>
    #include <util/delay.h>

    #define BAUD 9600
    #define BAUD_PRESCALLER (((F_CPU / (BAUD * 16UL))) - 1)

    void USART_init(void) {
        UBRR0H = (uint8_t) (BAUD_PRESCALLER >> 8);
        UBRR0L = (uint8_t) (BAUD_PRESCALLER);
        UCSR0B = (1 << RXEN0) | (1 << TXEN0);
        UCSR0C = (3 << UCSZ00);
    }

    void USART_send(unsigned char data) {
        while (!(UCSR0A & (1 << UDRE0)));
        UDR0 = data;
    }

    unsigned char USART_receive(void) {
        while (!(UCSR0A & (1 << RXC0)));
        return (unsigned char) UDR0;
    }

    void USART_putstring(char *StringPtr) {
        while (*StringPtr != 0x00) {
            USART_send((unsigned char) *StringPtr);
            StringPtr++;
        }
    }

    char String[] = "Hello world!!";

    int main(void) {
        USART_init();
        while (1) {
            USART_putstring(String);
            _delay_ms(1000);
        }
        return 0;
    }

If I try and listen to my serial port `screen /dev/tty.wchusbserial141120 9600`, only unicode nonsense comes back.

    ���

I am not quite sure what's the issue here.

title: Garbage when listening to serial

Answers: 0


body:
Can I (attempt to) measure a voltage that is higher that the ADCs Vref, without damaging my IC?

I'm trying to measure the battery voltage using a resistive divider, and using the internal 1.1V bandgap voltage. I selected the resistors so the voltage would be around 1V when fully charged.

My project can however also be power by a wall-adapter, which exceeds the batteries voltage, resulting in a voltage higher than 1.1V at the ADC.

In the datasheet the table of ADC Characteristics seems to indicate that the maximum input voltage is Vref. Though I'm not sure if that's the maximum voltage is can convert, or if that's the maximum voltage that's allowed.

Elsewhere in the datasheet it says: `Single ended channels that exceed VREF will result in codes close to 0x3FF`, which seems to indicate it isn't a problem to exceed Vref (as long as it's below Vcc).

The part I'm using is an ATtiny13A, but the relevant sections of the datasheet seem identical to the ATMega328.

title: Can I connect a voltage, higher that the 1.1V bandgap voltage, to an ADC pin

Answers: 1

body:
Yes, you can go above VRef.

> Voltage on **any Pin except RESET**
>
> with respect to Ground ................................-0.5V to VCC+0.5

And as the ADC reference says anything above VREF will give you the maximum value (it will saturate).

So powered from 5V you can apply anything from -0.5V to +5.5V safely. That's basically the supply voltage plus one diode drop for the ESD protection diodes within the pin.

The ADC is just comparing two voltages. The VREF isn't used to power anything.


body: I want to be able to control an analog potentiometer. I'd like to be able to go from the minimum range to the maximum range possibly using an Arduino and a motor/servo. I want to be able to control vintage equipment, so the knobs on the pot must still work. I want to be able to rotate both by hand and by sending  a (MIDI) signal.How would I go about doing this?

title: Controlling an analog potentiometer using an Arduino

Answers: 1

body:
The first problem we have is that replacing the original potentiometer might be wrong thing to do. Analog audio hardware is usually nonlinear, because the volume of the sound is actually a logarithmic function. So the potentiometers might be fine tuned specifically for particular device, and impossible to acquire today since it's vintage.

I suggest a different approach. Connect the knobs to rotary encoders, or cheap linear potentiometers. That way you will receive data about what the user is doing, and what setting does he want to change. They usually are small and you might even fit an extra el-cheapo 28BYJ485V stepper motor to move the knobs to provide feedback. (It can be modified doubling it's torque)

Move all the audio potentiometers inside the case of the device and connect them directly to a stepper motor or a servo to move them only with Arduino.


body:
I'm working with a project in which I need to use an SD card module and an RFID antenna simultaneously. The devices that I'm using are the MFRC522 and the CATALEX SD Card Adapter. Both have SPI Protocol, and they're using the libraries MFRC522.h and SD.h.

This is the pin layout that I'm using:

    /////// For RFID //////////
                 Arduino
                 Mega
      Signal     Pin
      ---------------------
      RST/Reset  5
      SPI SS     53 (CUSTOM)
      SPI MOSI   51
      SPI MISO   50
      SPI SCK    52

    //////// For SD ///////////
                 Arduino
                 Mega
      Signal     Pin
      ----------------------
      SPI SS     49 (CUSTOM)
      SPI MOSI   51
      SPI MISO   50
      SPI SCK    52

As you can see the only line that they are not sharing is the Slave Select (aside from the RST pin of the RC522 module), so I believe that my wiring is correct.
I tried setting in LOW the chip select of the device that I wanted to use and in HIGH the one that I didn't. But this didn't work.

Any help you could provide would be appreciated! Thanks!

title: How can I work with two devices that use the SPI protocol?

Answers: 2

body:
If that SD card adapter looks similar like the picture, I never could get it to work together with another SPI device.

What I used was a data logger shield for Arduino (with SD card slot and proto part, unused in my case), something like this: [SD logger][1]

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

  [1]: https://www.aliexpress.com/item/OOTDTY-New-Data-Logger-Module-Logging-Recorder-Shield-V1-0-for-Arduino-UNO-SD-Card/32818880127.html?spm=2114.search0104.3.1.jfta86&ws_ab_test=searchweb0_0,searchweb201602_4_10152_10065_10151_10068_10209_5400011_5430020_10304_10307_10301_10137_10060_10155_10154_10056_10055_10054_10059_100031_10099_5410011_10103_10102_10052_10053_10142_10107_10050_10051_5380020_10084_10083_5370020_10080_10082_10081_10177_10110_10111_10112_5390011_10113_10114_10312_10313_10314_10315_10078_10079_10210_10073_5420011,searchweb201603_1,ppcSwitch_4&btsid=d28b8a3a-14d3-4af8-940d-0ab2a3a28772&algo_expid=6d5ea032-5f55-4210-af53-da3096a35cc9-0&algo_pvid=6d5ea032-5f55-4210-af53-da3096a35cc9
  [2]: https://i.stack.imgur.com/ILDNR.jpg

body:
I have a few of those in my parts box and I have left a little note with them that says "exlusive SPI" to remind myself. A search brings up [this][1] which seems to confirm it. The OP's solution of powering it on and off with a pin seems pretty smart to me - assuming it doesn't draw too much current from the output pin.

Update: I found [this][2] which suggests that powering the SD card adapter from an output pin is a bad idea. The card could be drawing more than the pins can reliably supply.

  [1]: https://forum.arduino.cc/index.php?topic=407804.0
  [2]: https://arduino.stackexchange.com/questions/19397/why-can-i-power-an-sd-card-reader-from-a-digital-pin


body:
I would like to know the purpose of the LEDs on top of the Arduino WiFi Shield: L9/Link/Error/Data (left in the picture). What do they indicate?

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

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

title: LEDs on Arduino WiFi Shield

Answers: 1

body:
The [web page on the Arduino site](https://store.arduino.cc/arduino-wifi-shield) for the board tells you in plain words what they mean:

> On board indicators The shield contains a number of informational LEDs:
>
> * L9 (yellow) : this is tied to digital pin 9
> * LINK (green) : indicates a connection to a network
> * ERROR (red) : indicates when there is a communication error
> * DATA (blue) : indicates data being transmitted/received


body:
I'm playing around with a Neopixel strip and want to be able to enter the amount of minutes I want an LED to do something rather than in milli seconds. So for example,

    void loop() {

    colorWipe(strip.Color(0, 0, 255), 50);
    delay(sConversion(5));

    colorWipe(strip.Color(0, 0, 0), 50);
    delay(sConversion(5));

In my mind this should then delay the code by 5 minutes instead of doing

    void loop() {
    colorWipe(strip.Color(0, 0, 255), 50);

    delay(300000);

The function I wrote is

    sConversion(int minutes) {
        int milli = minutes * 60000;

        return milli
    };

When I write this same function in JS it returns the correct value, 300000. But when I run it in the Arduino IDE the blue light never changes.

I have this function outside my void loop() and void setup(). Is that the correct place to put it? I have no errors returned.

Full code sample

    void setup() {

    strip.begin();
    strip.show();

    }

    int sConversion(int minutes) {
        int milli = minutes * 60000;

    return milli;
    }

    void loop() {

    colorWipe(strip.Color(0, 0, 255), 50); // Blue
    delay(sConversion(1));

    colorWipe(strip.Color(102, 204, 0), 50); // Green
    delay(300000);
    }

    void colorWipe(uint32_t c, uint8_t wait) {
    for (uint16_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, c);
        strip.show();
        delay(wait);
        };
    };

Is this the reason?

> No other reading of sensors, mathematical calculations, or pin manipulation can go on during the delay function, so in effect, it brings most other activity to a halt.

https://www.arduino.cc/en/Reference/Delay

title: Function for converting milliseconds to minutes?

Answers: 3

body:
Your `sConversion` returns an `int` as argument. You need to declare it as `unsigned long`.

This is what you are lookin for:

    unsigned long conv(int x) {
      return x * 600000L;
    }

body:
 > Function for converting milliseconds to minutes?

1 min has 60 seconds and 1s has 1000 me.

So take the ms and divide it by 60k you will get its equivalent min.

body:
    int sConversion(int minutes) {
        int milli = minutes * 60000;

    return milli;
    }

If minutes is greater than 1, you will overflow the int and not get the right answer.  Use unsigned long here instead.

    unsigned long sConversion(int minutes) {
        unsigned long milli = minutes * 60000ul;

    return milli;
    }


body:
I'm very new to the Arduino platform and micro-controller projects in general, which is why I'm still learning about all the parts needed for circuit creation. There is one particular part that I would need for my current project but I'm having troubles figuring out what exactly this "thing" is ...

Please take a look at this picture: https://i2.wp.com/makezine.com/wp-content/uploads/2015/08/rolljam-hardware.jpg?fit=929,724

I need to know, please, what exactly these dual row female headers are called that are placed right to the Teensy board and are holding the two CC1101 units (so I can find them on Amazon or in other shops).
Obviously, they are spanning the gap on the breadboard but is there something you can buy like this? Or are these common dual row headers that have had their pins bent and put into single row headers?
I can't quite tell. The whole thing looks custom made though (to me it even looks like some hot glue was used, but I might be entirely wrong about that).

^^ And if my assumption is right, what might be the purpose of doing this? From my understanding this would create a full row for the power (instead of having two shorter rows), which the gap on the breadboard is meant to prevent?!

Thank you for suggestions.

title: Can anyone identify these headers?

Answers: 1

body:
From the pic, it looks like a 2x16 female header, PCB mount, with the pins bent outward and soldered to some male header pins.

I think they do this to provide mating sockets for the 2x5 male pins on the CC11001s that can be hooked up to a breadboard.

You could avoid this by prototyping on something like "stripboard' or 'Veroboard' like https://www.amazon.com/Soldering-Prototype-Printed-Circuit-Stripboard/dp/B019Q14GRQ/ and cutting/soldering a few traces where appropriate.

Or you could use a small chunk of stripboard tor protoboard to do the adapting from the 2x5 at 0.1" centers, to 2x5 on 0.1"x0.4" centers.


body:
I have a system with a server (a personal computer with an XBee Dongle plugged in, running a Java program) and some Boe-Bots with XBees attached and Arduino programs. I know how to get the Boe-Bots to send a message to the server. I want the server to obtain the Boe-Bot's XBee's physical address so that it can send a message to that particular Boe-Bot with the Java method
com.digi.xbee.api.XBeeDevice.sendData(RemoteXBeeDevice remoteXBeeDevice, byte[] data)
knowing what argument to put for remoteXBeeDevice.

I can think of two ways this might be possible.

1) There might be a method in the Arduino XBee library to obtain an XBee's physical address. Then the Boe-Bot can get its own address and send it in a message to the server. I have not found such a method.

2) On the server side, there might be a method in the Java XBee library that allows it to automatically determine the physical address of a client that is communicating with the server. I thought that XBeeMessage.getDevice() was such a method, but it returned a RemoteXBeeDevice with an XBee64BitAddress of FFFFFF... which is not the proper address of the Boe-Bot's XBees.

Does anyone know the correct Arduino method for option 1 or the correct Java method for option 2?

Edit: XBee S1

title: How to know physical address of XBee?

Answers: 1

body:
First you can check the signal received from the xbee connected with the server by using coolterm or arduino serial monitor. This is to ensure there are connections between the two xbees.

Then, you will receive some funny characters which is normal, you need to change these characters into hexadecimal form which is more preferable to use coolterm as it has the ability to do so.

Laslty, the characters received will be about 21 characters long. It starts with 7E as a starting character. That is what I received when using XBee S2. These characters then can be translated into other form.

I would suggest a book entitled Wireless Sensor Network by Robert Faludi to understand more.


body:
i recently bought hm-10[![Back view of HM-10 BLE module][1]][1] ble module which works using cc2541 ti SOC but problem is there are many ports the the bluetooth module but the seller has not mentioned which is rx and tx pins so...
I wanted to connnect it with Arduino uno and use AT commands but now i am stuck can anyone in this community help me finding which pin is Tx and Rx and the data sheet of the module is difficult to find on the net .....[![Front view of module][2]][2]

  [1]: https://i.stack.imgur.com/sFuxJ.jpg
  [2]: https://i.stack.imgur.com/u1zCZ.jpg

title: Which is RX and TX pin of the HM-10 module?

Answers: 1

body:
That's not an HM-10 but an EY-08. It's the same chip, but it's been provided in a different footprint (and maybe with different firmware installed).

Pin P03 is TX and pin P02 is RX.

The AT command set, pinouts, and examples for wiring it are detailed [here](http://www.electrodragon.com/w/EY-08) (Thanks to Mikael Patel for finding that link).


body:
For some reason I want to mix a bit of assembly with C++ (not C).
To allow the code to be compilable using the standard Arduino IDE, I don't want to use direct assembly source.
I don't want to use a wrapper C file either.

My problem is as follows:

I have a class with a single instance (implementing some kind of driver) that looks like this:

    class cDriver {
    public:
        char ISR_param;
        // ...
    };

    cDriver Driver;

If I want to access the `ISR_param` of this single instance from within an ISR, I can do something like:

    ISR (TIMER2_COMPA_Vect) {
        do_something_with (Driver.ISR_param);
    }

This works like a charm: the address of `Driver.ISR_param` beign a constant, the compiler simply generates an `lds r24, &Driver.ISR_param` instruction to load the proper byte as a parameter for `do_something_with`.

Now when I try to replicate the same mechanism with inline assembler, things get a lot more complicated.

The address of `Driver.ISR_param` is only known to the C++ compiler as an mangled label, and I can't find a way to pass it to the inline assembler to generate the equivalent `lds r24, <&Driver.ISR_param>`.

# trying to remane the variable

The renaming of variables for assembly like so:

    char global_var asm("my_var");

and an attempt to use it like so:

    asm ("lds r24, my_var\n");

will compile, but produce a linker error (`my_var` is undefined).

Looking at the object symbol table, the only label for `global_var` is a C++-like mangled name.
However hard I tried this renaming trick, I could not bring the compiler to generate a `my_var` label.

# trying to use asm constraints

A constraint like

    asm (lds r24, %0\n" : : "I"(&global_var));

will simply not compile. I scoured the possible parameter types and could not find a way to let the assembler know about this bloody address.

# a terribly awkward workaround

The only way I found to make the compiler generate this dreaded `lds r24,...` instruction is to perform an actual function call.

So you can do something like:

    __attribute__((always_inline)) give_me_my_friggin_variable(char data)
    {
        asm volatile ("cmp  %0,%0\n"::"r"(data));
    }

    ISR (TIMER2_COMPA_Vect, ISR_NAKED) {

        <some prologue to save SREG and all needed registers>

        //...

        give_me_my_friggin_variable(Driver.ISR_param);

        // continue assembly code with r24 properly initialized
    }

That will generate:

        lds r24, <the proper address> // added by the compiler...
        cmp r24,r24                   // ...because of the register constraint here

Well, that sort of works, but at the cost of generating a totally useless instruction.

# so my question is...

Is there a simpler way to let the assembler know about addresses of C++ static variables?

title: Accessing a C++ static variable from gcc inline asm

Answers: 1

body:
Try this:

    asm volatile("lds r24, %0" : : "i" (&Driver.ISR_param));

The `"i"` constraint means you provide an integer constant. It can be
any integer, unlike the uppercase `"I"` constraint which is limited to
6-bit positive integers.

**Addendum**:
The constraints supported by gcc are listed in the gcc documentation,
section [Constraints for `asm` Operands][asm-constraints]:

* The `"i"` constraint is listed in the subsection “Simple Constraints”
  and is described as:

> An immediate integer operand (one with constant value) is allowed.
> This includes symbolic constants whose values will be known only at
> assembly time or later.

* The `"I"` constraint is in the subsection “Machine Constraints” and,
  for the AVR architecture, is defined as

> Constant greater than -1, less than 64.

[asm-constraints]: https://gcc.gnu.org/onlinedocs/gcc/Constraints.html


body:
I am stuck trying to get it not to account for black in RGB.  My first instinct was to use the HSV color spectrum over the RGB rainbow but, the same code will behaves differently in HSV.  If i could get the same effect in HSV I would, and that would account for the black, but I have not found a solution for that or the accounting for black in RGB.  Here is my code:

<!-- language: lang-cpp -->

    #include <FastLED.h>

    #define LED_COUNT     96
    #define LED_OUT       13
    #define BUTTON_IN     10
    #define ANALOG_INPUT  A9
    #define EXTRA_PIN_A    7
    #define EXTRA_PIN_B   11

    struct CRGB leds[LED_COUNT];

    void setup() {
      Serial.begin(57600);
      LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
      LEDS.show();
    }

    void colorLoop() {

      static int Col1;
      static int Col2;
      static int Col3;

      static int C1;
      static int C2;
      static int C3;

      if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

        // select a random number from 1 to 2 for the array
        C1 = random(1, 3);
        C2 = random(1, 3);
        C3 = random(1, 3);
      }

      if (((C1 == 1) && (Col1 != 0))) {
        Col1 = (Col1 - 10);
      }
      if (((C2 == 1) && (Col2 != 0))) {
        Col2 = (Col2 - 10);
      }
      if (((C3 == 1) && (Col3 != 0))) {
        Col3 = (Col3 - 10);
      }

      if (((C1 == 2) && (Col1 != 250))) {
        Col1 = (Col1 + 10);
      }
      if (((C2 == 2) && (Col2 != 250))) {
        Col2 = (Col2 + 10);
      }
      if (((C3 == 2) && (Col3 != 250))) {
        Col3 = (Col3 + 10);
      }

      for (uint8_t i = 0; i < LED_COUNT; i++) {
        leds[i] = CRGB(Col1, Col2, Col3);
      }
      delay(100);
      LEDS.show();
    }

    void loop() {
      colorLoop();
    }

title: LEDs Randomly smooth transitioning, accounting for black or how-to switch using HSV

Answers: 3

body:
For it not to be _black_, at least one color (R,G,B) have to be on.

Before assigning the color values to the LED, maybe you can try using the _constrain_ function to keep the values within a range. For example,

    ...

    Col1 = constrain(Col1, 50, 150);  //If anything falls below 50, set it to the minimum value (50)
    Col2 = constrain(Col2, 50, 150);
    Col3 = constrain(Col3, 50, 150);

    for (uint8_t i = 0; i < LED_COUNT; i++) {
       leds[i] = CRGB(Col1, Col2, Col3);
    }

    ....
Sure enough! adding the *constrain* function to one of the static integers fixed the RGB from going to black. Now simply set 50 as the min value in the rest of the code:

    void colorLoop() {
        //Set the minimum value to 50
        static int Col1 = constrain(Col1, 50, 255);
        static int Col2;
        static int Col3;

        static int C1;
        static int C2;
        static int C3;

        if ((((Col1 == 50) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

            // select a random number from 1 to 2 for the C1,C2,C3 array
            C1 = random(1, 3);
            C2 = random(1, 3);
            C3 = random(1, 3);
        }

        if (((C1 == 1) && (Col1 != 50))) {
            Col1 = (Col1 - 10);
        }
        if (((C2 == 1) && (Col2 != 0))) {
            Col2 = (Col2 - 10);
        }
        if (((C3 == 1) && (Col3 != 0))) {
            Col3 = (Col3 - 10);
        }
        if (((C1 == 2) && (Col1 != 250))) {
            Col1 = (Col1 + 10);
        }
        if (((C2 == 2) && (Col2 != 250))) {
            Col2 = (Col2 + 10);
        }
        if (((C3 == 2) && (Col3 != 250))) {
            Col3 = (Col3 + 10);
        }

        for (uint8_t i = 0; i < LED_COUNT; i++) {
            leds[i] = CRGB(Col1, Col2, Col3);
        }
        delay(100);
        LEDS.show();
    }

body:
Black will basically be when all the colours have reduced to 0. That can only happen when all three of C1, C2 and C3 are 1. So you basically need to ensure that never happens.

And that is simple enough to arrange, with a "try again" construct:

    if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

        // select a random number from 1 to 2 for the C1,C2,C3 array
        do {
            C1 = random(1, 3);
            C2 = random(1, 3);
            C3 = random(1, 3);
        } while ((C1 == 1) && (C2 == 1) && (C3 == 1));
    }

Pick three numbers. If they are all 1 then you are destined towards black. So go back and pick three new random numbers. Keep trying until you get at least one result that isn't 1.

body:
I found this approach works:

    if (((Col1 <= 50) && ((Col2 <= 50) && (Col3 <= 50)))) {  //avoid black
       C1 = 2;
       C2 = 2;
       C3 = 2;
    }


body:
I'm still learning how to use Arduino and electrical components, but I will try my best to understand any answers!

So I just bought an e-paper display off a website, not from the manufacturer itself (http://www.good-display.com/products_detail/productId=305.html). The product is a 1.54 inch E-paper display 200x200 partial update GDEP015OC1.

[![e-paper display][1]][1]

I was a bit puzzled by how to connect the display to the Arduino Uno. Turns out that to connect the display to a board, it needs a breakout board (is this the correct term?). I could buy it online from the manufacturer, however, it will take me at least a month and the shipping cost is too high.

I was wondering if it is possible for me to make my own breakout board? Is there any 'general' breakout board for an e-paper display, or does it have any special from the manufacturer? If it is possible, how difficult would it be for a beginner who has almost no knowledge on circuit building/electrical components?

The aim is just to display an image onto the e-ink display.

Thanks!

edit: I bought the mentioned display because of the size. I was afraid of not knowing how to connect the mention display (which is where I am now), so I bought this e-ink display also: https://www.smart-prototyping.com/E-ink-E-paper-Display-module-3.3V-2.04-inch-177x72.html I was thinking to take the 60mmx30mm display off the board and try connecting the 30mmx30mm display to the 'breakout board' if I am unable to build my own board. Both seemed to have the same pin number (need to confirm later).

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

title: Connecting E-paper display (GD) to Arduino?

Answers: 1

body:
E-ink displays require high voltages to operate them. They are electrostatic devices and the pixels need charging up to a high voltage (high compared to what an Arduino runs at) to attract the pigment powder (basically the same as laser printer toner) to create an image.

While it is possible to make your own board it's not something that is simple and straight forward. Designing boost converters requires a certain base level of knowledge and expertise to get it right. Not something I would recommend a beginner attempting.

Even though a display may have the same pin number as another it doesn't follow that the pins are in the same order on the connector. There is no standard and each display from different manufacturers (and even different displays from the same manufacturer) will have a different pin-out. You will need to compare the datasheets for the two displays to see if the pin-out is the same and if it isn't you would have to somehow map from one to the other on the driver board.

The simplest option is to just order the correct driver board for that display.

(Note: in this context it is called a *driver board* not a *breakout board*. A breakout board is typically a passive circuit board that converts from one hard-to-use connector or footprint to a simpler, say 0.1", header. A driver board contains active electronics, in this case a boost converter, to drive the device it is connected to.)


body:
I am an absolute beginner and wanted to build a simple home automation system using [DTMF][1] module using this [guide][2]. My problem is out of 12 pins most of them are getting used in DTMF module(5) and the relay module(4). So how do i add an LCD display to it?

  [1]: https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling
  [2]: https://roboindia.com/tutorials/dtmf-home-automation-with-arduino

title: Adding an LCD to Uno but not enough pins left

Answers: 5

body:
You have chosen a mighty task as your first project. I suggest that you run through as many of the example programs as possible before undertaking your project.

Firstly, I would recommend a [matrix keypad][1] instead of the DTMF keypad as it is much easier to use with an Arduino. This will also allow you to use a multiplexer which would use fewer pins.

[![Keypad and matrix circuit][2]][2]

[I2C][3] allows you to communicate to the LCD with only 2 pins. [Here is such a I2C LCD (with buttons)][4] sold by Adafruit.

[![Adafruit I2C LCD + buttons][5]][5]

As well as the [tutorial over at Adafruit][6], there is a [tutorial on such a topic over at ArduinoInfo][7].

Alternatively, you could upgrade to a [Arduino Mega][8] which has 54 IO pins as apposed to 14 on the Arduino Uno.

  [1]: http://playground.arduino.cc/Code/Keypad#Description
  [2]: https://i.stack.imgur.com/Khhh8.jpg
  [3]: https://learn.sparkfun.com/tutorials/i2c
  [4]: https://www.adafruit.com/product/714
  [5]: https://i.stack.imgur.com/xMA1W.jpg
  [6]: https://learn.adafruit.com/rgb-lcd-shield
  [7]: https://arduino-info.wikispaces.com/LCD-Blue-I2C
  [8]: https://store.arduino.cc/usa/arduino-mega-2560-rev3

body:
I suggest you first try every component separately (or if you are new to Arduino, try first simpler components like LEDs, switches etc),

As told by others the following components are easier to use:

- Use a matrix keypad, see for example [keypad][1]. To reduce the number of pins you can use a multiplexer, such as 74HC165. 74HC165 are very cheap, although they need some additional programming and are slower than using direct pins (although for a keypad you will not notice).

- Use a display like 1602 or 2004. See example at [1602 Display][3]. Make sure you order one that has an I2C adapter attached to it (or solder it yourself if you feel comfortable).

- After you tested all components separately (make different sketches and save them in case you need them later), you can combine them.

  [1]: http://playground.arduino.cc/Main/KeypadTutorial
  [2]: https://www.arduino.cc/en/Tutorial/ShiftOut
  [3]: https://www.arduino.cc/en/Tutorial/HelloWorld

body:
If some of the pins aren't used at the same time there are ways to reuse them.

Otherwise use a serial shifter or o.o expanders to drive the LCD. 2 to 3 pins max. Even 1 pin is possible if you tolerate lower speed of update.

body:
You are using 8 GPIO pins for your existing modules. That leaves 12 left for an LCD (assuming you aren't using the serial port).

An LCD can work from as few as 6 pins (4 data, E and RS) - WR can be tied LOW and RESET can be tied HIGH, and the remaining 4 data pins left floating (or tied low).

That still leaves you 6 pins to do other things. Or 4 if you (advisedly) steer clear of using pins 0/1 for anything.

body:
You can use arduino mega rather than uno or nano .... Or can use **I2C adapter to control your LCD display, I2C adapter only needs two pins to communicate with arduino and is easy to use ......
**


body:
I have a Pololu DRV8835 motor controller. I managed to properly solder and connect it and it actually works, however I've been wondering about the purpose of the extra pin slots - especially the ones without pins headers soldered to them on the right side of the picture below, but also the ones marked A and B (I assume these ones are an alternative way to connect to motors, though). I wasn't able to find anything about them, so I assumed that it may be obvious to someone who is not a complete beginner (like me). What, if anything, could I use them for if I soldered pin headers there?
[![Pololu DRV8835 mounted on an Arduino][1]][1]

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

title: Purpose of extra pin slots on Pololu DRV8835

Answers: 1

body:
A and B are the same as the A and B screw terminals.

The pins on the right, if you use your eyes and follow the traces, are the same as the pins that plug into the Arduino. I guess they are intended to be used to isolate the existing pin assignments (cut tracks on the underside between adjacent holes with a knife) and solder wires to other pins so you aren't limited to just using the pins they have assigned.


body:
I know similar question has already been discussed here but I could not get clear answer.
Here is the thing: I have one master device - Mega2560, and multiple (about 9 but could be expandedin future) I2C perfiferals - displays, that can have one of two possible I2C IDs - limitation by the manufacturer. As I can't connect and talk to them from a single I2C bus I chose to attach each two of them to a Mini-Pro's I2C pins and connect the 5 Mini-Pros to the master. The question is am I going to the right direction, and which connection would do the trick? I2C is obviously out of question, so the remaining are UART and SPI. UART would require some external hardware to cope with multiple outputs from the slaves, SPI would require additional pins from the master for chip select signal.
Data rates are not high - min 10-20 kbps.
I think the SPI offers better solution, but I'm no expert, what do you think?

Cheers!

Stefan

title: Solution for simple multi-Arduino communication network (or alternative?)

Answers: 3

body:
SPI afaik is not good over bigger distances (> 1 meter). If you need many CS signals you always can use a multiplexer (like 74HC595N). I am not sure if it is 'normal' to have many SPI devices connected to one Arduino though.

Other solutions: I2C, but I don't have much experience with them. I heard about I2C expanders (MCP23017) that maybe are useful.

Also RF might be a possibility, also depending on the distance and most important speed (and latency).

In case for the Mega, it has 4 UARTs so that could maybe be used to spread the load.

body:
I would suggest using 485 communication though it will increase the hardware but you will be able to add upto 32 devices and also have greater communication distance.
You can use MAX485 IC or you can directly use [TTL to 485 Module][1]

  [1]: http://www.dnatechindia.com/RS485-TTL-Module.html

body:
Thanks all for your answers.

I did some more research with the new info you provided and found my perfect solution: TCA9548A. That's a 1-to-8 port i2c multiplexer that will allow the master MEGA2560 to control up to 8 independent i2c buses, where I can connect my displays. The chip is dirt cheap here - 2 euro only, and it is available in the store.

Thanks again guys!


body:
I'm trying to transfer data from ESP8266(NodeMCU ESP12E) to my laptop. I'm coding ESP using Arduino IDE. I am able to receive correct packets (each containing 400 bytes) on a visual basic console program. However, to see whether the transmission is continuous or not, I have toggled an output pin whenever UDP.endpacket() returns 1. I observed waveforms on DSO. I found that UDP.endpacket() does NOT return 1 many times and the there is no transmission from ESP for a significant amount of time (milliseconds). Refer attached waveforms.

Why does UDP.endpacket() return 0 for such long time? Why is UDP transmission getting interrupted? How can I solve this? Please feel free to ask for more details if necessary.

Code :

    #include <ESP8266WiFi.h>
    #include <WiFiUdp.h>

    const char* ssid = "Connectify-me33";
    const char* password = "donfour276";

    WiFiUDP Udp;
    unsigned int localUdpPort = 65000;

    unsigned int dest_port = 11000;

    unsigned char clientBuf[400];
    int clientBuf_len=0;

    #define test_pin 5

    int return_udp_fcn = 0;

    void setup()
    {

      WiFi.begin(ssid, password);
      delay(5000);

      Udp.begin(localUdpPort);

      pinMode(test_pin, OUTPUT);
      digitalWrite(test_pin, HIGH);

      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(LED_BUILTIN, LOW);
      delay(1000);
      digitalWrite(LED_BUILTIN, HIGH);
      delay(1000);
      digitalWrite(LED_BUILTIN, LOW);
      delay(1000);
      digitalWrite(LED_BUILTIN, HIGH);
      delay(1000);

    }

    void loop()
    {
            digitalWrite(test_pin, HIGH);

            //filling up buffer
            for(clientBuf_len = 0; clientBuf_len<=399; clientBuf_len++)
            {
                clientBuf[clientBuf_len] = 0x7E;
            }

            //UDP transmit
            Udp.beginPacket("172.22.0.1", dest_port);
            Udp.write((const uint8_t *)clientBuf, 400);
            return_udp_fcn = 0;
            return_udp_fcn = Udp.endPacket();
            if(return_udp_fcn){
              digitalWrite(test_pin, LOW);
            }
            delayMicroseconds(100);

    }

[![test-pin waveform : interruptions can be observed][1]][1]

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

title: ESP8266 - UDP send interruptions

Answers: 1

body:
I think you need a `delay(1);` after your call to `write()`.

There is/was a bug where the underlying buffer files up and can't get time to clear.  It looks like it will require a change to the ESP8266 firmware from the manufacturers before it will get fixed properly.

See what you think:

https://github.com/esp8266/Arduino/issues/1696

https://github.com/esp8266/Arduino/issues/2285


body:
I am working on air quality measuring project. it should be able to record gps and air quality data into a SD card and then when wifi is available it should send it to a server. Please help me decide the required hardware for this.
Can i use ESP8266 module to send this data

title: arduino send logged data over wifi

Answers: 1

body:
You need:

- SD card + reader
- GPS module
- Air sensor
- WIFI ESP 8266 should be ok
- Arduino Uno or Mega, depending on if everything fits and calculations to be performed

Start with finding each component, read examples how to use them, than combine them.

Looks like a big project to start with if you are new to Arduino.


body:
I want to control the contrast and backlight of an HD44780 LCD display with two PWM signals. I would like to use `PB1` and `PB2` (`Pin 9` and `Pin 10`) for this.
As far as my research goes, `timer1` is responsible for the two pins.
`OCR1A` and `OCR1B` are responsible for the pulse length.

With the code below I get a frequency of 7.823 kHz and a duty cycle of 88%. But it works only on `PB1`. `PB2` is still constant `0V`. I am using the AtmelStudio, therefore I don't have access to functions like `pinMode(10, Output)`

How can I have different duty cycles on pin 9 and 10?

    #define F_CPU 16000000UL
    #include <avr/io.h>

    int main(void)
    {
     DDRB |= (1 << DDB1) | (1 << DDB2);
        OCR1A = 900;
        OCR1B = 400;
        TCCR1A |= (1 << COM1A1);
     TCCR1A |= (1 << WGM11) | (1 << WGM10);
        TCCR1B = (TCCR1B & 0b11111000) | (1 << CS10);

    }

title: Pin 9 and 10 with different duty cycles

Answers: 1

body:
After trying  a lot of things i got it working.
And even the contrast is working directly on the pwm signal.

 #define F_CPU 16000000UL
    #include <avr/io.h>
    void main(void){
     DDRB = 0x06;
  OCR1A = 200; //Duty cycle for PB1 ~80%
  OCR1B = 100; //Duty cycle for PB2 ~40%
  TCCR1A = 0; //Set TCCR1A to zero. We will configure it manually
  TCCR1A |= (1 << COM1A1) | (0 << COM1A0) | ( 0 << COM1B0) | (1 << COM1B1);
  TCCR1A |= (0 << WGM12) | (0 << WGM11) | (1 << WGM10);
  TCCR1B = 0; //Set TCCR1B to zero. We will configure it manually
  TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
  while(1){

  }
    }


body:
Can anyone see any errors in my code that would affect the opening command? Upon first power up the open command (remoteA) works fine.

After that the opening command does what its supposed to except it only momentarily fires "digitalWrite (power, LOW)" command.  It should be set LOW for the same amount of time as "digitalWrite (openGate, LOW)", but it doesnt.

Strange thing is, the close command code is almost identical and it always works as it should, no problems.

Any suggestions? (hopefully the code pastes in here ok, its acting weird)

    /*
     *  Swing Gate Opener with 2Ch remote, gate lock, motor, buzzer, amp monitor
    and two independent limit switches
     *
     *  By Darren Clarke
     *
     */
    int current = A0;  // monitor motor current
    int buzzer = 3;  // operation buzzer
    int power = 5;  // 24v power on/off
    int remoteOpen = 6;  // remote button A to digital pin 6
    int remoteClose = 7;  // remote button B to digital pin 7
    int openGate = 8;  // open gate to motor on digital pin 8
    int closeGate = 9;  // close gate to motor on digital pin 9
    int gateLock = 10;  // gate lock connected to digital pin 10

    // variables
    int openRelay = 0;  // variable to store the motor direction
    int closeRelay = 0;  // variable for previous motor direction
    int remoteA = 0;  // variable for remote A condition
    int remoteB = 0;  // variable for remote B condition
    int lock = 0;  // varialbe for gate lock
    int mA = 0;  // variable for motor current
    unsigned long previousMillisA = 0;
    unsigned long previousMillisB = 0;
    unsigned long currentMillisA = 0;
    unsigned long currentMillisB = 0;

    void setup() {
     // put your setup code here, to run once:
     pinMode(buzzer, OUTPUT);   // sets the digital pin 4 as output
     pinMode(power, OUTPUT);   // sets the digital pin 5 as output
     pinMode(remoteOpen, INPUT);   // sets the digital pin 6 as input
     pinMode(remoteClose, INPUT);   // sets the digital pin 7 as input
     pinMode(openGate, OUTPUT);   // sets the digital pin 8 as output
     pinMode(closeGate, OUTPUT);   // sets the digital pin 9 as output
     pinMode(gateLock, OUTPUT);   // sets the digital pin 10 as output
     digitalWrite(closeGate, HIGH);   // sets relay to open
     digitalWrite(openGate, HIGH);   // sets relay to open
     digitalWrite(power, HIGH);   // sets relay to open
     digitalWrite(gateLock, HIGH);   // sets relay to open
     analogWrite(buzzer, 0);   // sets buzzer off
     Serial.begin(9600);
    }

    void loop() {
     // put your main code here, to run repeatedly:
     remoteA = digitalRead(remoteOpen);   // read remote A input
     remoteB = digitalRead(remoteClose);   // read remote B input
     openRelay = digitalRead(openGate);   // read state of openGate
     closeRelay = digitalRead(closeGate);   // read state of closeGate
     lock = digitalRead(gateLock);   // read state of gate lock
     mA = analogRead(current);   // read value of motor current
     currentMillisA = millis();
     currentMillisB = millis();
     Serial.print("aIn ");
     Serial.print(remoteA);
     Serial.print(", bIn ");
     Serial.print(remoteB);
     Serial.print(", Open ");
     Serial.print(openRelay);
     Serial.print(", Close ");
     Serial.print(closeRelay);
     Serial.print(", Lock ");
     Serial.print(lock);
     Serial.print(", mA ");
     Serial.print(mA);
     Serial.print(", cur ");
     Serial.print(currentMillisA);
     Serial.print(", prev ");
     Serial.print(previousMillisA);
     Serial.println(" ");

    // to open the gate
     if ((remoteA == HIGH) && (remoteB == LOW)) {
      delay(500);   // time for gate direction reversal
      digitalWrite(power, HIGH);   // stops previous movement
      digitalWrite(closeGate, HIGH);   // Stop gate open command
      analogWrite(buzzer, 100);   // starts buzzer
      digitalWrite(gateLock, LOW);   // energize lock open (unlock state)
      delay(500);   // time for lock to open
      digitalWrite(openGate, LOW);   // actuate gate open
      digitalWrite(power, LOW);   //  supplies 24v power
      previousMillisA = millis();  // set time references
      currentMillisA = millis();  // set time references
     }

    // to stop open command
     if ((closeRelay == HIGH) && (currentMillisA - previousMillisA) >= 6000) {
      digitalWrite(gateLock, HIGH);   // denergize lock (locked state)
      digitalWrite(openGate, HIGH);   // stop open relay to motor after open
      digitalWrite(power, HIGH);   // remove 24v power
      analogWrite(buzzer, 0);
     }

    // to close the gate
     if ((remoteB == HIGH) && (remoteA == LOW)) {
      delay(500);   // time for gate direction reversal
      digitalWrite(power, HIGH);   // stops previous movement
      digitalWrite(gateLock, HIGH);   // de-energize lock on quick reverse
      digitalWrite(openGate, HIGH);   // Stop gate close command
      analogWrite(buzzer, 100);   // starts buzzer
      digitalWrite(closeGate, LOW);   // actuate gate close
      digitalWrite(power, LOW);   // supplies 24v power
      previousMillisB = millis();  // set time references
      currentMillisB = millis();  // set time references
     }

    // to stop close command
     if ((openRelay == HIGH) && (currentMillisB - previousMillisB) >= 6000) {
      digitalWrite(closeGate, HIGH);   // stop close relay to motor
      digitalWrite(power, HIGH);   // remove 24v power
      analogWrite(buzzer, 0);
     }

     delay(100);
    }

title: Gate opener code help - should be working

Answers: 1

body:
Ok, i figured it out.

Thanks all for your help.

It only happens on the A channel because its first in the series of the code.  The turn off command after the timer isnt specific enough.  The if conditions are met on the B channel so it keeps turning the power off immediately.

I just need be more specific in my if command or make another tweek.

Thanks guys,  your suggestions caused me to do much more digging and code adjustments.

Its working like a peach now.

Thanks.


body:
Why such horrible Arduino's Mega PWM doesn't work??

Below is my code.

I try to set Fast PWM 8-bit to dim and light up a LED connected to OCR1A Pin. I try to do it in C language, completelly without Arduino's lbraries and it doesn't work at all.

I'm working with documentation and the code seems me to be correct. Almost the same code worked on ATmega8 and ATmega16 (obviously, with special setting for those special ATmegas) but this one doesn't.

The comments in this code point out, that I tried to use few other flags to  check if it work with some of another settings.

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <util/delay.h>

    //Anode of LED connected to OCR1A (digital pin 11)
    #define LED (1<<PB5)

    int main()
    {
      DDRB |= (1 << LED);

      //FAST PWM 8-bit, set OCR1A at the Bottom
      TCCR1A = (1 << COM1A1) | (1 << WGM10);    // | (1<<WGM11) | (1<<COM1A0)
      //Prescaler :1024
      TCCR1B = (1 << CS12) | (1 << WGM12);     //| (1<<WGM13); //Presc :1024  (1<<CS10) |
      //Enable to interrupt Compare Match A
      TIMSK1 = (1 << OCIE1A);

      uint8_t i;

      sei();

      while (1)
      {
        for (i = 0; i < 255; i++)
        {
          OCR1A = i;
          // _delay_ms(5);
        }

        for (i = 255; i > 0; i--)
        {
          OCR1A = i;
          //_delay_ms(5);
        }
      }
    }
   }

title: Arduino Mega PWM doesn't work in C Code

Answers: 3

body:
I'm not sure this is right:

    #define LED (1<<PB5)

Since later on you use:

    DDRB |= (1<<LED);

That would expand out to:

    DDRB |= (1<<(1<<PB5));

That would equate to:

    DDRB |= (1<<(1<<5));

Take it a step further:

    DDRB |= (1 << 32)

Shifting 1 to the left 32 times on an 8 bit register results in:

    DDRB |= 0;

Which of course does nothing.

I can't comment on the rest of the code, other than to say "without delays in your loops you won't get much sense out of it".

body:
Majenko showed you one of your mistakes.

Then you wrote:

    //Enable to interrupt Compare Match A
    TIMSK1 = (1<<OCIE1A);

And this is your other mistake. You should not enable an interrupt
unless you have defined an ISR for it. Otherwise your program will
restart every time the interrupt fires.

body:
My advice. Stay simple. Try to get your code to output a duty cycle first. From there try to get your code to vary the duty cycle.

Once you do that the issues with your code will be clear.


body:
I want to receive about 5kb of data in Base64 format. The following code does not work. Only a few characters are received, sometimes CPU crashes.

    String content = "";
    char character;

    while (Serial.available()) {
           character = Serial.read();
           content.concat(character);
    }

I do not care about ram usage since on ESP32 there is plenty.
How can I get all the data? Example input: https://pastebin.com/wYG5AhHK

title: How to receive and process a long string sent over serial?

Answers: 1

body:
I had to read until delimiter :D

    String receive() {
      String content = "";
      content = Serial.readStringUntil('\r');
      return content;
     }
Now it is fine. I will also change String to large char array.


body:
### Hardware

1. Arduino Nano

2. XBee Pro S1 (802.15.4) Modules

3. [Adafruit BNO055 Absolute Orientation Sensor](https://learn.adafruit.com/adafruit-bno055-absolute-orientation-sensor/overview)

### Purpose

I want to send the Euler angles and Linear Acceleration angles to the a central __XBee Coordinator__ (can be connected to a Computer or a Single Board Computer) every __100 ms__

Since the BNO055 has __SDA__ and __SCL__ pins for I2C how will the performance of the Nano matter when sensor data is acquired from the BNO sensor and send to XBee module which will be connected to the __Hardware Serial UART__ Port?

An interesting observation was that if one:

> Shorts the PS1 pin to 3.3V for the BNO055, the __SDA__ and __SCL__ will function as __RX__ and __TX__ pins for UART.
> [source](https://learn.adafruit.com/bno055-absolute-orientation-sensor-with-raspberry-pi-and-beaglebone-black/hardware#raspberry-pi)

In terms of interfacing, I can think of the __Xbee__ now connected to the __Hardware Serial Port__ and perhaps the BNO sensor will can be connected to the Nano via `SoftwareSerial` port. But will that serve any better purpose in terms of performance and data acquisition i.e. using two _Asynchronous_ Serial Ports compared to one?

title: is using two UARTs wiser compared to I2C and UART with Arduino + Xbee + BNO055 Sensor

Answers: 1

body:
All software serial solutions are much less efficient than `HardwareSerial` (i.e., `Serial`).  `SoftwareSerial` is particularly bad, because it disables interrupts for long periods of time.  95% of the MCU time can be spent twiddling its thumbs, waiting for each bit to come in.

Using the I2C interface for the BNO055 means that the Arduino hardware will independently and concurrently handle each *byte* of data from the BNO055 and from `Serial` (i.e., the XBee).  Your sketch can continue to do other things while each byte arrives.  This is most efficient.

Software serial port libraries handle each *bit* of data, sometimes to the exclusion of all other activity.


body:
I made a clap light switch to control my room lights and ground LEDs, and it works perfectly but when ever I have both the LEDs and the lights on it kinda stops working.
I use two claps for the lights and three for the LEDs.
Does anyone know what could be wrong? here is my code.

    /* DEFINE PINS */
    const int buzzer = 2;
    const int micPin = 0;
    const int relayLED = 9;
    const int relayLights = 8;

    const int sampleWindow = 50;
    const int N = 50;

    unsigned int sample;

    boolean lights = false; //lighs on or off
    boolean leds = false; //leds on or off

    double soundArray[N]; //array to check claps

    int i = 0;
    int clapsCount = 0;

    void setup() {
      pinMode(relayLED, OUTPUT);
      pinMode(relayLights, OUTPUT);
      digitalWrite(relayLED, HIGH);
      digitalWrite(relayLights, HIGH);
    }

    void loop() {
      /* gets 50 constant sound sample and resets */
      if (i<N) {
        soundArray[i] = getVolts();
        i++;
      } else {
        i = 0;
      }
      if (i == N-1) {
        clapsCount = clapCount(soundArray);
      }

      /* if 2 claps detected do this */
      if (clapsCount == 2) {
        if (lights == false) {
          turnOnLights();
          lights = true;
        } else {
          turnOffLights();
          lights = false;
        }
        playSound();
        clapsCount = 0;
      }

      /* if 3 claps detected do this */
      if (clapsCount == 3) {
        if (leds == false) {
          turnOnLeds();
          leds = true;
        } else {
          turnOffLeds();
          leds = false;
        }
        playSound();
        clapsCount = 0;
      }
    }

    int clapCount(double soundArray[]) {
      int claps = 0;
      for (int j=0; j<N; j++) {
        if (soundArray[j] > 3.0 && soundArray[j] < 3.5) {
          claps++;
        }
      }
      return claps;
    }

    void turnOnLights() {
      digitalWrite(relayLights, LOW);
    }

    void turnOffLights() {
      digitalWrite(relayLights, HIGH);
    }

    void turnOnLeds() {
      digitalWrite(relayLED, LOW);
    }

    void turnOffLeds() {
      digitalWrite(relayLED, HIGH);
    }

    /* gets mic volts */
    double getVolts() {
      unsigned long startMillis= millis();  // Start of sample window
      unsigned int peakToPeak = 0;   // peak-to-peak level
      unsigned int signalMax = 0;
      unsigned int signalMin = 1024;
      // collect data for 50 mS
      while (millis() - startMillis < sampleWindow)
      {
        sample = analogRead(micPin);
        if (sample < 1024) {
           if (sample > signalMax) {
              signalMax = sample;  // save just the max levels
           }
           else if (sample < signalMin) {
              signalMin = sample;  // save just the min levels
           }
        }
      }
      peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
      double volts = (peakToPeak * 5.0) / 1024;  // convert to volts
      return volts;
    }

    void playSound() {
      tone(buzzer, 1000);
      delay(100);
      tone(buzzer, 500);
      delay(100);
      noTone(buzzer);
    }

**Edit:**

When I do both two claps and three claps, both lights turn on and no matter how many times I clap none of them turn back off.

**Edit 2:**

Components I am using are, a simple buzzer, and microphone called MAX4466 and a 5v relay with two outputs.

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

  [1]: https://i.stack.imgur.com/98xutm.jpg
  [2]: https://i.stack.imgur.com/bjKPTm.jpg

title: Weird arduino bug, using microphone and relay

Answers: 1

body:
I've looked through your code and can't see anything obvious that is causing the problem, so I have refactored it a bit in the hope that the problem becomes more obvious.

    /* DEFINE PINS */
    const int PinBuzzer = 2;
    const int PinMic = 0;
    const int PinRelayLED = 9;
    const int PinRelayLights = 8;

    const int sampleWindow = 50;
    const int MaxSamples = 50;

    // Simple enumeration to clarify which state is on and off.
    enum EOnOff { Off, On };
    EOnOff lights = Off; //lights on or off
    EOnOff leds = Off; //leds on or off

    double soundArray[MaxSamples]; //array to check claps

    void setup()
    {
     pinMode(PinRelayLED, OUTPUT);
     pinMode(PinRelayLights, OUTPUT);
     digitalWrite(PinRelayLED, ConvertOnOff(leds));
     digitalWrite(PinRelayLights, ConvertOnOff(lights));
    }

    void loop()
    {
     for (int sample = 0; sample < MaxSamples; ++sample)
     { // Get the samples
      soundArray[sample] = getVolts();
     }
     switch (clapCount())
     { // Analyse the samples
     case 2:
      lights = ChangeRelay(lights, PinRelayLights);
      playSound();
      break;
     case 3:
      leds = ChangeRelay(leds, PinRelayLEDs);
      playSound();
            break;
     }
    }

    /// Count the number of 'claps' in the sample data
    int clapCount(/*clap array is global*/)
    {
     int claps = 0;
     for (int sample = 0; sample < MaxSample; ++sample)
     {
      if (soundArray[sample] > 3.0 && soundArray[sample] < 3.5) /* Why 3.5?? */
      {
       ++claps;
      }
     }
     return claps;
    }

    /// Convert an EOnOff value to a HIGH or LOW value.
    // OFF = HIGH
    int ConvertOnOff(const EOnOff& state)
    {
     return state == Off ? HIGH : LOW;
    }

    /// Change a relay to the given state.
    /// Return the new state.
    EOnOff ControlRelay(const EOnOff& state, const int& relayPin)
    {
     EOnOff result = state == On ? Off : On;
     digitalWrite(relayPin, ConvertOnOff (result));
     return result;
    }

    /* gets mic volts */
    double getVolts()
    {
     const unsigned long startMillis = millis();  // Start of sample window
     unsigned int signalMax = 0;
     unsigned int signalMin = 1024;

     unsigned int sample;
     // collect data for 50 mS
     while (millis() - startMillis < sampleWindow)
     {
      sample = analogRead(PinMic);
      if (sample < 1024)     // ?? Should this be 1024 or signalMin?
      {
       if (sample > signalMax)
       {
        signalMax = sample;  // save just the max levels
       }
       else if (sample < signalMin)
       {
        signalMin = sample;  // save just the min levels
       }
      }
     }
     const unsigned int peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
     const double volts = (peakToPeak * 5.0) / 1024.0;  // convert to volts
     return volts;
    }

    void playSound()
    {
     tone(buzzer, 1000);
     delay(100);
     tone(buzzer, 500);
     delay(100);
     noTone(buzzer);
    }

What I have tried to do is to reduce the number of lines of code.  If there are less lines then there should be less bugs :)

You used a bool to record the on off state, I changed that to an enumeration because that adds a bit of clarity, and when working with mains voltages I like things being clear.

I changed your while loop into a for loop, I think it looks cleaner.  This was also the reason I changed your if statements into a switch statement.

The guts of the if statements have been removed and placed in a function `ChangeRelay()`, it returns the new state of leds or lights.  I could have gone with a reference to make `state` an in out parameter, but decided a return was simpler.

`ClapCount()` and `GetVolts()` are relatively unchanged apart from a bit of const'ing of variables to make things easier to read.  Also you might have noticed I, j and N have all been removed, because single letter variable names are my nemesis, who knows what `q` means and why `r` and `t` are being added to it to make `z`?

ControlRelay lets you route all you relay switching through one function, if there was a copy and paste bug in your code (which I don't think there was) then they will either all work or not work now.

There is a big difference between "my" code and yours, you won't be able to switch both on at the same time because the switch statement won't let you.  So in a way you problem is solved.  If you really wanted to you could add:

    case 5:
        lights = ChangeRelay(lights, PinRelayLights);
        leds = ChangeRelay(leds, PinRelayLEDs);
        playSound();
        break;


body:
I am trying to burn MegaCore bootloaders to it, I have setup my custom PCB  with Atmega2560V-8AU and 8Mhz Crystal + Load Caps all assembled on using PCBA process.
I am trying to burn MegaCore bootlaoders to it, I am using Arduino UNO as ISP Programmer. My connections are all correct, It shows different Device Signatures (see below) whenever I hit Burn Bootloaders....

> 0x0000ff
0x00003f
0x0000ff
0x00ff00
0x001000
0xff0000
0xfc0000
0x00fe00

This is complete output with different Device Signatures

> Arduino: 1.8.3 (Windows 10), Board: "ATmega2560, Arduino MEGA pinout,
> 2.7v, Disabled (default), 8 MHz external"
>
> C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude
> -CC:\Users\mudas\OneDrive\Documents\Arduino\hardware\MegaCore-avr-100-pin\avr/avrdude.conf
> -v -patmega2560 -cstk500v1 -PCOM4 -b19200 -e -Ulock:w:0x3f:m -Uefuse:w:0xfd:m -Uhfuse:w:0xd6:m -Ulfuse:w:0xf7:m
>
> avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
>          Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
>          Copyright (c) 2007-2014 Joerg Wunsch
>
>          System wide configuration file is "C:\Users\mudas\OneDrive\Documents\Arduino\hardware\MegaCore-avr-100-pin\avr/avrdude.conf"
>
>          Using Port                    : COM4
>          Using Programmer              : stk500v1
>          Overriding Baud Rate          : 19200
>          AVR Part                      : ATmega2560
>          Chip Erase delay              : 9000 us
>          PAGEL                         : PD7
>          BS2                           : PA0
>          RESET disposition             : dedicated
>          RETRY pulse                   : SCK
>          serial program mode           : yes
>          parallel program mode         : yes
>          Timeout                       : 200
>          StabDelay                     : 100
>          CmdexeDelay                   : 25
>          SyncLoops                     : 32
>          ByteDelay                     : 0
>          PollIndex                     : 3
>          PollValue                     : 0x53
>          Memory Detail                 :
>
>                                   Block Poll               Page                       Polled
>            Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
>            ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
>            eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
>            flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
>            lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
>            signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
>
>          Programmer Type : STK500
>          Description     : Atmel STK500 Version 1.x firmware
>          Hardware Version: 2
>          Firmware Version: 1.18
>          Topcard         : Unknown
>          Vtarget         : 0.0 V
>          Varef           : 0.0 V
>          Oscillator      : Off
>          SCK period      : 0.1 us
>
> avrdude: AVR device initialized and ready to accept instructions
>
> Error while burning bootloader. Reading |
> ################################################## | 100% 0.02s
>
> avrdude: Device signature = 0x00fe00 avrdude: Expected signature for
> ATmega2560 is 1E 98 01
>          Double check chip, or use -F to override this check.
>
> avrdude done.  Thank you.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
What should be the problem.??? How to solve this.?

title: Atmega2560V, trying to burn bootloaders of MegaCore

Answers: 1

body:
I removed 8Mhz from board and followed this instructions [LINK][1], and burnt bootloaders using -F override check, then i returned 8Mhz oscillator to Atmega2560V and see device signature and it's automatically appears 0x1e9801 rather than 0x1e9803

  [1]: http://www.avrfreaks.net/forum/tutsoft-recovering-locked-out-avr


body:
I am trying to control [this OWI Robotic Arm][1] using the Arduino's digital outputs (I am using pins 12 & 13).

If I wire up the wires to ground and 5V it goes one way, if I switch the wires, it goes the other way. However when I have the pins wired up to the digital pins, it does not work, but the on-board LED does blink.

The code:

    int a = 12;
    int b = 13;

    void setup() {
      // put your setup code here, to run once:
      pinMode(a, OUTPUT);
      pinMode(b, OUTPUT);
      pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop() {
      //up
      digitalWrite(a, LOW);
      digitalWrite(b, HIGH);
      digitalWrite(LED_BUILTIN, HIGH);
      delay(500);
      //down
      digitalWrite(b, LOW);
      digitalWrite(a, HIGH);
      digitalWrite(LED_BUILTIN, LOW);
      delay(500);
    }

  [1]: https://www.amazon.com/OWI-OWI-535-Robotic-Arm-Edge/dp/B0017OFRCY/ref=sr_1_3/144-0256150-0926858?ie=UTF8&qid=1502310116&sr=8-3&keywords=robotic arm kit

title: Arduino digitalWrite not working

Answers: 1

body:
The problem you are seeing here is that the Arduino can provide *nowhere* near as much current through I/O pins as it can power. Quoting from [the Arduino website][1]:

> DC Current per I/O Pin: 40 mA

This means that each pin can power maybe a couple of LEDs, and that's it. Additionally, motors provide "[back-EMF][2]": When opening (cutting power) an inductive load (e.g. a motor), the current wants to keep going. This will damage whatever just opened unless protection is used. So, I wouldn't be surprised if you damaged your Arduino by attempting to drive a motor with it.

So, what *can* you do? Use an H-Bridge. This circuit will allow you to easily control a motor & its direction. Many circuits can be found online, but an easy solution is a cheap L298N module, which can be as cheap as $3 a piece. This will safely & easily control the arm. Connecting your Arduino with the following circuit & using your existing sketch will make it work.

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

<!-- End schematic -->

  [1]: https://www.arduino.cc/en/Reference/Board
  [2]: https://en.wikipedia.org/wiki/Counter-electromotive_force


body:
I want to write a driver that can use either timer0 or timer2, based on a choice made at compile time.

So I want all references to timer registers to be abstracted, e.g. OCRA for OCR0A/OCR2A, etc.

I could do it with plain macros, like so:

    #define _CONCAT3(a,b,c)   a##b##c
    #define CONCAT3(a,b)   _CONCAT3(a,b,c)

    // set timer number globally
    #define MY_TIMER 2

    // define an alias for each control register
    #define OCRA CONCAT3(OCR, MY_TIMER, A)

**but** for some reason I don't want to use macros there.

So I came up with this scheme:

    typedef volatile uint8_t& tRegister;

    constexpr volatile uint8_t& timer_register (volatile uint8_t& a, volatile uint8_t& b)
    { return MY_TIMER==0 ? a : b; }

    tRegister OCRA = timer_register (OCR0A, OCR2A);

It works pretty well for all its awkwardness, *but* when I try to use this definition in an inline assembly directive, I get strange results:

    asm volatile("lds r24, %0" : : "i"(&OCRA));

will get an `error: impossible constraint in 'asm'`

Now this:

    asm volatile("lds r24, %0" : : "i"(&timer_register (OCR0A , OCR2A )));

will compile (and produce `lds r24, 0x00B3` as it should).

By definition a reference to a static variable is a constant address, known at compile time, so I can't see why it can't be used in this context.

So my questions are:

- what is going on there?
- how to alias these registers (without macros) to please the inline assembler?

title: using references to SFRs in gcc inline assembler

Answers: 1

body:
You could use pointers instead of references. With pointers, you have
the separate notions of “constant pointer” and “pointer to constant”. A
reference is a kind of pointer coated with syntactic sugar. However,
whereas you can have a “constant reference” (equivalent to _pointer to
constant_), I do not know how to declare a “reference with constant
address” (which would be the equivalent of a _constant pointer_). And
this is your issue: the `"i"` constraint in the `asm` statement requires
a constant.

Here is my take with pointers:

 typedef volatile uint8_t * tRegister;

 constexpr tRegister timer_register(tRegister a, tRegister b)
 { return MY_TIMER==0 ? a : b; }

 // The `const' below is essential.
 const tRegister OCRA = timer_register(&OCR0A, &OCR2A);

 asm volatile("lds r24, %0" : : "i"(OCRA));

Of course, you then have to change all your `OCRA = ...;` statements
with `*OCRA = ...;`, which is awkward. But note that the avr-libc
defines the SFRs with macros equivalent to

    #define OCR0A (*address_of_OCR0A)

If you want this convenience, you may have to resort to using similar
macros yourself.


body:
I have a problem i need to solve so i will simply it as much as possible.

Basically there is a system with a micro-controller where it reads 2 sensors. These 2 sensors are of variable resistance type, aka their measuring value is output as different resistance. For example one is a pressure sensor where at 0psi the sensor has a value of 20ohms to ground, and for 100psi it has a value of 120ohms. The sensor is connected between ground and a fixed value resistor so the output acts like a voltage divider.

The micro-controller seems to be multiplexing by switching pull up between each 2 sensors (probably because using a single ADC), at random times (as the microcontroller performs other functions) but approx. every 80ms for each sensor, and about 40ms between each sensor. So at 0ms it reads one sensor, at 40ms the other sensor, and at 80ms back at the first sensor and so on. I have no idea why they haven't used a fixed pull-up, but the pull-up is only done when the controller wants to read the sensor for only about 120us.

I wanted to read these sensors to input to an ECU, without affecting the original device. Thus the easiest solution i could think off as the pull-up isn't always high to perform a read, was to add another microcontroller (in my case a Digispark based on the ATtiny85 running at 16.5MHZ). Alternatively i could open up the device and modify it to use a fixed pull-up but let's say i want to avoid this route. The digispark essentially reads both sensor outputs and when it sees a voltage above ground it outputs it to the ECU. I have since then updated the program to check the ADC values it reads so that it is between the nominal range of the sensor. And while this works there are times where the ADC will read a wrong value and output it to the ECU which looks as random spikes and dips in the data.

Look at my following code:

      const int oil_in = 0; //P5
      const int temp_in = 1; //P2
      const int oil_out = 1; //P1
      const int temp_out = 4; //P4
      int oil_value = 0;
      int oil_value_good = 0;
      int temp_value = 0;
      int temp_value_good = 0;

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(oil_out, OUTPUT);
      pinMode(temp_out, OUTPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      oil_value = analogRead(oil_in);
      if (oil_value > 106 && oil_value < 466)
      {
        oil_value_good=oil_value;
        analogWrite (oil_out, oil_value_good/4);
      }

        temp_value = analogRead(temp_in);
      if (temp_value > 113 && temp_value < 920)
     {
        temp_value_good=temp_value;
        analogWrite (temp_out, temp_value_good/4);
      }
    }

Each ADC pin has a range of acceptable values. These correspond to the MIN AND MAX nominal values for each sensor. However there are times where the ADC will read at the wrong time and it will output either a MIN or a MAX value depending on the condition. I can replicate this on the breadboard by having the input to the ADC reading a nominal value, and by shorting it to either ground or VCC (5V) i can sometimes trick the ADC to read a MIN or MAX value. And since the next measurement will be done after some time, the output will produce these spikes. Since there is no sync between the readings these error data can be sometimes be outputed for 1-1.5s.

I've tried thinking hard about this problem, but i am not sure for a certain solution that will eliminate this problem. ADC interrupts, changing ADC pre-scaler, filtering of data, problem the reading window is really small (100-120us).

Also nominal ADC input values for each sensors are between 0.56V-2.33V for one sensor, and 0.6V-4.68V for the other sensor. Not sure if the interrupt can even be activated at such low voltage.

How do you think i should proceed?

Kind regards

title: Attiny85 - Method to discard glitched ADC values?

Answers: 1

body:
> I have no idea why they haven't used a fixed pull-up, but the pull-up
> is only done when the controller wants to read the sensor for only
> about 120us.

If you want to get a good resolution in the resistance measurement, the
resistance of your pull-up should be in the same range as the resistance
of your sensor. If your sensors have low resistance, this means the
voltage divider will draw significant current. In order to save energy,
it makes sense to power the voltage divider only while you are doing the
measurement.

> the reading window is really small (100-120us).

That's short indeed. If you `analogRead()` a single channel in a tight
loop, you will get one reading every 108.6 µs (128×14 CPU
cycles ÷ 16.5 MHz), and you have a small risk of missing the
window. If you are reading two channels, then you have about 50% risk of
missing the window.

Here is what I would do:

1. Set the ADC prescaler to 64 instead of 128. This way you will get one
   reading roughly every 54 µs, and at least one sample (but more
   often two) during the reading window.

2. Read a _single channel_ in a tight loop, until you get a value above
   your minimum. Then take one more reading and use the largest of the
   two as your “good” value.

3. Switch to the other channel and go back to step 2.

This assumes that outside the reading window your ADC input reads close
to zero, as it is grounded through the sensor, with no pull-up. You then
have, on each channel, a train of positive pulses, and you want to
measure the height of those pulses. There is a small risk of you
sampling the rising edge of a pulse, which could give a wrong value
which is nevertheless above your minimum. If this happens, then the next
sample will be near the center of the pulse. That's why I recommend
taking one extra sample and using the largest of the two.


body:
I'm transmitting serial data from a sensor on my Arduino simultaneously to my laptop via USB and to a terminal app on my phone via a genuine HM-10 BLE module (onboard a Linksprite BLE Shield).

At 9600 baud, the BLE module was transmitting all of my data to the phone's terminal app without issue. I just figured out how to increase the HM-10 module's baud rate to 115200 (for reference, by sending it an AT+BAUD4 command at 9600 baud from the Arduino IDE console via USB, and then uploading a new sketch to the Arduino with both the USB serial and BLE serial baud rates set to 115200). The data is being received via USB serial flawlessly, but the data received by the terminal app on my phone via BLE appears to be missing chunks of data - and I have to try to connect to it 30+ times to get it to properly connect.

Is 115200 baud too fast to transmit data via BLE? Is there any way to make sure all of the data is properly sent via BLE without slowing the program down too much? 9600 baud is too slow for my application, unfortunately.

I should add that I am using an Arduino M0 pro and the BLE is connected via hardware serial (Serial1) and not SoftwareSerial as would need to be done on the Uno, if that makes a difference.

title: Bluetooth Low Energy dropping data at 115200 baud?

Answers: 1

body:
Well, I did some tests and was not able to reliably receive data at over 9600 baud, even with hardware flow control activated via the AT+FLOW1 command. And even then, if either the BLE module or the phone was moving, data was consistentlydropped.

I ended up implementing an SD data logger instead.


body:
I just bought an Arduino Uno (SMD version) from [W11Stop][1] and want to know whether there is any other difference between Arduino UNO DIP and Arduino UNO SMD besides knowing that the SMD version doesn't have a DIP chip which can be replaced?

I am just a beginner so please help me if I am wrong!

  [1]: http://www.w11stop.com/

title: Differences between Arduino Uno SMD and Uno DIP

Answers: 3

body:
As far as I know there is no real difference, at least not directly related to the SMD.

There are many clones which sometimes have slightly different behavior or protection.

But for the SMD the only disadvantage is it cannot (easily) be replaced.

I have one original one (with DIP) and several clones and so far I did not found any difference, except for having mini USB instead of normal USB.

body:
Actually, there are no different on the functionality. But you may can't go through some features, because the ATmega can be remove it manually without any special tools. One of the useful case as [ArduinoISP][1] for burning bootloader to another ATmega328p AVR.

For personal suggestion, you just needed one piece of PDIP/DIP version UNO, others boards you can consider the lower cost, such as [Nano][2], [Pro Mini][3](Without [USB-to-TTL][4]), UNO(SMD).

For the USB-to-TTL, there are many options in the market, watch this [video][5] to explain what are they different.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP
  [2]: https://store.arduino.cc/usa/arduino-nano
  [3]: https://store.arduino.cc/usa/arduino-pro-mini
  [4]: https://www.adafruit.com/product/954
  [5]: https://www.youtube.com/watch?v=Vawhrr4COjI

body:
There's no actual difference, but just the "look". Neither version of it should bother you at anything, but there are 2 things, worth mentioning.

1. The IC can fall out of DIP socket: I've been told a few times this already, but never had experienced such behaviour or been at occasion, where that happened.
So here's a **disadvantage** for DIP cases.

2. DIP has also possibility of changing waaaaaaaaaay easier the microprocessor in case of failure. You simply grab it off (even might with a help of a screwdriver) and you're ready to put in a new one. So this is an **advantage nr. 1**.
I also like to use an Arduino in projects, but not the whole board. I just take the IC (atmega328) and use 2 ceramic caps with 16MHz quartz and I've got my own arduino on other PCB - in this case, you can use Arduino UNO board as a programmer. This is how to avoid installing FTDI or CH340 chip on other boards.
**Advantage nr. 2.**


body:
I am trying to connect to esp8266 using Arduino UNO. There are various things on the internet having mixed information and hence I am seeking some clarity.

I followed these instructions, but could not get to connect to ESP8266 using AT command. http://cordobo.com/2300-flash-esp8266-01-with-arduino-uno/

I have following questions:

- Can I connect ESP8266 directly to Tx/Rx without voltage divider or level shifter? I also suspect that the voltage divider connections are wrong. As per my understanding, the Tx from Arduino should be divided, and the divider output should be connected to ESP8266.
- When I connected the shield as described, the shield gets hot. Is there any way to conclude if the shield is damaged or not?
- When I connect the device using voltage divider the blue LED on the shield also lights up. Without divider, it does not light up. What is the significance of the blue LED?

**Hardware**

ESP8266-01 pinout

[![Esp8266-01 pinout][1]][1]

Circuit using voltage divider

[![Flashing with Voltage Divider][2]][2]

Circuit without voltage divider

[![Flashing without Voltage Divider][3]][3]

  [1]: https://i.stack.imgur.com/75ZAH.png
  [2]: https://i.stack.imgur.com/qudID.png
  [3]: https://i.stack.imgur.com/KhjDp.png

title: Connecting esp8266 using Arduino

Answers: 3

body:
Some ESP boards are 5v tolerant on the digital pins, some aren't. So it depends on what board you have, I don't think the one in the tutorial is.

If you are using serial to communicate the a resistor divider will not work.  You need a proper level shifter, which you should be able to get for less than a $1.  Remember you will probably need to down shift the Tx from the Arduino and Up Shift the RX to the Arduino.

body:
There are a number of issues with the tutorial you've listed there.

Firstly, a voltage divider is very highly recommended as the ESP8266 cannot handle more than 3.3V, however, the connections for the voltage divider in the tutorial you linked to are the wrong way round (as you suspected).

Secondly, you cannot power the ESP8266 directly from the Arduino, as the power requirements are higher than the Arduino's on board 3.3V regulator. A separate power supply or regulator is recommended. This might be cause of it getting hot (the onboard regulator maybe - but I can't be sure as there is not enough information from your initial post as to exactly what is getting hot).

There are 2 LED's on the ESP8266 shield (the one used in the tutorial you've linked to) one is power and the blue one is wifi communication.

The other potential issue with the tutorial you've linked to is that they have used Arduino pins 0 and 1 to connect to the ESP8266 - while this will work, the problem is that the Arduino uses pins 0 and 1 to communicate over USB with a computer, which means that in in that configuration you cannot use Serial monitor to send/receive data.

body:
I'm working with ESP-12S which use ESP8266 recently.

My main goal is to use UART-WIFI passthrough mode, so I only need **VCC, RX, TX, GND**.

These are the steps I take:

1. Use USB to TTL converter to link WIFI module to PC for WIFI configuration. (two USB converter were used for power issue)

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

2. On PC I used *minicom* to open the USB serial. Use AT commands(espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf) to config WIFI module:

    AT+RESTORE    // restores the factory default settings

    AT+GMR     // checks version information

    AT+RST     // restarts the module

    AT+CWMODE_DEF=1   // set station mode

    AT+CWJAP_DEF="APname","password" // connect to AP

    AT+CWDHCP_DEF=1,1  // set station mode with DHCP

    AT+CWAUTOCONN=1   // auto connect

    AT+CIFSR    // show local IP

    AT+PING="10.0.1.1"  // ping network gate

    AT+CIPSTART="TCP","10.0.1.116",2048 // setup TCP to server

    AT+CIPMODE=1   // set UART-WIFI passthrough mode

    AT+CIPSEND    // enter UART-WIFI passthrough mode

    AT+SAVETRANSLINK=1,"10.0.1.116",2048,"TCP" // save configuration in WIFI module

3. After configuration, hook WIFI module to Arduino (actully I'm using stm32, but it's the same) UART pins. When power on, the WIFI module will automatically connet to AP and setup TCP link to server and enter UART-WIFI passthrough mode.

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

4. If you want to exit UART-WIFI passthrough mode, send '+++' on UART end, without '\r\n' and '+++' must be sent continuously (type '+++' in minicom won't work).

as for your questions,

1. Voltage divider is used, but pay attention to RXD TXD link problem. (RXD to TXD, TXD to RXD)

2. My WIFI module also gets hot, but working properly.

3. I don't know the blue LED's function, but I did remember reading about it some where, maybe in the documentation.

  [1]: https://i.stack.imgur.com/rOroV.jpg
  [3]: https://i.stack.imgur.com/x7ZnY.jpg


body:
I want to make a sketch which behaves differently, i.e.:

    pinMode(pin1, OUTPUT);
    digitalWrite(pin1, HIGH);

    pinMode(pin2, OUTPUT);
    digitalWrite(pin2, LOW);

    pinMode(pin3, INPUT);
    // And a user decides to short pin3 with pin1 or pin2

    if (digitalRead(pin3) == HIGH) {
      // behavior 1
    } else {
      // behavior 2
    }

But, I wonder whether shorting two pins with/without a resistor safe or not. If it is dangerous, what is an alternative way to do such a thing?

title: Is it safe to short two pins together for conditioning a sketch?

Answers: 1

body:
Firstly, why would you?

All you are doing is connecting the input pin 3 to either VCC or GND, since that is what setting a GPIO to HIGH or LOW gives you - why would you waste two GPIO pins for that purpose?

"shorting" an input pin with VCC or GND is what you do with a button or switch anyway. The resistor in that case is used to hold the pin in the opposite direction when the button isn't being pressed. The same effect can be created using a two-way switch connecting the pin to either VCC or GND with no resistor required.

So yes, you can "short" the input pin with an output pin safely - as long as that input pin never becomes an output pin at any time (hint: never use pin 13 on an Uno for this - it becomes an output to flash the LED during the bootloader over which you have no control. The same goes for the TX pin.)


body:
For my application I need to simulate the sunlight including the rising and setting of the sun.

I have a program that will light up some LEDs slowly over a period of time but I need to know what to type in the (delay on) to keep the lights on for 7 hours?

Will it work if I just replace `delay(1000)` with `delay(25200000UL)` ?
I don't want to run anything else at the same time and don't want to use or understand `millis()`.
Thanks for any help.

title: how to set the delay on for 7 hours?

Answers: 5

body:
delay(1000) is a delay in ms.
So for a 7 hour delay you need 7 hours * 60 minutes * 60 seconds * 1000 = 52,200,000

Adding UL is good, to show it's long and unsigned.

Also it fits in an unsigned long which has a max value of 2^32-1 = 4,294,967,295.

If you really want to test it you can wait 7 hours, or use a smaller number (like dividing by 60 * 60, thus 7,000 which should be 7 seconds, or make it 70.000 and check it is 70 seconds.

If you would want to make it explicitly how 52,200,000 is calculated or want to make your program more flexible you can always create some defines (or constants):

    static const uint32_t DELAY_1_S      = 1000UL;
    static const uint32_t DELAY_1_MINUTE = DELAY_1S * 60UL;
    static const uint32_t DELAY_1_HOUR   = DELAY_1MINUTE * 60UL;

than you can use

    delay(7UL * DELAY_1_HOUR); // Delay 7 hours

body:
Yes, absolutely, it should work. But your code will be easier to read if
you use some constants, like:

    const unsigned long SECOND = 1000;
    const unsigned long HOUR = 3600*SECOND;

    delay(7*HOUR);

body:
Yes you can write `delay(25200000UL)` and it will delay for 7 hours.

**How it works**
`delay(x)` will delay for x number of milliseconds.
1 second = 1000 milliseconds
1 minute = 60 seconds
1 hour = 60 minutes
7 hours = 1000 * 60 * 60 * 7 =  25,200,000

This number is quite large but is well within the scope of an unsigned long: 32 bits = (2^32)-1 = 4,294,967,295. Doing the sums, this will last for 49 days and 17 hours.

**Delaying for >49 days**
If for some reason you needed to go longer than 49 days, you can do so by placing the delay inside a `for` loop.

    const unsigned long ONE_DAY = 24UL*3600*1000;
    const unsigned int numOfDays = 51;
    int i;
    int j;

    for( i=0; i<numOfDays; i++ )
    {
        delay(ONE_DAY);
    }

body:
> For my application I need to simulate the sunlight including the rising and setting of the sun.

if you have to simulate that long of a delay, you are doing something seriously wrong.

but if you do want to go down that path, something like this may work

    #define delay_1hr()  delay(1000ul * 60 * 60)  //delay a hour

    //delay a day
    void delay_hr(uint8_t hr) {
      while (hr--) delay_1hr();
    }

body:
It's an old one but I give an answer.
I think someone needs help like you.

I trying to make a fish meal machine with the Arduino Uno.

In the first.
I counted seconds over a minute.
It works well.
But when I try over an hour it does not work.

After all.
I got to know another way to count a long time

In the second.
I used the SimpleTimer.h.
The link is here.
[Arduino SimpleTimer][1]

It's an easy way to makes a circular moving but it has the same problem.
SimpleTime can't make a count over time.
I think it's 30 seconds.

Now I referenced StackExchange Arduino.
Here is my code.

    #include <SimpleTimer.h>
    #include <Servo.h>

    #define FIVE_SEC 5000UL
    #define ONE_MIN 60000UL
    #define FIVE_MIN 300000UL
    #define TEN_MIN 3000000UL
    #define ONE_HR 3600000UL
    #define EIGHT_HRS 28800000UL
    #define TWELVE_HRS 43200000UL

    SimpleTimer timer;
    Servo servo;
    int servoPin  = 9;
    int servoReadyAngle = 180;
    int servoMoveAngle = 170;
    int servoMoveCnt = 0;
    int servoJobCycle = 35000;

    unsigned long startTime;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      servo.attach(servoPin);

      startTime = millis();
    }

    void loop() {

      if(millis()- startTime > TEN_MIN) {
        startTime = millis();
        giveAFishMeal();
      } else {
        Serial.print("ping ");
        Serial.println(millis());
      }

    }

    void giveAFishMeal() {

      int servoAngle;
      if(servoReadyAngle > servoMoveAngle) {
        servoAngle = servoReadyAngle - servoMoveAngle;
      } else {
        servoAngle = servoReadyAngle + servoMoveAngle;
      }

        Serial.println("I give a meal to your fish");

        delay(500);
        servo.write(servoReadyAngle);
        delay(500);
        servo.write(servoAngle);
        delay(500);

    }

  [1]: https://playground.arduino.cc/Code/SimpleTimer/


body:
I am using WeMos D1 Mini Pro to control multiple relays. I found out that during start up the relay connected to pin D3 and D8 would switch between on and off a couple times in a very short interval. I found out that the two pins are related to boot loader configuration.

Question is: Is there any way to prevent the relay from "blinking"? Is there a way to disable the relay output until boot loader finish it's stuff? Because this behavior only occur once every boot up.

title: How to use ESP8266 Pin D3 / GPIO 0 and D8 / GPIO 15 properly

Answers: 1

body:
A [74HC244][1] can be used to buffer up to 8 outputs and isolate them at will from the ESP8266. It can also be used for inputs as well if you connect gates the other way around. One additional IO line is required to control it.

  [1]: http://www.ti.com/lit/ds/symlink/sn74hc244.pdf