body:
The IR Transmitter and Receiver module has both receiver and transmitter in same board. I tried Arduino IR Remote library example to decode Remote signal using below connection, but its not working.

 - IR MODULE:   ARDUINO
 - Ground   ->  Ground
 - 5V       ->  5V
 - RXD      ->  PIN 11
 - TXD      ->  PIN 10

The board also has 3 pin connector (Gnd, 5v, S). How to connect pins to Arduino to receive/decode and send IR signals? (Can't able to find any tutorial for this type of board)

[![IR Transmitter and Receiver Front][1]][1]
[![IR Transmitter and Receiver Back][2]][2]

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

**Example Code:**

    #include <IRremote.h>
    int RECV_PIN = 11;
    IRrecv irrecv(RECV_PIN);
    decode_results results;
    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    void loop() {
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        irrecv.resume(); // Receive the next value
      }
      delay(100);
    }

title: How to connect IR Transmitter and Receiver Module?

Answers: 4

body:
The device in the question is commonly sold on aliexpress.com and the likes of ebay.com.  As you might guess there is little in the way of documentation.  Without documentation we can only speculate.  As such, I expect that the module handles all the modulation and demodulation.  It is likely all you need to do is use the [Arduino serial library][1] and connect the TX and RX to the Arduino's RX and TX pins.  However, if you would like to preserve the function of these pins for use with the Arduino Uno's USB port, you can use the [Arduino software serial library][2] which will "emulate" a serial port an an unused (alternate) set of pins.

([This][3] is an example of a similar well documented device with access to the schematic and source code.  Armed with this type of knowledge you can turn this device into what ever you want.  In other words, you probably don't even need an Arduino.  You can just program this device and be done with your project.)

  [1]: https://www.arduino.cc/en/Reference/Serial
  [2]: https://www.arduino.cc/en/Reference/SoftwareSerial
  [3]: http://dangerousprototypes.com/docs/USB_IR_Toy_v2

body: I think you need to switch RX and TX in your code. Looking at the video that @nick-gammon reffered to. TX on audrion is RX on device.

body: For that module you dont need library for easy example for sample for send HIGH and LOW status but. it doesnt work for control IR protocol. for that you need the basic conection Just (data-gnd-Positive)   in that example data is for pin = 11

body:
it use UART protocol so your code is wrong.

[Here link with code][1]

  [1]: https://forum.arduino.cc/index.php?topic=359707.0


body:
I was playing around with an Adafruit Flora and a strip of NeoPixel LEDs.  After uploading the sketch to the Flora (via Arduino IDE), the LED strip lights for about 1 second and then dims to a dull orange color for all the lights.  When this orange color appears, it seems to indicate that the Flora has crashed.  If I unplug the Flora from power and plug it back in, the LEDs light again for about 1 second and then it crashes again.

The time between boot and crash is short enough that I can't upload a new sketch.

So how would I go about rescuing the Flora?
Is there a couple pins I can jumper to put it into bootloader mode?  Or some other way of resetting the Flora so as to remove the offending code?

title: Made a Adafruit Flora unusable

Answers: 1

body:
> 42 pixels in the strand all set to bright white.

This exceeds the power supply capability of either a USB port or the Arduino's regulator.

Likely the circuit starts out working, then once the LEDs are all on drawing high power either a protective device such as a polyfuse / PTC fuse activates trips or the supply simply sags under load.  At this point the circuit either shuts down or starts misoperating, the ATmega may go into brownout protection mode, etc.

Disconnect power to your LEDs and you will probably find that the Flora is fine.

You will need to use a suitable higher current power supply if you want to light more than a few pixels of this type at any given time.


body:
I'm trying to figure out my power requirements for a strand of [Adafruit DotStar][1] LEDs - APA102 Cool White, not the RGB. I'm not sure how to interpret the [datasheet][2].

In the middle of the product spec table on page 1, under Power Consumption, it says `0.2W (MAX: 1W)`.  Which would mean at 5V, MAX would be 0.2A, or 200mA.

Then on page 3 in the electrical characteristics table under the symbol/Parameter "LOL/Sink Current Voltage" it says `typ. 24.5mA; max. 26.5mA`.

I plan on having the strand on full brightness most of the time.

So which is it?  200mA? or 26.5mA?

  [1]: https://www.adafruit.com/products/2432
  [2]: https://cdn-shop.adafruit.com/product-files/2343/APA102C.pdf

title: Reading the DotStar datasheet - power requirements

Answers: 2

body:
[![datasheet spec][1]][1]

You have correctly worked out:

    I(A) = P(W) / V(V)

    I = 0.2 / 5
    I = 0.04A

    MAX:
    I = 1 / 5
    I = 0.2A

From that it seems it will use between 40 - 200mA depending on brightness.

Sink current refers to the current required to drive the led's digital input from your MCU's digital output.

[![Sinking Output][2]][2]

[More information on current sinking][3]

  [1]: https://i.stack.imgur.com/lsbDW.png
  [2]: https://startingelectronics.org/articles/current-sourcing-sinking/current-source-sink.png
  [3]: https://startingelectronics.org/articles/current-sourcing-sinking/ "Sinking Output"

body:
I expect you will have to run an experiment and measure how much current each unit draws at full brightness.

The APA102C spec sheet seems to mix together data about the whole unit (controller chip plus three LEDs) and the controller chip itself.  The “LOL/Sink Current Voltage (RGB)” line that shows “min. 22.5, typ. 24.5, and max. 26.5 mA” appears to apply to the controller, and probably to single outputs on that controller, which anyway would give a 3X multiplier.  (The Cool White strips have three white LED chips per unit, instead of 1 each R, G, B.)

Note, the [Adafruit DotStar LED Strip - APA102 Cool White](https://www.adafruit.com/products/2432) webpage suggests using their 5V 4A power supply to drive “a half meter or meter” and their 5V 10A supply to drive  “a couple meters”, which at 30 units per meter works out at 2/3 to 5/6 W of power supply capacity per unit.


body:
I have a project that requires  data to be sent online from a moving bus. I am using ESP8266F modules to send the data.

I am wondering what Arduino modules to buy that will act as an access point with wifi and will connect to the internet through GSM.

In this configuration, the ESP8266 will connect to the access point and will upload the data online.

I want to connect a DF robot "SIM808 GPS/GPRS/GSM Shield For Arduino" to an Arduino Yun and use them as a wifi access point to connect to the internet through GSM connection.

The ESP8266 (5 of them) will connect to the Arduino Yun and will then send variables to the internet through the internet connection provided by the GSM.

title: Using Arduino GSM with WiFi

Answers: 1

body: ESP is a full stack WiFi module. If you are intended to collect some data from several ESPs you can configure one more as an access point and collect those data from other ESPs as stations. At access pint you can make a small web server as well. To send aggregated data through GSM then you can use a GSM module wire-connected to this ESP. To avoid RF interference while GSM sends data, you should use different power sources and shielded twisted pair for connection. It may happan, that you will need to place GSM module at some distance from ESP access point to avoid overload of the receiver. Even better to use external antennae outside the bus for GSM and shield it inside the bus to minimise the interference. I do not see how Arduino can help here.


body:
I just bought an ERC12864-655 LCD screen.

On the [datasheet][2] it says that I need to connect the vlcd pin to GND.

However in [this][3] (page 8) datasheet it says that vlcd is the main power supply. As far as I know ground is no power supply. That doesn't make sense to me.

So what should I do with this pin?

  [2]: http://www.buydisplay.com/download/interfacing/ERC12864-655_Interfacing.pdf
  [3]: http://www.buydisplay.com/download/manual/ERC12864-655_Series_Datasheet.pdf

title: VLcd pin to ground?

Answers: 1

body:
It appears that the LCD is powered/switched by the chip, not directly powered externally. The 10K to ground would be a pulldown to keep pin 20 from floating when the LCD is not being powered, and the .33 uF cap would be for power filtering.

The datasheet pointed to by your second link is a quality-control document; not quite what most of us call a datasheet, but Note B on page 1 suggests more documentation is available on the manufacturer's website. Their interfacing description and demo code should help.


body:
sorry if this isn't the done thing. I have a little red space invader shaped board that has an arduino chip on the back from a conference. There is an LCD display and I've just got it to function correctly (there was a power issue.

    ATE1 E
    0
    ATE
    1
The above is what the screen is displaying and I can't make heads or tails of it. Any ideas?

I've tagged this with arduino-micro because I think it may be that although I've had relative success using 'SparkFunProMicro' board in arduino IDE

**EDIT:** I've been able to get some more board info from arduino IDE. VID:1B4F, PID:9204, BN:unknown board, SN:Upload a sketch to get it.

title: I'm new here. Where to look for documentation for my specific board

Answers: 0


body:
I'm developing a arduino based system, which includes a alarm system.

Searching on the Internet, I found these lybraries ["Time.h"](http://www.pjrc.com/teensy/td_libs_Time.html) and ["TimeAlarms.h"](http://www.pjrc.com/teensy/td_libs_TimeAlarms.html).

In the requirements, it says: *"Time does not require any special hardware. Internally, Time depends upon **Arduino's millis()** function to keep track to elasped time."*

Considering Arduino's millis() rollover after 49.7 days, how can I ensure these lybraries are handling the rollover well?

I don't think that waiting 49.7 days to test it is the better way.

title: Time.h rollover after 49.7 days

Answers: 3

body:
As long as the date is before 2038, and your code calls one of the time functions at least once every 49 days, rollover won't affect you.

Internally the library uses Unix epoch time. Every time you call a function it checks to see if 1 or more seconds have past since the last time it was called and then updates the epoch time accordingly. Only for this check it uses millis(). And in only checks the difference between the last call's millis-value and the current millis-value, and rollover has no effect on time differences (as long as they are less that 49 days).

body:
You should simply buy a real time clock such as the common DS3231. They work well and don't have any problems with resting or continuous data reading. It also dictates the date!

Hope I helped :)

body:
I have a lengthy [post about this](http://www.gammon.com.au/millis).

To avoid going to the link if you don't want to, the simple answer is to subtract when calculating time intervals, eg.

    unsigned long startTime = millis ();
    unsigned long interval = 60000;

    ...

    if (millis () - startTime >= interval)
      {
      // do something
      }

This *always works!* - even after 49.7 days - because of the way that unsigned arithmetic works.

The only time it would fail is if you needed to time an interval of over 49.7 days - in which case a real-time clock is an obvious answer.

Another example:

    startedFeedingFish = millis ();

    ...

    if (millis () - startedFeedingFish >= 20000)  // feed them for 20 seconds
      {
      // stop feeding the fish
      }


body:
I have received an ESP8266 (ESP-07) Wi-Fi module from DealExtreme (Link: http://bit.ly/2dFJdxE).

It is a 4-pin module with the following pins: RX, TX, VCC and GND.
The module has a switch so you can switch between the following modes: Program & UART. The module also has a RESET-button.

Here's a picture of my module:

I've connected the module to my Arduino Uno like this:

RX > RX,

TX > TX(TX>RX & RX > TX, like mentioned in manuals, results in no connection),

VCC > 3.3v (not using any level shifters because the module has on board level shifters),

GND > GND.

I found a lot of manuals to test the module, but apparantly I can't get my module working. I am using Windows with the Arduino IDE.

The boards mentioned on the manuals/tutorials also seem to differ from my module because most of the manuals are talking about a board that has 8-pins (with an extra GPO0, GPO2 CH_PD and RST pin).

I've tried to upload the BareMinimum sketch to the module, which only finishes uploading if I disconnect and reconnect the 3.3v input that's feeded to the ESP-board when the Arduino IDE says "Uploading...... " while the ESP-board is in Program-mode.

I have installed the ESP8266 library within the Arduino IDE and the **Generic ESP8266 Module** is selected.

Then when I open the serial monitor in the Arduino IDE, to test the AT commands (on different BAUD values), it does not respond (neither in Program-, nor in UART-mode).

Strange thing is when I keep the serial monitor on at 74880 BAUD (and UART-mode on the module) and I push the RESET button on the module, it gives the following message:

    ets Jan  8 2013,rst cause:2, boot mode:(3,7)
    ets_main.c

I've tried several things.  But none of them seem to work; like trying to flash new firmware (for example 'v0.9.5.2 AT Firmware.bin' and 'esp8266-2016-05-03-v1.8.bin') with **esptool.py** with the following command:

    esptool.py -b 115200 -p COM3 write_flash 0 FIRMWARE.bin

It says that the writing is finished and no errors appear after running the esptool. This is what is printed + command that is used:

`esptool.py -p com3 -b 115200 write_flash 0 firmware.bin
esptool.py v1.2-dev
Connecting...
Running Cesanta flasher stub...
Flash params set to 0x0000
Writing 520192 @ 0x0... 520192 (100 %)
Wrote 520192 bytes at 0x0 in 44.2 seconds (94.1 kbit/s)...
Leaving...`

A strange thing is when I open the serial monitor in the Arduino IDE after that moment (without resetting the module/unplug from 3.3v or change to UART mode), it keeps printing the following at 115200 BAUD:

`Fatal exception (28):
epc1=0x4000228b, epc2=0x00000000, epc3=0x00000000, excvaddr=0x000000b5, depc=0x00000000
`

I even tried it with the erase_flash before and 0x00000 instead of 0. Also tried to run the command with a variety of flash_sizes (with the command --flash_size=Xm).

Esptool looks like the only tool where I can flash new binaries successfully, tried some others that where on some manuals but without success.

When I run `esptool.py -p flash_id`

I get the following response:

`Connecting...
Manufacturer: e0
Device: 4014`

Who knows how to fix this problem so I can send AT commands to the module through the serial monitor in the Arduino IDE.

Thanks in regards (this is my first post so if some things are unclear, please let me know)

**Edit:** Note that I have to disconnect and reconnect the 3.3v to the module EVERY time to successfully run a command (like write_flash, flash_id et cetera).
 Also tried connecting it to 5v and using an external power supply next to the USB.

title: Can't get ESP8266 working

Answers: 1

body:
Personally I think using an ESP as a interface for an Arduino is backwards and the Arduino ought to act as the interface to your devices for the much more powerful ESP.

I think you had a board that was configured to work as a interface between serial and Wifi, not as a normal board.  I'm pretty sure that you have now shagged it totally by trying to write programs to it.  However you might be able to recover it if you can find the original program and upload that to it.  You don't need the ability to program and ESP-8266 in the IDE to use this board, you can not upload sketches to it, you can't access the GPIOs.

I think you should just be able to slide the switch to "program" power the board up and type AT commands via a terminal emulator to set the board up and then power down, slide the switch back to UART and away it goes.  As to the Tx and Rx pins, that depends on weather its saying "this is the Rx pin" or "this is the Rx connection", you'll get it right second time :)

If you want a ESP8266 try AliExpress they cost between £1 and £2 and I've never had any problems, probably because they were made in China.


body:
I have the following code below for an `EthernetClient` named `client`. It is supposed to print a 2 row, 9 column table. The headers are `ID` and `Name` and are the first cell in each row. The other columns are the associated data. The problem I am having is that it is only printing the first `ID` and then the rest of the cells for that row are blank. The names all get printed in the row below it without a problem. Why won't it print the other IDs?

Here is the ID array: `  String ids[16] = {"00000", "00001", "00010", "00011", "00100", "00101", "00110", "00111", "01000", "01001", "01010", "01011", "01100", "01101", "01110", "01111"};`

    client.println("
");
    client.println("
");
    client.println("ID	");
    for(int i = 0; i < 8; i++) {
      client.print("");
      client.print(ids[i]);
      client.println("	");
    }
    client.println("
");
    client.println("
");
    client.println("Name	");
    for(int i = 0; i < 8; i++) {
       client.print("");
       client.print(name[i]);
       client.println("	");
    }
    client.println("
");
    client.println("
");

title: EthernetClient: HTML table isn't being fully populated

Answers: 0


body:
I built a sketch using some timer ISR code to get a trigger every second.  (for the Atmega328 chip I use the following code I got form the internets.  It works)

It runs fine and I get a trigger/callback every second.

    void setupAtmega328()
    {
    #ifdef __AVR_ATmega328P__

//     traceDebug("setupAtmega328() entry");

     cli();  // stop interrupts
  //   traceDebug("setupAtmega328() 1");

       //set timer1 interrupt at 1Hz
     TCCR1A = 0;// set entire TCCR1A register to 0
     TCCR1B = 0;// same for TCCR1B
     TCNT1 = 0;//initialize counter value to 0
         // set compare match register for 1hz increments
     OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
          // turn on CTC mode
     TCCR1B |= (1 << WGM12);
     // Set CS12 and CS10 bits for 1024 prescaler
     TCCR1B |= (1 << CS12) | (1 << CS10);
     // enable timer compare interrupt
     TIMSK1 |= (1 << OCIE1A);
    // traceDebug("setupAtmega328() 2");
     sei();//allow interrupts
    // traceDebug("setupAtmega328() 3");

    #endif
    }

I also wanted to add the capability of a real time clock (RTC) so I got a [DS3231][1].

I downloaded and ran the sample app from [this RTCLib on github][2]

The sample code works fine when running under the Arduino IDE

However, when I add the RTC code to my sketch I don't get the results I want/expect.

**Specifically, the program seems to hang/halt** at the call to:

    cli();

I am new to the Arduino platform and not sure what I am missing.
What do I need to do to get the RTC to work in conjunction with an ISR?

I wired the RTC according to the [directions from Adafruit's site][3]

I have other arduino boards that use different ISRs, but I have not tried them yet with the rtc since the 328 seems to be the standard arduino boars that is used to do initial work/testing.

**How can I use the 3231 RTC AND a 1 second ISR/callback?**

**EDIT:**
I removed the trace/serial output - I had originally added those to track the code to see where I got but i think I exacerbated or added problems in doing that.

for those interested the code is at https://github.com/tjurik/Intervalometer

  [1]: https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/
  [2]: https://github.com/adafruit/RTClib
  [3]: https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/wiring-and-test

title: Having trouble using RTC if I set an ISR for a 1 second timer

Answers: 1

body:
In the Arduino you don't have control how are some essential parts implemented.

For example `delay` function requires interrupts to be enabled or it'll be deadlocked (for sure).

Serials are little bit better, it'll be working until send buffer gets full. For devices with small RAM it's 16B only! And your `traceDebug` is little bit longer.

In general `ISR` should be as short as possible and it's mainly used for setting some flag to be handled in main loop later.

    volatile bool flag = false;

    ISR(...) {
      flag = true;
    }

    int main() {
      init();

      while (1) {
        if (flag) {
          do_something();
          flag = false;
        }
      }
    }


body:
I picked up an [AdaFruit Motor Shield V2.3][1] .  The example on the site shows how to code the DC Motor connection

    // Create the motor shield object with the default I2C address
    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    // Or, create it with a different I2C address (say for stacking)
    // Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

    // Select which 'port' M1, M2, M3 or M4. In this case, M1
    Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
    // You can also make another motor on port M2
    //Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2)

What I'm unclear about is how to connect the shield to the mega board.  Which pin on the shield should connect to which pin on the board in order for `Motor 1` to run at that speed?

  [1]: https://www.adafruit.com/product/1438

title: DC Motor Pinning the Ada Fruit Moto Shield with the Mega2560 R3

Answers: 1

body:
Well because an Arduino Mega2560 is pretty much and UNO with a longer rear end, try seeing the UNO in the MEGA if that makes any sense. Then just put the shield in like a normal shield that you would put on a UNO. Most UNO shields are compatible with MEGAs. Then you just use your shield like if it was on an UNO.

[![The UNO in the MEGA][1]][1]

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


body: My project is to find latitude and longitude of certain places. I am using an Arduino Uno R3 with a Cytron GPS 53 shield to get the position of places but, my device cannot run because COM4 already in use. How to fix this error?

title: Arduino Uno R3 not working with Cytron shield GPS 53

Answers: 1

body:
Your GPS board supports sending the data to the USB socket on the Arduino, sending it to pins 0 and 1, or sending it to a Software Serial port.  The first two options are going to confuse the output you are getting from the Arduino, so you should probably use the Software Serial option (read the manual on how to do that).

The data that you receive on the Arduino from the software serial port will need forwarding to the USB serial port that your PC is connected to, you will have to right a program to do this, but its not a difficult program and I'm sure there are examples out there.

If you want to make this mobile, you will need a battery to power the kit and an LCD display to show your results (get one with an I2C 'backpack' it will be easier to program).

Hopefully that should give you a start.


body:
I am not allowed to use the Arduino Library (or any Library) for this program. How would I check the input of a pin?

I found two different functions:

In Arduino.h:

    #define bitRead(value, bit) (((value) >> (bit)) & 0x01)

Following digitalRead back to pgmspace.h:

    #define __LPM_enhanced__(addr)  \
    (__extension__({                \
        uint16_t __addr16 = (uint16_t)(addr); \
        uint8_t __result;           \
        __asm__ __volatile__        \
        (                           \
            "lpm %0, Z" "\n\t"      \
            : "=r" (__result)       \
            : "z" (__addr16)        \
        );                          \
        __result;                   \
    }))

For the first one, I don't know where bit and value come from and I just don't understand the second one at all.

title: Get pin input status without using the arduino library

Answers: 1

body:
For reading, e.g., PB2, you would test

    PINB & _BV(PB2)

where PINB is the port input register and `_BV(x)` is a macro defined as
`(1 << (x))`.

C.f. the datasheet for the relevant port names.

See also the Arduino tutorial on
[port manipulation](https://www.arduino.cc/en/Reference/PortManipulation).


body:
This is for a class in which we are not allowed to use the Arduino Library (Not my choice or preference). I know to use DDRB for the B pins. This is the code that I have so far:

    //Global pointers
    unsigned char *portDDRB = (unsigned char *) 0x24;
    unsigned char *portDataB = (unsigned char *) 0x25;
    unsigned char *portPinB = (unsigned char *) 0x23;

    void setup () {
      //For the led output I know that I would do this
      *portDDRB |= 0x80;
    }

    void loop () {
       //And here the code would be like this to light up the light:
       if (condition to turn on light) {
         *portDataB |= 0x80;
       }
       // To Turn off the LED:
       if (condition to turn off the light) {
         *portDataB &= 0x7F
       }
    }

I would like for the light to turn on when the input of PB4 is HIGH (from a button press). I just am not sure on what to put in the condition statements or the setup functions.

When I set the DDRB to 0x80, is that just making the PB7 an output and the rest as input?

I am using the Arduino Mega ATmega2560 btw.

From the comments I have this:

    //Global pointers
    unsigned char *portDDRB = (unsigned char *) 0x24;
    unsigned char *portDataB = (unsigned char *) 0x25;
    unsigned char *portPinB = (unsigned char *) 0x23;

    void setup () {
      //For the led output I know that I would do this
      *portDDRB |= 0x80;
    }

    void loop () {
       //And here the code would be like this to light up the light:
       if (portPinB & 0x10) {
         *portDataB |= 0x80;
       }
       // To Turn off the LED:
       else {
         *portDataB &= 0x7F
       }
    }

title: Can I use the same Data Registry for both input and output pins?

Answers: 2

body:
Assuming the button is connected between GND and pin 10, without any pull-ups or pull-downs.

    void setup () {
        //For the led output I know that I would do this
        DDRB = 0;             // set all pins on port B to INPUT
        DDRB |= _BV(DDB7);   // set PB7 to OUTPUT
        PORTB = 0;            // set all pins on port B to LOW
        PORTB |= _BV(PORTB4); // enable the pull-up resistor on PB4
    }

    void loop () {
        if( PINB & _BV(PINB4) )
        {
            // if bit PINB4 is set, the button is not pressed
            PORTB &= ~_BV(PORTB7); // turn off led
        }
        else
        {
            PORTB |= _BV(PORTB7); // turn off led
        }
    }

body:
> When I set the DDRB to 0x80, is that just making the PB7 an output and the rest as input?

----

**Clarification**

I take that question to mean "When I *assign* the value to 0x80 to DDRB". For example:

    DDRB = 0x80;

In the code above that question, you were not assigning, you were "or"ing the value.

----
Yes. Typically you would "or" in the value if you want to affect only one pin, eg.

    DDRB |= 0x80;

The conventional way to make it an input again would be:

    DDRB &= ~0x80;

That is, "and" in the negated bit pattern for that pin.

Remember, you have 3 registers (per port) where "x" is "A", "B", "C" etc.:

 * DDRx - data direction - a 1-bit is output, a 0-bit is input
 * PORTx - output value - a 1-bit is HIGH, a 0-bit is LOW

    However, if the data direction is input, then a 1-bit is input-pullup, and a 0-bit is not input-pullup.
 * PINx - read the input from the port - a 1-bit is HIGH, a 0-bit is LOW

    Note that writing a 1-bit to PINx toggles the output value of that port.

---

These remarks apply to the AVR chips, not the SAM ones.


body:
I am building a quadrocopter with an Arduino Uno as control unit. I know I can [supply 5 volts to the 5V pin][1], but my ESCs produce 5.5 volts, which I measured with my multimeter. Will this voltage drop to 5 volts when I connect the Arduino and if not are 5.5 volts to the 5V pin a problem?

Edit:

My Arduino was running well for a couple of days on this setup with 5.5 volts to the 5V pin but died yesterday. By dying I mean the ATmega doesn't execute any code anymore, the L LED doesn't blink, and even a loopback test fails, which is a sign of a defective USB connector. But I am faced with the same challenge. Should I run my Arduino on 14.4 Volts from my 3S LIPO to Vin or supply 5.5 volts to the Vin pin?

Actually I just realised when I measure the voltage from the ESCs they deliver 9 point something volts for half a second when connecting the multimeter, I guess this voltage spike killed the Arduino.

  [1]: https://electronics.stackexchange.com/questions/65576/arduino-uno-r3-directly-supply-regulated-5v-to-5v-pin

title: Supply 5V to Arduino

Answers: 5

body:
I'm going to assume you are using the UNO model - or any other board based around the Atmega328p.

According to the datasheet the voltage limits are 1.8v to 5.5, with an absolute maximum of 6v.
You should be fine - but if you are able to get the voltage down closer to 5 volts, I would recommend doing that instead.

body: Most Arduinos won't mind 5.5v if your are sure that is the max. The ATmega328 is design to be used from 2.7V to 5.5V so that is the very max. No, the voltage will not drop down to 5V when you connect it to the Arduino but I believe you are quite safe with 5.5V. Just don't make a short because you'll be pushing your ATmega328 to it's designed max. You might wanna look at the datasheet for it. All it specs are in there.

body: You're better off applying that 5.5V to the Vin pin. You may end up with slightly less than 5V at the Arduino, but it'll tolerate that much better than going above 5.5V on the 5V rail.

body:
> Actually I just realised when i measure the voltage from the escs they deliver 9 point something volts for half a secound when connecting the multimeter ...

Yes, that won't be good for it. I suggest a LDO (low dropout) 5V voltage regulator. Something with a 0.5V dropout will get rid of that extra 0.5V and also handle the initial spike.

body:
Okay - it looks like that voltage spike might be the cause of death for your board.
As an answer to your question though - I would recommend applying the 14.4 volts to vin, as 5.5 volts is not enough (the regulator needs 6 volts as a minimum, and the absolute maximum is 20 volts).
Just make sure you apply the 14.4 volts to the *vin* pin and **NOT** the *5v* pin, as that would kill the board.

Please tell us how it worked out - good luck!


body:
I am able to set up one hz interrupts using millis and other timers, but would like to do it instead using the RTC I have attached ([DS3231][1])

I am not sure how I can do that.  Can someone point me to a reference for this?

**EDIT/UPDATE**

I tried to use the square wave to trigger a call back/interrupt, but it's not working for me.  I followed what I thought was the wiring diagram [here][2] and
[here][3] and [here][4]

I also added a led in the circuit to see if I could figure out something that way, but no dice.

Here is some simple code for a sketch that I think should trigger a 1 second interrupt and call my function:

    #include <DS3232RTC.h>    //http://github.com/JChristensen/DS3232RTC
    #include <Time.h>         //http://www.arduino.cc/playground/Code/Time
    #include <Wire.h>         //http://arduino.cc/en/Reference/Wire (included with Arduino IDE)

    const int rtcTimerIntPin = 2;
    bool flag = false;

    void setup(void)
    {
     Serial.begin(9600);
     setSyncProvider(gRTC.get);   // the function to get the time from the RTC
     if (timeStatus() != timeSet)
      Serial.println("Unable to sync with the RTC");
     else
      Serial.println("RTC has set the system time");

     bool stopped = gRTC.oscStopped();
     if (stopped)
     {
      Serial.println("Detected clock power loss - resetting RTC date");
      time_t newTime = cvt_date(__DATE__, __TIME__);
      adjustTime(newTime);
      setTime(newTime);
     }
     else {
      Serial.println("Clock did not lose power");
     }

     pinMode(13, OUTPUT);    // onboard LED
     pinMode(rtcTimerIntPin, INPUT);
     attachInterrupt(rtcTimerIntPin, rtc_interrupt, RISING);
     gRTC.squareWave(SQWAVE_1_HZ);

     digitalClockDisplay();
    }

    void rtc_interrupt(void)
    {
     flag = true;
    }

    void loop(void)
    {
     //digitalClockDisplay();

     if (flag) {
      digitalWrite(LED_BUILTIN, HIGH); // flash the led
      digitalClockDisplay();    // this just prints time to serial port
      delay(500);       // wait a little bit
      digitalWrite(LED_BUILTIN, LOW);  // turn off led
      flag =  false;      // clear the flag until timer sets it again
     }
    }

    void digitalClockDisplay()
    {
    // do something
    }

  [1]: https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/overview
  [2]: https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/wiring-and-test
  [3]: https://learn.adafruit.com/ds3231-precision-rtc-featherwing/pinouts
  [4]: https://learn.adafruit.com/ds3231-precision-rtc-featherwing/downloads

title: How to set up one second interrupt/ISR for ds3231 RTC

Answers: 4

body:
Try the following code. It pretty much detects a change in time and when a change has been detected, it will do something. In this case, it will print "do something".

    #include <DS3231.h>
    DS3231 rtc(SDA, SCL);
    String t; //time as a string
    String s;    //second
    String Ps;   //previous second

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

    void loop() {
      t = rtc.getTimeStr();             //finding time
      s = t.substring(6, 8);            //finding seconds

      if(s != Ps)                       //if the time has changed
      {
        Serial.println("do something"); //put whatever you want here
        Ps = t.substring(6, 8);         //redeclaring the previous second because it has advanced
      }
    }

body: Use [this DS3231 library](https://github.com/JChristensen/DS3232RTC). It has a method to set the squarewave `RTC.squareWave(SQWAVE_1_HZ)`

body:
> I tried to use the square wave to trigger a call back/interrupt, but it's not working for me.

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

>      bool flag = false;
>      ...
>      void rtc_interrupt(void)
>      {
>          flag = true;
>      }

Flags set in interrupts should be declared `volatile` otherwise the compiler may optimize away the comparison to the flag. That is:

    volatile bool flag = false;

---

If you are using the Adafruit library (from the page you linked to) then it should have a couple of functions that can be used to detect when the second has changed, for example:

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

    DateTime now = rtc.now();
    int second = now.second();
    unsigned long unixtime = now.unixtime();

In either case you just have to check if either one has changed in `loop`. For example:

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

    void loop(void)
    {
      static unsigned long previousTime = 0;
      DateTime now = rtc.now();
      unsigned long timeNow = now.unixtime();

      if (timeNow != previousTime) {
          digitalWrite(LED_BUILTIN, HIGH);    // flash the led
          digitalClockDisplay();              // this just prints time to serial port
          delay(500);                         // wait a little bit
          digitalWrite(LED_BUILTIN, LOW);     // turn off led
          previousTime = timeNow;             // remember previous time
        }
    }

body:
This answer addresses the original question of why the interrupts didn't work. I happened to have a DS3231 lying around so I made up a test.

---

## Interrupt vs pin number

First, this is wrong in your code:

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

>     attachInterrupt(rtcTimerIntPin, rtc_interrupt, RISING);

You need an interrupt number, not a pin number. This is correct:

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

      attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);

I also made it a CHANGE interrupt so you get both the rising and falling pulse.

---

## Pull-up resistor

Next, the 1 Hz output needs a pull-up resistor, so you should add that or make it INPUT_PULLUP like this:

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

      pinMode (rtcTimerIntPin, INPUT_PULLUP);

---

## Testing

I used [this library](https://github.com/adafruit/RTClib/archive/master.zip) from Adafruit.

Adapting one of their examples, and putting in your interrupt code (with my modifications), it worked!

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

    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS3231 rtc;

    const byte rtcTimerIntPin = 2;

    volatile byte flag = false;

    void rtc_interrupt ()
    {
      flag = true;
    }  // end of rtc_interrupt

    void setup () {

      Serial.begin(115200);

      while (!Serial); // for Leonardo/Micro/Zero

      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }

      if (rtc.lostPower()) {
        Serial.println("RTC lost power, lets set the time!");
        // following line sets the RTC to the date & time this sketch was compiled
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
      }

      // enable the 1 Hz output
      rtc.writeSqwPinMode (DS3231_SquareWave1Hz);

      // set up to handle interrupt from 1 Hz pin
      pinMode (LED_BUILTIN, OUTPUT);
      pinMode (rtcTimerIntPin, INPUT_PULLUP);
      attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);
    }

    void loop () {
      if (flag) {
        digitalWrite(LED_BUILTIN, HIGH);    // flash the led
        delay(100);                         // wait a little bit
        digitalWrite(LED_BUILTIN, LOW);     // turn off led
        flag =  false;                      // clear the flag until timer sets it again
      }
    }


body:
I am using the [L298N motor driver][1] for a robotics project to control 4 motors. 2 motors in each input and output terminal. I have this connected to an Arduino Uno which is powered by about 7-8v from NiMH batteries. This battery source also powers a servo with a 470uF capacitor and the L298N board.

I have a strange problem when I use the servo attach method for my servo, only outputs 1 and 2 on the L298N start working meaning the wheels on the left of the robot start moving only. When I have the servo connected and imported the library but don't use the attach method, the L298N outputs to all DC motors meaning it works. Even when I use the servo attach method on a pin where nothing is connected to it, the motors on out 4 and 3 on the L298N don't move. For some reason this attach method is causing issues. Can anyone explain why?

Note:  I applied a larger power supply, from my 7V to about 12V but the problem still persists. I don't think power is the issue since the problem even happens when the attach method is called on a pin that has no servo connected to it.

  [1]: https://www.sparkfun.com/products/9670

title: Servo.attach method causing strange issue

Answers: 0


body:
I'm building a smart shopping cart with Arduino for my final year project.

The cart is supposed to be able to follow its user while shopping. I don't know of many feasible indoor positioning systems to use.

**Proposed solution 1**

I have recently seen some RF/ultrasonic positioning systems that make use of:

- one ultrasound transmitter and one RF receiver, carried by the person,
- and two ultrasound receivers and one RF transmitter carried by the robot.

The robots RF transmitter sends out a signal, which when received by the person's RF receiver, triggers the person's ultrasound transmitter to transmit a signal. This signal is received by the robot's two ultrasound receivers (with a distance, d between them), and the distance and angle to the target person can be calculated.

That sounds very feasible, but my question is, if the robot is in a crowded place, where the other people are also carrying ultrasound transmitters and RF receivers:

1. Will the RF signal meant for the owner of the robot be accidentally received by the RF receiver on another person, or is there some kind of unique ID shared between RF receiver/transmitter pairs that could prevent this problem, or maybe some kind of frequency hopping system, so there would be no mistaken identity.
2. How will the ultrasound receivers on the robot be sure that the received signal is from its matching ultrasound transmitter. Again, is there some kind of special ID systems employed by some ultrasonic transmitter/receivers.

**Proposed solution 2**

I have also read about this new device called Trackr, it makes use of bluetooth low energy to track objects based on their proximity to bluetooth enabled devices like smart phones.

Considering a scenario where various bluetooth devices (beacons) are placed at specific points in a room, and the target to be tracked is equipped with a bluetooth emitter/bluetooth chip/dongle.

When the target passes each of those beacons, the signal strength intensity is received and distance from the target is calculated.

I understand this concept, but have some questions:

1. When distance is calculated between beacon and target, what about the angle, how would the robot follow the target based on distance alone?
2. If this method is not accurate enough to be used in a crowded space, what other method can be used, I have checked out some indoor GPS devices and they are way to expensive (above $200).

Would a camera-based tracking system be better and how easy would it be for a non expert like me to implement.

title: Problem building a smart shopping cart

Answers: 4

body:
Try keeping it simple. I'd have the person wear and infrared transmitter. Then on the cart have an array of IR-receivers pointing in all directions. That way the cart knows which direction to go.

Next you need to get the distance to the target using e.g. an ultrasonic distance sensor.

Lastly you need to add some bumper sensor, so the cart known when it's running into an obstacle.

Your camera solution might also work, combined with OpenCV. But you can't run that on a measly Arduino.

body:
I have a couple of ideas for you but know these are only suggestions. No hate please.

Have you tought of IR following?

IR is a almost unique signal that only you have. You can either use multiple IR sensors to determine where the emitter is or you can use the servo motor to do it as a radar. Note that you have to isolate each sensor so it knows where you are and it doesn't captures the wave from a different angle by accident.

Extra safety?

You can also incorporate an untrasonic distance sensor so that the cart doesn't bump into you or any one. Like you can say, if the distance is smaller then 12 inchs / 30 cm, stop the cart. It is practically an extra safety feature.

body:
Another solution, along the lines of your camera option, would be to seed the store with Kinect (or Kinect-like) camera systems.  These systems are already designed to track multiple people at once.

Using this method you don't need to equip the shopper with any device, which lowers logistics (how do I get that device back when the shopper exits the building) and tech support costs.

You *might* need to equip the carts with some kind of marker - I don't believe the Kinect systems are designed to track inanimate objects, but I could be wrong.

So challenges to overcome with this system would be:

1. How to track the carts?
2. Kinect doesn't have a very large focal distance so you will need some kind of system to hand shoppers off to the next Kinect when they pass out of range of the one currently tracking them.

body:
I'm going to get a bit ambitious here and suggest something along the lines of what the [Vive](https://www.vive.com/anz/product/) virtual reality system uses. You can see from some of the photos on that site that the headset has lots of sensors on it. Judging by [this article](https://www.gadgetdaily.xyz/heres-exactly-how-the-htc-vive-works/) they detect signals from two base stations. I presume the base stations send IR beams (because radio would not be directional enough). The sensors on the headset are recessed a bit, which would shield them from anything but a line-of-sight beam from a base station.

## The store

Now you don't need anything quite that sophisticated, but something like this might work. First, you have some IR transmitters located around the store, pointing in a criss-cross pattern, like this:

[![Shopping trolley system][1]][1]

The green box is the cart and the bigger boxes the shelving. Now with sensors on the corners of the trolley, pointing in different directions, and with each transmitter sending a differently-coded IR beam, the trolley should be able to work out its position fairly accurately.

## The trolley

By a process of exclusion (if you don't see a particular base station then you are not near it) and inclusion (if you *do* see a base station from a certain sensor then you can deduce a possible area you are in) you should be able to work out your position.

In this case we might expect that the bottom-left-diagonal sensor would be picking up signals from station 1003, and the bottom-right-diagonal sensor would be picking up signals from station 1004. Plus the forward sensor may be getting signals from station 1000 (depending on the range) and the rear sensor from station 1005.

## The shopper

Now we also need to know where the shopper is. If you gave the shopper a vest or belt with sensors on it in a similar way (eg. front, back, diagonal) then similar calculations can work out where the shopper is. Let's assume that each shopper and each trolley are given a unique ID pair (that is, a trolley is associated with a vest). Effectively, each shopper would transmit, every second or so "shopper 5677 is at position x=543, y=666 in the store".

Now we can use radio transmission (from the shopper) to its paired trolley, to tell the trolley where its "owner" is. And assuming the trolley knows where *it* is, then it can work out if movement is required, and if so, in what direction.

## Collision detection

In addition to the above, you would need some proximity sensors on the trolley (eg. ultrasonic) to stop the trolley from driving into other shoppers, display cases, its owner, etc.

## Maze solving

The trolley could have software on it to solve the problem of reaching the shopper. For example, if its way is blocked for too long on the shortest path, it might take an alternative which would be to go to the end of the aisle, go down a different aisle, and then back to where its owner is.

## Extra credit

1. You could make a button on the trolley you push when you are finished. The trolley could then "lead" you to the checkout with the shortest queue at it (or an empty checkout).

2. You could have some buttons on the trolley with major grocery types on it (eg. dairy food, bread, frozen foods). When pressed the trolley could lead you to the appropriate aisle.

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


body:
I have a couples of Arduino Pro Minis (original from sparkfun) that have those 4 disaligned pin. Unfortunetely, I need to use 2 of them, A4 and A5, because they are the I2C pins and I want to solder them onto a perf board.

Now, I really want to use headers and I do not want to solder any wire directly to it. I also do not want to add headers facing up on the board because I am trying to minimize space. Last, I am not willing to change Arduinos so please do not suggest me to use an Arduino Nano or Pro Micro.

[![Arduino Pro Mini][1]][1]

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

So I would like to know if there is a way to connect those 2 pin to the perf board via headers or is there any alternative pins that I can use to connect and use the I2C interface.

title: Soldering Arduino Pro Mini's disaligned pins

Answers: 3

body:
As you are soldering to perf board, perhaps you don't have a printed circuit board specific to your project. If you did, you could modify it, or could make a little intermediate PCB to accept connections from A4 A5 and shift them onto the grid.

If you have some 90°-angle headers, try removing a couple of pins from the plastic former, and 0.05" or 0.15" out from the line of the short side of the L, bend the long leg 90°.  Point the jog along the X or Y axis to align the pin with your perf board grid.

body:
That's indeed quite an problem.

If you don't mind losing 2 analog pin, you could solder some jumper-wires between A4 and A2; and between A5 and A3. Then you could connect your I2C lines to pins A2 and A3.

But you have to be careful to never set pins A2 and A3 to OUTPUT in your software. If you want to be super-duper safe, you could cut the trace from the header pins going to the TQFP-chip. See the image below.

[![modify arduino pro-mini][1]][1]

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

body: Easy! I like these ProMinis and use them in lots of projects. Simply exchange one of the 12 way header pin strips for a 14 way one (cheap to buy long lengths of these strips from eBay) add small neatly soldered wires to extend A4 and A5 to the extra pins you’ve added and job done.


body:
From the arduino documentation, the `Serial.read()` function is supposed to return a single character at a time from incoming serial messages. So if I program the arduino with the following:

    #include "SPI.h"

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

    void loop() {
      if (Serial.available() > 0) {
        char data1 = Serial.read();
        Serial.print(data1);
      }
    }

And I open the serial monitor and send `"Hello, World!"` I would expect the received message to be the individual characters printed one at time but instead I get back the whole message. So what gives? What am I not understanding?

title: Serial.read() is getting a whole string rather than just a character?

Answers: 1

body: You only think it is a string, it actually returns character by character. You can know by adding something like a delay after you Serial.print(). What the program actually does is that it receives one character each time you type one and it prints it, then the void loop repeats.


body:
I'm trying to control a DC motor's speed with my Arduino Mega `analogWrite()`, but it doesn't seem to function properly. The motor never completely slows down, just slows down a bit (which is still pretty fast) and then stops spinning completely.

I'm trying to create a robot with different speeds, and it just has to have a slow speed. I know it isn't the code, since the relay and motor works just fine when I use the `digitalWrite()`.

Is it better to write directly into the timer registers to implement the PWM, OR what else could be causing the problem?

title: Is analogWrite() inferior to writing directly into registers?

Answers: 1

body:
1. `analogWrite()` is already PWM, Arduino doesn't produce a true analog signal

2. Motors tend to draw a lot of current so you might want to control the motor with a MOSFET then connect your power supply directly to the motor. PWM will still work in that case, you just need to connect the output pin to the gate pin of the MOSFET

3. If you want more of an assurance when working with motors, try buying a motor shield. You current problem, speed problem and many will be resolved. It also makes it easy to control multiple motors.


body:
Is it possible to take a bare ATmega328 chip, and with an Arduino as ISP, burn a sketch directly to the chip (e.g. not needing a bootloader), or is the bootloader required to run Arduino sketches? I want to embed the ATmega328 into a different device, and do not want the overhead of the entire Arduino board.

I have looked at https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard and https://www.arduino.cc/en/Tutorial/ArduinoISP, and want to do the "minimal circuit" approach (as my application does not require 16MHz).

The tutorial described has steps to first burn a bootloader, then remove the chip from the Arduino, and then install the sketch. Ideally, I would like to skip the bootloader and removing the chip from my Arduino. Ideally, I would like to do it all from Arduino Studio (not AVRDUDE CLI).

I don't mind "dedicating" my Arduino to this (as I assume it's just burning the ArduinoISP sketch whenever I want to burn to a new ATMega328).

Thanks

title: Using Arduino as ISP to burn sketch directly to ATmega328 without first installing a bootloader on the ATmega328

Answers: 2

body: The bootloader only enables serial programming of the device; it is perfectly possible to run Arduino programs without it provided that the code is compiled with the same hardware options (MCU model, clock speed, etc.) that the standalone device/board uses.

body: It is possible to skip the **Burn Bootloader** step. When you do **Upload Using Programmer** the bootloader is overwritten and thus serves no purpose. However, there is another reason for the **Burn Bootloader** step, to set the correct fuses for your board selection. The fuse settings configure things on the ATmega328 such as clock speed and clock source. If the ATmega328 you are using doesn't happen to have the correct fuse settings for the board selection you're using in the IDE then things may not work or may not work correctly. For this reason it's best to always do the **Burn Bootloader** step the first time you use the ATmega328 and any time you change the board selection or other settings related to that board selection(such as custom **Tools** menu settings). Since you're not using an external clock source for your ATmega328 make sure that you don't select a board that is configured for an external clock as this will cause the chip to no longer work until you have connected an external clock.


body:
I have some neopixels, and I have one hooked up to my teensy.
I want to have the color change, when the push button is pressed vs not pressed. The LED will change colour when I upload the code, if I have the button pressed, green, if the button is not pressed, red.

The serial monitor reports changing button press statuses, so I'm not sure why the neopixel isn't changing.

The adafruit website is confusing to me, they have wonderful and involved project examples, but they never have just a basic IO example.

I would appreciate it, if someone could point out where Im going wrong with this code:

    #include <Adafruit_NeoPixel.h>

    #define PIN            0

    // How many NeoPixels are attached to the Arduino?
    #define NUMPIXELS      1

    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
    const int buttonPin = 2;
    int buttonState = 0;

    void setup() {
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
      pinMode(0,OUTPUT);
      Serial.begin(9600);
      pixels.begin(); // This initializes the NeoPixel library.

    }

    void loop() {

    buttonState = digitalRead(buttonPin);
    Serial.println(buttonState);

        // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
          if (buttonState == LOW) {
              pixels.setPixelColor(PIN, pixels.Color(0,33,0)); // green
              pixels.show();

          }else{
              pixels.setPixelColor(PIN, pixels.Color(66,0,0)); // red
              pixels.show();
            }
            delay(500);
      }

this code compiles, without errors, and uploads just fine, but pressing the button won't change the LED color.

title: neopixel not blinking

Answers: 2

body:
I had a wiring Problem, the device wasn't properly grounded, but still illuminating.

Its working now on pin0, but the idea to use PWM pins is valid. Duly noted.

body: I'm not a Teensy Pro but the neopixel library requires a PWM pin. Pin 0 doesnt seem to be PWM on the Teensy. Try another pin.


body:
I am at the moment trying via ros to publish a status message about how many steps a motor has moved.
Problem, is that value doesn't to be readable, or the only thing I am able to read from the topic is a zero.

The value i want to publish is being incremented inside a ISR routine, so i have a single thread that continuesly publishes the messages, and then when an ISR is called, increment it the value.

I tested with serial to see what might have been wrong, but the output of the serial doesn't seem to make any sence, isn't readable.. Is outputs alot of "??" eventhoug I am using the right baudrate and so on. So what is the problem here?

speed_profile.cpp

    #include "speed_profile.h"

    volatile speed_profile profile;
    ros::NodeHandle nh;

    std_msgs::Int16 status_step_count;
    ros::Publisher chatter("tipper_status", &status_step_count);

    void output_pin_setup()
    {
      pinMode(en_pin,OUTPUT);
      pinMode(dir_pin,OUTPUT);
      pinMode(step_pin,OUTPUT);
      nh.initNode();
      nh.advertise(chatter);
    }

    void timer1_setup()
    {
      // Tells what part of speed ramp we are in.
      profile.run_state = STOP;

      // Timer/Counter 1 in mode 4 CTC (Not running).
      TCCR1B = (1 << WGM12);

      // Timer/Counter 1 Output Compare A Match Interrupt enable.
      TIMSK1 = (1 << OCIE1A);
    }

    void compute_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed)
    {
      digitalWrite(en_pin,HIGH);
      delay(1);

      unsigned int steps_to_speed;  // Steps required to achieve the the speed desired
      unsigned int acceleration_step_limit; // If desired speed is not achieved, will this variable contain step_limit to when to stop accelerating.

      if (motor_steps < 0)
      {
        profile.dir = CCW;
        motor_steps = -motor_steps;
        digitalWrite(dir_pin,LOW);
      }
      else
      {
        profile.dir = CW;
        digitalWrite(dir_pin,HIGH);
      }

      delay(1);

      // If moving only 1 step.
      if (motor_steps == 1)
      {
        // Move one step
        profile.accel_count = -1;
        // in DECEL state.
        profile.run_state = DECEL;
        // Just a short delay so main() can act on 'running'.
        profile.first_step_delay = 1000;
        OCR1A = 10;
        // Run Timer/Counter 1 with prescaler = 8.
        TCCR1B |= ((0 << CS12) | (1 << CS11) | (0 << CS10));
      }
      else if (motor_steps != 0)
      {
        // Set max speed limit, by calc min_delay to use in timer.
        // min_delay = (alpha / tt)/ w
        profile.min_time_delay = A_T_x100 / motor_speed;

        // Set accelration by calc the first (c0) step delay .
        // first_step_delay = 1/tt * sqrt(2*alpha/accel)
        // first_step_delay = ( tfreq*0.676/100 )*100 * sqrt( (2*alpha*10000000000) / (accel*100) )/10000
        profile.first_step_delay = (T1_FREQ_148 * sqrt(A_SQ / motor_accel)) / 100;

        // Find out after how many steps does the speed hit the max speed limit.
        // steps_to_speed = speed^2 / (2*alpha*accel)
        steps_to_speed = (long)motor_speed * motor_speed / (long)(((long)A_x20000 * motor_accel) / 100);
        // If we hit max speed limit before 0,5 step it will round to 0.
        // But in practice we need to move atleast 1 step to get any speed at all.
        if (steps_to_speed == 0)
        {
          steps_to_speed = 1;
        }

        // Find out after how many steps we must start deceleration.
        // n1 = (n1+n2)decel / (accel + decel)
        acceleration_step_limit = ((long)motor_steps * motor_decel) / (motor_accel + motor_decel);
        // We must accelrate at least 1 step before we can start deceleration.
        if (acceleration_step_limit == 0)
        {
          acceleration_step_limit = 1;
        }

        // Use the limit we hit first to calc decel.
        if (acceleration_step_limit <= steps_to_speed)
        {
          //profile.decel_length = steps_to_speed - motor_steps;
          profile.decel_length = -(motor_steps-acceleration_step_limit); //---
        }
        else
        {
          //profile.decel_length = -((long)steps_to_speed * acceleration_step_limit) / motor_decel;acceleration_step_limit
          profile.decel_length = -((long)steps_to_speed * motor_accel) / motor_decel; //--
        }
        // We must decelrate at least 1 step to stop.
        if (profile.decel_length == 0)
        {
          profile.decel_length = -1;
        }

        // Find step to start decleration.
        //int steps_in_run = motor_steps - steps_to_speed-profile.decel_length;

        profile.decel_start = motor_steps + profile.decel_length;
        //profile.decel_start = motor_steps - steps_to_speed-steps_in_run;

        // If the maximum speed is so low that we dont need to go via accelration state.
        if (profile.first_step_delay <= profile.min_time_delay)
        {
          profile.first_step_delay = profile.min_time_delay;
          profile.run_state = RUN;
        }
        else
        {
          profile.run_state = ACCEL;
        }

        // Reset counter.
        profile.accel_count = 0;
        OCR1A = 10;
        // Set Timer/Counter to divide clock by 8
        TCCR1B |= ((0 << CS12) | (1 << CS11) | (0 << CS10));
        profile.moved_steps = 0;

      }

      while(1)
      {
        cli();
        status_step_count.data = profile.moved_steps;
        Serial.print("profile.moved_steps: ");
        Serial.println(profile.moved_steps);
        Serial.print('\n');
        sei();
        //chatter.publish( &status_step_count);
        //nh.spinOnce();
        delay(1);
      }

    }

    ISR(TIMER1_COMPA_vect)
    {
      // Holds next delay period.
      unsigned int new_first_step_delay;

      // Remember the last step delay used when accelrating.
      static int last_accel_delay;

      // Counting steps when moving.
      static unsigned int step_count = 0;

      // Keep track of remainder from new_step-delay calculation to incrase accurancy
      static unsigned int rest = 0;

      OCR1A = profile.first_step_delay;

      switch (profile.run_state)
      {

        case STOP:
          step_count = 0;
          rest = 0;
          TCCR1B &= ~((1 << CS12) | (1 << CS11) | (1 << CS10)); // Stop the timer,  No clock source
          break;

        case ACCEL:
          digitalWrite(step_pin,!digitalRead(step_pin));
          //delay(1);
          //digitalWrite(step_pin,LOW);
          step_count++;
          profile.accel_count++;
          new_first_step_delay = profile.first_step_delay - (((2 * (long)profile.first_step_delay) + rest) / (4 * profile.accel_count + 1));
          rest = ((2 * (long)profile.first_step_delay) + rest) % (4 * profile.accel_count + 1);

          // Chech if we should start decelration.
          if (step_count >= profile.decel_start)
          {
            profile.accel_count = profile.decel_length;
            profile.run_state = DECEL;
          }

          // Chech if we hitted max speed.
          else if (new_first_step_delay <= profile.min_time_delay)
          {
            last_accel_delay = new_first_step_delay;
            new_first_step_delay = profile.min_time_delay;
            rest = 0;
            profile.run_state = RUN;
          }
          break;
        case RUN:
          digitalWrite(step_pin,!digitalRead(step_pin));

          //delay(1);
          //digitalWrite(step_pin,LOW);
          step_count++;
          new_first_step_delay = profile.min_time_delay;
          // Chech if we should start decelration.
          if (step_count >= profile.decel_start)
          {
            profile.accel_count = profile.decel_length;
            // Start decelration with same delay as accel ended with.
            new_first_step_delay = last_accel_delay;
            profile.run_state = DECEL;
          }
          break;
        case DECEL:
          digitalWrite(step_pin,!digitalRead(step_pin));
          step_count++;
          profile.accel_count++;
          new_first_step_delay = profile.first_step_delay - (((2 * (long)profile.first_step_delay) + rest)/(4 * profile.accel_count + 1));
          rest = ((2 * (long)profile.first_step_delay)+rest)%(4 * profile.accel_count + 1);
          // Check if we at last step
          //digitalWrite(step_pin,!digitalRead(step_pin));
          if(profile.accel_count >= 0)
          {
            digitalWrite(en_pin,!digitalRead(en_pin));
            profile.run_state = STOP;
          }

          break;

      }
        profile.first_step_delay = new_first_step_delay;
        profile.moved_steps = step_count;
    }

speed_profile.h

    #ifndef speed_profile_h
    #define speed_profile_h

    #include <Arduino.h>
    #include <ros.h>
    #include <std_msgs/Int16.h>

    // Timer/Counter 1 running on 3,686MHz / 8 = 460,75kHz (2,17uS). (T1-FREQ 460750)
    //#define T1_FREQ 460750
    #define T1_FREQ 1382400

    //! Number of (full)steps per round on stepper motor in use.
    #define FSPR 1600

    // Maths constants. To simplify maths when calculating in compute_speed_profile().
    #define ALPHA (2*3.14159/FSPR)                    // 2*pi/spr
    #define A_T_x100 ((long)(ALPHA*T1_FREQ*100))     // (ALPHA / T1_FREQ)*100
    #define T1_FREQ_148 ((int)((T1_FREQ*0.676)/100)) // divided by 100 and scaled by 0.676
    #define A_SQ (long)(ALPHA*2*10000000000)         // ALPHA*2*10000000000
    #define A_x20000 (int)(ALPHA*20000)              // ALPHA*20000

    // Speed ramp states
    #define STOP  0
    #define ACCEL 1
    #define DECEL 2
    #define RUN   3

    // Pin numbering
    #define en_pin 13
    #define dir_pin 12
    #define step_pin 11

    // Motor direction
    #define CW  0
    #define CCW 1

    typedef struct
    {
     volatile unsigned char run_state : 3; // Determining the state of the speed profile
     volatile unsigned char dir: 1; // Determining the direction the motor has to move - Start being CCW
     volatile unsigned int first_step_delay; // Period time for the next timer_delay, determines the acceleration rate.
     volatile unsigned int decel_start; //  Determines at which step the deceleration should begin.
     volatile signed int decel_length; // Set the deceleration length
     volatile signed int min_time_delay; //minium time delay c0
     volatile signed int accel_count; // counter used when computing step_delay for acceleration/decelleration.
     volatile unsigned int moved_steps; // Used by ros to publish current tipper position

    }speed_profile;

    void compute_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed);
    void timer1_setup(void);
    void output_pin_setup(void);
    #endif

main.ino

    #include "speed_profile.h"

    void setup() {
      // put your setup code here, to run once:
      cli();
      Serial.begin(9600);
      output_pin_setup();
      timer1_setup();
      sei();
    }

    void loop()
    {
      // put your main code here, to run repeatedly:
        Serial.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

        int motor_steps = -3000;//-9600; //23400 -  100%
        // Accelration to use.
        int motor_acceleration = 500;//500;
        // Deceleration to use.
        int motor_deceleration = 500;//500;
        // Speed to use.
        int motor_speed = 1000; // 1000
        compute_speed_profile(motor_steps, motor_acceleration, motor_deceleration, motor_speed);
        while(1)
        {

        }
    }

title: How to handle an interrupt that interrupts a serial communication?

Answers: 3

body: That is QUITE a high baud rate. You might want to lower it. I know that Arduinos running at 8MHZ can barely handle 112500. Do not push it too far. I do not know what Arduino you are using but at 16MHZ, don't push it too far. Also make sure that at that baud rate you supply a lot of juice to your Arduino so that it can run more smoothly.

body:
The problem may be due to something you haven't told us about, so the following suggestions are just general ideas.

First, try out whether serial communication works ok at 230400 when your stepper code isn't running.  For example, add some debug lines to skip over whatever code turns on interrupts to run the stepper, and see if serial  communication is ok.

If serial  communication still fails with stepper interrupts off, try lower serial rates, eg 19200 or 9600.  In addition, in your Publisher add a reasonable delay, eg half a second or a second, between serial writes.  You might also not issue a write whenever the total steps has changed less than a hundred counts, or some similar number.

I'd probably factor toggling `step_pin` out of the `switch`, via code like the following.

    if (profile.run_state != STOP) {
       // Toggle step_pin by writing 1 to its bit in PINB
       PINB = step_pin_mask; // pin 11 = PB3, so mask is 1<<PB3, ie, 1<<3
       step_count++;
    }
    switch (profile.run_state) {
       ...

 Using `digitalRead()` and `digitalWrite()` adds a fair amount of overhead, undesirable in an ISR.  (See their source code at garretlab links, [`digitalRead()`](http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_digital.c/digitalRead.html) and [`digitalWrite()`](http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_digital.c/digitalWrite.html)) That extra overhead could possibly account for glitches in serial communications.

By contrast, writing a mask bit to an input port is about the fastest way for software to toggle a bit or set of bits.  It is, of course, less flexible and less obvious.

body:
This is highly inadvisable:

>     cli();
>     status_step_count.data = profile.moved_steps;
>     Serial.print("profile.moved_steps: ");
>     Serial.println(profile.moved_steps);
>     Serial.print('\n');
>     sei();

Doing serial prints with interrupts off could hang your sketch because the Serial output routines require interrupts on to work.

Later versions of the IDE might not hang completely but will block until the data can be written.


body:
I just bought an LCD. I connected everything as explained in [this][2] sheet.

This is the code I am using:

    #define RST 3
    #define CE 2
    #define DC 4
    #define DIN 6
    #define CLK 5

    void LcdWriteCmd(byte cmd) {
      digitalWrite(DC, HIGH); //DC pin is low for commands
      digitalWrite(CE, HIGH);
      shiftOut(DIN, CLK, MSBFIRST, cmd); //transmit serial data
      digitalWrite(CE, LOW);
    }

    void setup() {
      pinMode(RST, OUTPUT);
      pinMode(CE, OUTPUT);
      pinMode(DC, OUTPUT);
      pinMode(DIN, OUTPUT);
      pinMode(CLK, OUTPUT);
      digitalWrite(RST, LOW);
      digitalWrite(RST, HIGH);
      LcdWriteCmd(0xAE); // LCD set display enabled
      LcdWriteCmd(0x21); // LCD set power COntrol
      LcdWriteCmd(0x14); // LCD bias mode 1:40
      LcdWriteCmd(0xA2); // LCD basic commands
      LcdWriteCmd(0xA9); // LCD all segments on
    }

    void loop() {
    }

The commands I used are in the [command table of this sheet][3]. (page 12)
It is supposed to turn all pixels on now. However nothing happens. All pixels are staying off.

Can you see a problem?

  [1]: http://www.buydisplay.com/default/blue-2-8-inch-128x64-display-serial-lcd-module-spi-with-touch-panel
  [2]: http://www.buydisplay.com/download/interfacing/ERC12864-655_Interfacing.pdf
  [3]: http://www.buydisplay.com/download/ic/UC1701.pdf

title: LCD not doing anything

Answers: 1

body:
I am not so sure the command that you used to turn all pixels on is right. It might say it in the document but you should try to manually turn a couple of pixels on yourself. check the link bellow if you need more assistance with LCDs.

Also be sure that you connected some power and a potentiometer to the contrast pin and/or backlight of the LCD.

https://www.youtube.com/watch?v=dZZynJLmTn8


body:
I want to use 4 Push Buttons and 4 leds in my project. What do I need to change in my sketch for multiple input push buttons and multiple outputs of leds? So my sketch is only for one push button and one led. So tell me how I can solve this problem.

Here is the code:

    const int buttonPin =2;    // the number of the pushbutton pin
    const int ledPin = 13;      // the number of the LED pin

    // Variables will change:
    int ledState = HIGH;         // the current state of the output pin
    int buttonState;             // the current reading from the input pin
    int lastButtonState = LOW;   // the previous reading from the input pin
    long lastDebounceTime = 0;  // the last time the output pin was toggled
    long debounceDelay = 50;
    void setup() {
    pinMode(buttonPin, INPUT);
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, ledState);
    }

    void loop() {
    int reading = digitalRead(buttonPin);
    if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
    }

    if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
      }
      }

      // set the LED:
     digitalWrite(ledPin, ledState);
     lastButtonState = reading;
     }

title: Arduino Debounce Sketch

Answers: 3

body: Well you declared only one pushbutton and one led. Now do like push1, push2, push3, push4 and led1, led2, led3, led4, and so on. You can also do that with your buttonStates1... Do not forget to declare them as INPUTs or OUTPUTs. Copy paste will help you with this task.

body:
>  What do I need to change in my sketch for multiple input push buttons and multiple outputs of leds?

easy:

1) study your code to understand how it debounces one input;

2) isolate those parameters / variables used to debounce that specific input;

3) group those parameters / variables into a struct and pass a pointer to that struct to your code;

4) rewrite your code so that it takes the pointer to that struct and debounces accordingly;

5) use that code on as many inputs as you wish.

that's the general approach you take to coding any task.

hope it helps.

body:
I hope this will work for you.

    const int buttonPin1 = 2; // Button 1
    const int buttonPin2 = 3; // Button 2
    const int buttonPin3 = 4; // Button 3
    const int buttonPin4 = 5; // Button 4

    const int ledPin1 = 6; // LED 1
    const int ledPin2 = 7; // LED 2
    const int ledPin3 = 8; // LED 3
    const int ledPin4 = 9; // LED 4

    int ledState1 = HIGH;
    int ledState2 = HIGH;
    int ledState3 = HIGH;
    int ledState4 = HIGH;

    int buttonState1, buttonState2, buttonState3, buttonState4;

    int lastButtonState1 = LOW;
    int lastButtonState2 = LOW;
    int lastButtonState3 = LOW;
    int lastButtonState4 = LOW;

    long lastDebounceTime1 = 0;
    long lastDebounceTime2 = 0;
    long lastDebounceTime3 = 0;
    long lastDebounceTime4 = 0;

    long debounceDelay1 = 50;
    long debounceDelay2 = 50;
    long debounceDelay3 = 50;
    long debounceDelay4 = 50;

    void setup()
    {
      pinMode(buttonPin1, INPUT);
      pinMode(ledPin1, OUTPUT);
      digitalWrite(ledPin1, ledState1);

      pinMode(buttonPin2, INPUT);
      pinMode(ledPin2, OUTPUT);
      digitalWrite(ledPin2, ledState2);

      pinMode(buttonPin3, INPUT);
      pinMode(ledPin3, OUTPUT);
      digitalWrite(ledPin3, ledState3);

      pinMode(buttonPin4, INPUT);
      pinMode(ledPin4, OUTPUT);
      digitalWrite(ledPin4, ledState4);
    }

    void loop()
    {
      led1Fun();
      led2Fun();
      led3Fun();
      led4Fun();
    }

    void led1Fun()
    {
      int reading1 = digitalRead(buttonPin1);

      if(reading1 != lastButtonState1)
      {
        lastDebounceTime1 = millis();
      }

      if((millis() - lastDebounceTime1) > debounceDelay1)
      {
        if(reading1 != buttonState1)
        {
          buttonState1 = reading1;

          if(buttonState1 == HIGH)
          {
            ledState1 = !ledState1;
          }
        }
      }

      digitalWrite(ledPin1, ledState1);
      lastButtonState1 = reading1;
    }

    void led2Fun()
    {
      int reading2 = digitalRead(buttonPin2);

      if(reading2 != lastButtonState2)
      {
        lastDebounceTime2 = millis();
      }

      if((millis() - lastDebounceTime2) > debounceDelay2)
      {
        if(reading2 != buttonState2)
        {
          buttonState2 = reading2;

          if(buttonState2 == HIGH)
          {
            ledState2 = !ledState2;
          }
        }
      }

      digitalWrite(ledPin2, ledState2);
      lastButtonState2 = reading2;
    }

    void led3Fun()
    {
      int reading3 = digitalRead(buttonPin3);

      if(reading3 != lastButtonState3)
      {
        lastDebounceTime3 = millis();
      }

      if((millis() - lastDebounceTime3) > debounceDelay3)
      {
        if(reading3 != buttonState3)
        {
          buttonState3 = reading3;

          if(buttonState3 == HIGH)
          {
            ledState3 = !ledState3;
          }
        }
      }

      digitalWrite(ledPin3, ledState3);
      lastButtonState3 = reading3;
    }

    void led4Fun()
    {
      int reading4 = digitalRead(buttonPin4);

      if(reading4 != lastButtonState4)
      {
        lastDebounceTime4 = millis();
      }

      if((millis() - lastDebounceTime4) > debounceDelay4)
      {
        if(reading4 != buttonState4)
        {
          buttonState4 = reading4;

          if(buttonState4 == HIGH)
          {
            ledState4 = !ledState4;
          }
        }
      }

      digitalWrite(ledPin4, ledState4);
      lastButtonState4 = reading4;
    }


body:
I am currently working on a project which requires me to record IR signals. (I realize there is a library available for doing this but I want to learn how to do this myself).

I tried using a simple sketch which prints out `pulseIn()` times on the Arduino, but then if I try to record them into an array, the Arduino misses the pulses happening while it is writing the timings to the array.

How can I achieve being able to record these fast pulses to the Arduino's memory without skipping some of the pulses?

title: Arduino Record pulseIn

Answers: 0


body: I have a byte that I am looking to break into 2 nibbles. The leftmost nibble I can get easily via shifting right 4 times. However, I can't figure out how to get the rightmost nibble. Any ideas?

title: How to get the rightmost four bits from a byte

Answers: 1

body:
Just mask it with an AND operator:

    val = var & 0xF;


body:
I'm debugging a project which includes SoftwareSerial. I'm not convinced the serial connection behaves as expected, so I came up with the following simple test:

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

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

      // starting the software serial
      mySerial.begin(4800);
    }

    void loop() {
      for (int i=0; i <= 10; i++){
        delay(10);
        mySerial.write(i);
      }
    }

I connected pin 11 to pin 1 (arduino Uno), hence forwarding the data of the software serial connection via the default (hardware) serial connection to my computer. But no data is coming through.

Am I missing something?

title: Using SoftwareSerial to send data to itself

Answers: 1

body:
If you are hoping to see the results in the serial monitor, you need to read it in and send it back (so it ends up on the USB port). Like this:

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

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

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

      // starting the software serial
      mySerial.begin(4800);
    }

    void loop() {
      for (int i = 0; i <= 10; i++) {
        delay(10);
        mySerial.println(i);

        while (Serial.available ())
          Serial.write (Serial.read ());
      }
    }

Now you have to connect pin 11 to pin **0** (not pin 1) because that will now be the Serial Rx pin.

I think your method failed because with Serial active the Serial hardware was trying to drive pin 1 high (ie. idle) which was conflicting with the data from pin 11.

---

An alternative is to not do a `Serial.begin()` - which therefore does not initialize the serial hardware and it doesn't conflict any more. This also works:

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

    void setup() {
      // starting the software serial
      mySerial.begin(4800);
    }

    void loop() {
      for (int i = 0; i <= 10; i++) {
        delay(10);
        mySerial.println(i);
      }
    }

Now you connect pin 11 to pin 1 as you originally wanted.

---

Notice I changed your `mySerial.write(i);` to `mySerial.println(i);` so you get correct data output (numbers, not control characters).


body: I want to initialize the value of byte to -1. When I just use `byte num = -1` the value ends up being a decimal 255. I've also tried `int8_t number = -1` and then `byte num = number` but this didn't work either.

title: How to represent -1 as a byte

Answers: 3

body:
A byte can't be -1. A byte can only store numbers between 0 and 255 inclusive.

Depending on the range of your numbers you could use a `char` (-128 to +127) or an `int` (-32768 to +32767).

body: Simply -1 can't be a byte. A byte is a number from 0-255. -1 is below 0. The Arduino reference defines a byte as "A byte stores an 8-bit unsigned number, from 0 to 255.".

body:
As the other two users have already mentioned:
A byte can only store a number between 0-255, which obviously means that -1 can't be stores as a byte.

I suggest storing it as a positive number, and then when you want to use it just multiply it by -1, which will turn it into a negative one.

***Example to convert positive number as a byte to a negative number:***

     negativeNumber = positiveNumberStoredAsByte * -1


body: Is there any way to change the default name (ESP_xxxxx) that the module generates?

title: How to change the default name of ESP8266-12E module

Answers: 4

body:
This line of code should hopefully do a difference.

    wifi_station_set_hostname(myHostname);

For more information :

https://www.reddit.com/r/esp8266/comments/3zl3pi/change_esp8266_network_name/

body:
Here you are the code where you can see how you can change `network name` of your ESP8266 working in AP mode:

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>

    IPAddress ip(192,168,1,81);         // choose IP address
    IPAddress subnet(255,255,255,0);

    ESP8266WebServer server(80);

    void handleRoot() {
      String page = "<!DOCTYPE html>\n";

      page += "\n\n
Some heading

Generated by ESP8266\n\n";
      server.send(200, "text/html", page);
    }

    // what to do when accessed through http://ip_address/something_undefined
    void handleNotFound(){
      String message = "File not found\n\n";
      message += "URI: ";
      message += server.uri();
      message += "\nMethod: ";
      message += (server.method() == HTTP_GET)?"GET":"POST";
      message += "\nArguments: ";
      message += server.args();
      message += "\n";
      for (uint8_t i=0; i<server.args(); i++){
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
      }
      server.send(404, "text/plain", message);
    }

    void setup(void){
      Serial.begin(74880);                      // so you can see debug messages automatically sent by ESP8266
      WiFi.mode(WIFI_AP);
      WiFi.softAPConfig(ip, ip, subnet);        // declared as: bool softAPConfig (IPAddress local_ip, IPAddress gateway, IPAddress subnet)
      WiFi.softAP("SOME_NAME", "password", 7);  // network name, network password, wifi channel

      IPAddress myIP = WiFi.softAPIP();
      Serial.println();
      Serial.print("AP IP address: ");
      Serial.println(myIP);

      server.on("/", handleRoot);               // what to do when accessed through browser using http://IP_address

      // what to do when accessed through http://ip_address/test
      server.on("/test", [](){
        server.send(200, "text/plain", "This is another page");
      });

      server.onNotFound(handleNotFound);

      server.begin();
      Serial.println("HTTP server started...");
    }

    void loop(void){
      server.handleClient();
    }

body: The function is: `WiFi.hostname("Name");`, make sure you call it before `Wifi.begin()`

body: check the Erase Flash>> Tools >> Arduino IDE before uploading your sketch and select erase previous wifi settings


body:
When programming an ESP-01 with Arduino IDE, how can I make the Tx and Rx into a generic I/O pins reliably? I think there's a command to swap the Tx and Tx with other pins. I  tried `serial.swap()` but it didn't work. So how to get done with Arduino IDE or is it even possible?. I am using an ESP-01, which means there will be four GPIO pins once this question in answered.

I want to achieve same as in the video, [How to add more GPIOs to ESP8266 (ESP-01)][1], but without soldering wire.

  [1]: https://www.youtube.com/watch?v=9RVyWZCSMtA

title: How to I make the Tx and Rx pins on an ESP-8266-01 into GPIO pins?

Answers: 5

body:
Tx = GPIO 1

Rx = GPIO 3

Should work but be careful cause if they burn, you won't be able to program or even talk to the ESP anymore.

body:
Maybe a little late but it might helps someone else.

[ESP-01 GPIO pins (1&3)][1]

  [1]: http://www.forward.com.au/pfod/ESP8266/GPIOpins/ESP8266_01_pin_magic.html

body:
Add this to your code at the beginning of set `void setup()`:

    //********** CHANGE PIN FUNCTION  TO GPIO **********
    //GPIO 1 (TX) swap the pin to a GPIO.
    pinMode(1, FUNCTION_3);
    //GPIO 3 (RX) swap the pin to a GPIO.
    pinMode(3, FUNCTION_3);
    //**************************************************

You will no longer be able to use the Serial Monitor as TX will now be a GPIO pin and not transmit Serial data. You can still Flash your device as when you boot the device in flash mode it converts GPIO1 and GPIO3 back to TX/RX. Once you reboot into regular running mode GPIO1 and GPIO3 will go back to being GPIO pins.

To change GPIO1 and GPIO3 back to being TX/RX for regular Serial Monitor use add this to your code at the beginning of set `void setup()`:

    //********** CHANGE PIN FUNCTION  TO TX/RX **********
    //GPIO 1 (TX) swap the pin to a TX.
    pinMode(1, FUNCTION_0);
    //GPIO 3 (RX) swap the pin to a RX.
    pinMode(3, FUNCTION_0);
    //***************************************************

If I understand the ESP-01 correctly the pins CANNOT be both TX/RX and GPIO pins at the same time.

body:
One thing I noticed is that if you're trying to use the Tx/Rx pins for the main serial comm (1 & 3) as a GPIO then you must not use any Serial commands in your code, such as Serial.begin.

I was having my GPIO digital reads randomly read high (they had their mode set as INPUT_PULLUP) while I had a source pulling them low (I verified that input was indeed pulled low while the ESP8266 digitalRead was reading high)

Removing all Serial commands (begin, print and println) fixed that for me.

body: To work TX RX as GPIO Serial.begin() must be deleted from code.


body:
[UPDATE] Now it works fine but the as soon as I add the GY-521 module (hardware not software), it starts sending me crapy info

Project uses:

Arduino Pro Mini as brain

FTDI as a programmer

GY-521 gyro/accel

MPL3115A2 baro/altimeter

DS3231 real time clock

Micro SD card adapter to datalog

The GY-521, MPL3115A2 and the DS3231 uses I2C and they are breakout boards so they include pull-up resistors on the board. Now the GY-521 and the MPL3115A2 works fine together but as soon as I add the DS3231, it all freezzes. My code is fine and I'm sure of that.

Now my theory is that all of those pull-up resistors caused some kind of problem in the circuit. I know that normal I2C require 4.7k ohm pull-up resistors. Now I BELIEVE that the GY-521 uses 4.7k pull-up resistors, the MPL3115A2 uses 10k pull-up resistors and the DS3231 also uses 10k pull-up resistors.

I don't know if this setup could work and I would like to know if I can add some external resistors to calm the whole I2C constellation a bit. Note that I do not want to sodder anything to the breakouts nor do I want to modify them.

Here is the code:

Tab1: MAIN

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

    #include <SPI.h>                        //include the SPI library
    #include <SD.h>                         //include the SD card library
    #include <Wire.h>                       //include I2C library
    #include "I2Cdev.h"                     //include another I2C library
    #include "Wire.h"                       //include another I2C library (yes, again)
    #include "MPU6050_6Axis_MotionApps20.h" //include the MPU6050 library
    #include "SparkFunMPL3115A2.h"          //include the MPL3115A2 library
    #include <DS3231.h>                     //include the DS3231 library

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

    #define testtest           //*** COMMENT THIS LINE BEFORE UPLOADING OFFICIAL CODE TO FINAL PROJECT ***

    #define chipSelect 10      //pin for the CS/SS
    #define led 2              //led and/or buzzer

    volatile bool mpuInterrupt = false; //just one of those bools

    bool ledState     = false; //state of the led and/or buzzer
    bool dmpReady     = false; //state of the mpu6050

    int yprInt[3];             //gyro data in a integer because the extra precision of the float is total bullshit
    int altitude;              //altitude above takeoff point in meters
    int altitudeCalibration;   //calibration for the altimeter
    int temperature;           //temperature in degrees Celcius

    float counter = 0;         //time counter, a somewhat internal clock that starts when the module starts dataloging

    uint8_t mpuIntStatus;      //holds actual interrupt status byte from MPU
    uint8_t devStatus;         //return status after each device operation (0 = success, !0 = error)
    uint8_t fifoBuffer[64];    //FIFO storage buffer

    uint16_t packetSize;       //expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;        //count of all bytes currently in FIFO

    String day;                //day of the week
    String ymd;                //date: year,month,day
    String hms;                //time: hour,minute,second

    MPU6050 mpu;               //MPU6050 object declaration as mpu
    Quaternion q;              //quaternion container
    VectorFloat gravity;       //gravity vector

    MPL3115A2 myPressure;      //MPL3115A2 object declaration as myPressure
    DS3231  rtc(SDA, SCL);     //DS3231 object declaration as rtc

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

    void setup()
    {
      generalSetup();

      gyroSetup();
      baroSetup();

      dataSetup();
    }

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

    void loop()
    {
      gyro();      //read angles
      baro();      //read altitude and temperature
      timeClock(); //read day, date, time

      dataPrint();   //serial print the information

      dataLog();   //write data in sd card

      timer();     //time delay and led flash
    }

Tab2: SETUP

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

    void generalSetup()
    {
      Serial.begin(115200); //start serial communication
      Wire.begin();         //start I2C communication
      rtc.begin();          //start DS3231

      pinMode(led, OUTPUT); //led or buzzer; used to easily find a lost device
    }

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

    void dmpDataReady() {
      mpuInterrupt = true;
    }

    void gyroSetup()
    {
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
      TWBR = 24;
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
      Fastwire::setup(400, true);
    #endif
      //while (!Serial);
      mpu.initialize();
      devStatus = mpu.dmpInitialize();
      mpu.setXGyroOffset(220);
      mpu.setYGyroOffset(76);
      mpu.setZGyroOffset(-85);
      mpu.setZAccelOffset(1788);

      if (devStatus == 0)
      {
        mpu.setDMPEnabled(true);
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
      }

      else
      {
        return;
      }
    }

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

    void baroSetup()
    {
      myPressure.begin();             //start MPL3115A2 communication
      myPressure.setModeAltimeter();
      myPressure.setOversampleRate(7);
      myPressure.enableEventFlags();
      altitudeCalibration = myPressure.readAltitude(); //read altitude
    }

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

    void dataSetup()
    {
      if (SD.begin());
    }

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

Tab3: FUNCTIONS

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

    void gyro()
    {
      float yprFlo[3]; //gyro data in a float

      mpu.resetFIFO();
      mpuInterrupt = false;
      mpuIntStatus = mpu.getIntStatus();
      fifoCount = mpu.getFIFOCount();

      if (mpuIntStatus & 0x02)
      {
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        fifoCount -= packetSize;
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(yprFlo, &q, &gravity);

        for (int i = 0; i < 3; i++)
        {
          yprFlo[i] = yprFlo[i] * 180 / M_PI; //simplify the variable for serial printing and dataloging
        }

        for (int i = 0; i < 3; i++)
        {
          yprInt[i] = yprFlo[i]; //changing the variable from a float to a int
        }
      }
    }

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

    void baro()
    {
      altitude = myPressure.readAltitude() - altitudeCalibration; //read altitude
      temperature = myPressure.readTemp();  //read temperature
    }

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

    void dataPrint() //serial print all the data
    {
      Serial.print(day);
      Serial.print(" ");
      Serial.print(ymd);
      Serial.print(" -- ");
      Serial.print(hms);
      Serial.print(", ");
      Serial.print(counter);
      Serial.print(", ");
      Serial.print(yprInt[0]);
      Serial.print(", ");
      Serial.print(yprInt[1]);
      Serial.print(", ");
      Serial.print(yprInt[2]);
      Serial.print(", ");
      Serial.print(altitude);
      Serial.print(" ,");
      Serial.print(temperature);
      Serial.println();
    }

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

    void dataLog()//wirte all the data in a note file on the sd card
    {
      if (altitude > 1) //if the device is higher then 1m, then we sstart recording everything
      {
        File dataFile = SD.open("datalog.txt", FILE_WRITE);

        if (dataFile)
        {
          dataFile.print(day);
          dataFile.print(" ");
          dataFile.print(ymd);
          dataFile.print(" -- ");
          dataFile.print(hms);
          dataFile.print(", ");
          dataFile.print(counter);
          dataFile.print(", ");
          dataFile.print(yprInt[0]);
          dataFile.print(", ");
          dataFile.print(yprInt[1]);
          dataFile.print(", ");
          dataFile.print(yprInt[2]);
          dataFile.print(", ");
          dataFile.print(altitude);
          dataFile.print(" ,");
          dataFile.print(temperature);
          dataFile.println();
          dataFile.close();
        }
      }
    }

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

    void timeClock()
    {
      day = rtc.getDOWStr();
      ymd = rtc.getDateStr();
      hms = rtc.getTimeStr();
    }

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

    void timer()
    {
      counter = counter + 0.5;

      #ifndef testtest
      ledState = !ledState;
      digitalWrite(led, ledState);
      #endif

      delay(500);
    }

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

title: Multiple I2C BREAKOUTS with pull-up resistors doesn't work [UPDATE]

Answers: 3

body:
According to my calculations the total pull-up is:

    1 / (1/10 + 1/10 + 1/4.7) = 2.423 k

As I show on [my page about I2C](http://www.gammon.com.au/i2c) a 2.2 k pull-up resistor gives a reasonably good signal:

[![2.2k pullup][1]][1]

Thus I don't think the resistors are the issue. And I don't see how adding more would "calm the whole I2C constellation a bit".

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

body:
In fact the MPU-6050 on the GY521 and the DS3231 both use I2C address 0x68.  Had you looked at the source of the header files you included for each, this would have been apparent.

By consulting the data sheet for each chip you will likely find a way to either change the I2C address by changing a configuration pin, or else to potentially enable/disable the chip by changing one with a GPIO.  This will, however, likely require surgical modification of the carrier board.

You could also move whichever device you expect to access least to a distinct "soft" I2C bus bit-banged on other GPIO pins. No endorsment is implied, but the the first such library that came up in a web search was:

http://playground.arduino.cc/Main/SoftwareI2CLibrary

you can likely find other options for yourself, or can potentially create your own.

There are also other chips in the family of the MPU-6050 which speak SPI instead of or as well as I2C, however these tend to be more expensive.

body: When additional resistors are added in parallel, which is what is going on when you add new I2C devices to the I2C bus, the overall resistor is lowered. This could cause a problem with devices that cannot provide enough current with a low pull-up resistance. Hence, the device will not function well when the pull-up resistance is lower than a specific value. To fix the problem, I recommend removing all parallel pull-up resistors and just keep one at each line to achieve a good resistor value of approximately 4.7 k-ohms.