body:
**TL;DR** When Serial is invoked on a rev3 Uno, the UART uses the Tx and Rx pins on PORTD regardless of what you try to do to PORTD I/O directly. The warnings on arduino.cc about avoid those bits appears to be wrong. Readbacks from PORTD on those pins reflects the last user input, not the state of those pins.  **/TL;DR**

I have extensive assembler (other platforms) and python experience, but no C and am still on the lowers lopes of the Arduino learning curve. I am using the Arduino/C IDE at the moment for simplicity, though I have a feeling that once I bite the bullet (not for this project if possible), I am going to find the direct AVR route suits my style more.

I'm developing a charliplexed LED driver application on Uno hardware which uses most of the I/O pins, so am having to use portD. I'm using direct writes to DDRD and PORTD rather than digitalWrite(), for a number of reasons not all related to speed.

I am aware of the use of pins 0 and 1 for serial comms, so am using the recommended DDRD |= Bxxxxxx00 format when setting to 1, and DDRD &= Bxxxxxx11 when setting to 0.

I hadn't intended reading back the port, though I'm knee-deep in debug readbacks, so did it eventually. When I read back DDRD, it's Bxxxxxx00 every time. But my readbacks are working, so serial communication using the Serial.println(xx) format and the monitor in the IDE, continues to work.

I would have expected the Tx direction bit to be 1. Is it the case that the Serial library grabs the port when it needs to transmit, and then reverts it? So is it actually 0 when I read it, or am I reading wrongly, or I can't read it? As I expect DDRD &= Bxxx to work, I should be able to read it.

I'm comfortable working with the bare metal, where I have total control, and with python where it's all magic, but get a bit uneasy when I'm not sure whether I expect magic to be happening under the hood or not.

Here's the code

    const byte portD_1_mask = B11111100;
    const byte portD_0_mask = B00000011;

    #define DEBUG_LEN 20
    char debug_str[DEBUG_LEN+1];
    #include "debug_formats.h"

    byte counter;

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

      // send an intro:
      Serial.println("\n\ndebug portD demo:");
      Serial.println();
    }

    void loop()
      {
        counter += 3;
        Serial.println(counter);
        drive_LEDs(counter);
        delay(100);
      }

    void drive_LEDs(int a)
    {
        // create port programming variables, initialised to 0
        byte D_dir = 0;
        byte D_data = 0;

        // prepare bytes to be written to the ports
        // the anode gets driven by ORing into both data and direction
        D_dir |= 4;  // constant for this demo
        D_data |= 4;
        // the cathode(s) get driven by ORing into the direction only
        D_dir |= a;   // wave these around

        Serial.println("generated programming bytes");
        Serial.print("direction - data - ");
        debug_format(D_dir, D_data);
        Serial.println(debug_str);

        // finally write all pins to their new values
        // D port needs to pussyfoot around not changing the TxRx pins

        // reset D port 7-2 to all 0s
        PORTD &= portD_0_mask;
        // and then set the ones we've got in the 7-2 positions
        D_data &= portD_1_mask;
        PORTD |= D_data;

        // and the same for D direction
        // switch D 7-2 to inputs first
        DDRD &= portD_0_mask;
        // then set the outputs
        D_dir &= portD_1_mask;
        DDRD |= D_dir;

        // and see what we have written to port
        Serial.println("what the hardware has been set to");
        Serial.print("direction - data - ");
        D_dir = DDRD;
        D_data = PORTD;
        debug_format(D_dir, D_data);
        Serial.println(debug_str);
    }

and the results it produces on the monitor

    debug portD demo:

    3
    generated programming bytes
    direction - data - 00000111..00000100..
    what the hardware has been set to
    direction - data - 00000100..00000100..
    6
    generated programming bytes
    direction - data - 00000110..00000100..
    what the hardware has been set to
    direction - data - 00000100..00000100..
    9
    generated programming bytes
    direction - data - 00001101..00000100..
    what the hardware has been set to
    direction - data - 00001100..00000100..
    12
    generated programming bytes
    direction - data - 00001100..00000100..
    what the hardware has been set to
    direction - data - 00001100..00000100..

The hardware is doing what I'd expect, LEDs are flashing.

Now I'm not concerned that the 'generated programming bytes' have LSBs set and they don't appear in the readback, as I'm doing a data &= portD_1_mask which clears the LSBs before ORing into the port.

What I am questioning is the fact that the two LSBs on DDRD are always read back as 0. If the Serial library grabbed and kept those pins continuously, then I would expect the Tx pin to be an output, whenever I read it. But it's not reading back that way. So does that mean Serial only makes the Tx an output when it's transmitting, and then puts it back to input when not? Or is my read of the DDRD Tx bit not working for some reason, though it seems to be working for the other bits?

OK, so I've got the 'scope out, put a resistor network on the Tx pin so I can see whether it's high or low Z, and it stays low Z even when not transmitting, so the UART does 'retain' the port. This means the readback of the DDRD contents is a lie. Section 19.6 of the AVR doc 8161 does say the port pins are *overridden* by the UART, which this seems to confirm.

So if they are overridden, all this warning on the arduino.cc site tutorials about not stomping on the pins is incorrect. The following code bashes the bejaabers out of PORTD while using it to receive and send.

      int count;

    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      // send an intro:
      Serial.println("\n\ndebug portD demo:");
      Serial.println();
    }

    // the loop function runs over and over again forever
    void loop() {
      count += 1;
      if ((count&1)==0) DDRD = 0; else DDRD = 0xff;
      if ((count&2)==0) PORTD = 0; else PORTD = 0xff;

      PORTB = 0xff;
      byte dd = DDRD;
      byte pp = PORTD;
      Serial.println();
      Serial.println(count);
      Serial.println(dd);
      Serial.println(pp);
      PORTB = 0;
      delay(2000);

      if (Serial.available() > 0)
      {
        byte inByte = Serial.read();
        Serial.print("got >");
        Serial.println(inByte);
      }
    }

and this fragment of output captured from the monitor shows it keeps working. I used a sufficiently long delay so I'd be able to hit all phases of the write to data and direction on PORTD.

    9
    255
    0
    got >49

    10
    0
    255
    got >114

    11
    255
    255
    got >99

    12
    0
    0
    got >115

    13
    255
    0
    got >115

Lessons

a) When Serial is in use, the UART hardware does override the Tx Rx pins, at least on a rev3 Uno.

b) It does hang on to the hardware between active transmissions

c) The warnings on arduino.cc tutorials about writes to PORTD and DDRD don't seem to be valid, it appears the hardware just ignores them

d) Reads back from PORTD and DDRD show what you last wrote in pins 0 and 1 when the UART is in use, not what's on the pins.

title: (SOLVED more or less) Direct reading/writing to PORTD, unexpected readback, how does the serial library use it?

Answers: 1

body:
See the datasheet: **14.3.3 Alternate Functions of Port D**

> * TXD/PCINT17 – Port D, Bit 1
TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1.
> PCINT17: Pin Change Interrupt source 17. The PD1 pin can serve as an external interrupt source.
>
> * RXD/PCINT16 – Port D, Bit 0
RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input regardless of the value of DDD0. When the USART forces this pin to be an input, the pull-up can still
be controlled by the PORTD0 bit.
> PCINT16: Pin Change Interrupt source 16. The PD0 pin can serve as an external interrupt source.

So basically if you turn on the USART the pins are configured as input/output regardless of DDRD.

---

> but get a bit uneasy when I'm not sure whether I expect magic to be happening under the hood or not.

It's not the IDE - it's the underlying hardware.

---

>  This means the readback of the DDRD contents is a lie.

No it isn't. The hardware is ignoring DDRD in those bits. See this example:

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

    void setup()
    {

    DDRD = 0;
    byte a = DDRD;
    DDRD = 0xFF;
    byte b = DDRD;

    Serial.begin (115200);

    DDRD = 0;
    byte c = DDRD;
    DDRD = 0xFF;
    byte d = DDRD;
    Serial.end ();

    Serial.begin (115200);
    Serial.print ("a = ");
    Serial.println (a);
    Serial.print ("b = ");
    Serial.println (b);
    Serial.print ("c = ");
    Serial.println (c);
    Serial.print ("d = ");
    Serial.println (d);
    }

    void loop()
    {
    }

Output:

    a = 0
    b = 255
    c = 0
    d = 255

The code is setting DDRD and reading it back as set. However the hardware is ignoring those bits because of the alternative use of those ports.


body:
I have an L239D motor shield just like the Adafruit motor shield. I had a question in my mind. While making a robot, I could not connect my pins from various sensors in Arduino as the motor shield is already fitted on the board. So how can I connect my pins?

PS: I have the same board as shown in the picture [![enter image description here][1]][1]

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

title: Problem with connecting pins on an Arduino board with an L239D shield

Answers: 1

body:
That's a common problem that has many solutions.

The cheapest way is to solder the wires directly as many comments said. Though this is quite dirty, it should work for you.

The more professional way is to use these [Arduino stackable header][1]. They can even let you have a shield on top of your shield. This is the best choice in my opinion.

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


body:
I'd like to program my Arduino using Assembler. We have to learn this at college.
The problem is that I can find a documentation for the instruction set but I can't find the Special Function Registers.

Something like this would be great or similar to make a sheet like this by myself.

title: Where are the Special Function Registers located? (Atmega 328)

Answers: 2

body:
> Where are the Special Function Registers located? (Atmega 328)

Please see Chap. 36 Register Summary, pp. 612, in
http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

The registers are available "by name" in the AVR IO header files.

Cheers!

body:
There are several options for programming the AVR in assembly, but since
you have an Arduino and the Arduino IDE bundles the gcc toolchain, using
this toolchain is probably the easiest way. Besides, if you learn
assembly in the GNU syntax, you will be able to use it together with C++
and the Arduino libraries.

The gnu compiler will run through the C preprocessor any assembly
program having the `.S` extension (in uppercase). You would then start
your program with

    #include <avr/io.h>

in order to get all the SFR definitions from avr-libc. That include file
is intended to work both in C and in assembly. The SFRs so declared
should be considered as opaque identifiers. To get their addresses, you
should use the macros `_SFR_IO_ADDR()` or `_SFR_MEM_ADDR()`. I
personally find those names too cumbersome to type, so I tend to
`define` my own shortcuts.

Just to get you started, here is a minimal “blinky” program in assembly
for the Arduino Uno (ATmega328P with the LED on PB5):

    ; Blinky in assembly.

    #include <avr/io.h>
    #define io(reg) _SFR_IO_ADDR(reg)

    .global main
    main:
        sbi io(DDRB), PB5  ; PB5 as output
    0:  sbi io(PINB), PB5  ; toggle PB5

        ; delay 16 * 65536 * 5 cycles ~ 0.31 s
        ldi  r26, 16
    1:  sbiw r24, 1
        sbci r26, 0
        brne 1b

        rjmp 0b ; restart


body:
I'm currently working on an Arduino project that sends the charge of my car battery once a day via an ESP8266 to me. During the winter I don't drive my car, and I would like to get informed when the battery drops beyond a critical value, so I can charge it and prevent damage.

So energy efficiency is important for the project, so it doesn't discharge the battery itself. I read a lot about sleep mode, efficient drop down regulators etc. These all have in common that the voltage regulator is always running, which is not what I want.

I'm looking for some kind of "swich-on-timer circuit". It should count down 24 hours and then turn on a relay or MOSFET, which connects the voltage regulator to power and with that turns on the Arduino and the ESP8266. When the Arduino has finished with the transmission, it resets the timer, which disconnects the voltage regulator from power, and so on. Of course, the timer circuit should use only very little power.

Does anybody know a circuit like that? I searched on [AliExpress](http://www.aliexpress.com/) with all variations of words that came to my mind, without success. Or maybe an IC which can be used (easily) to create such a circuit?

title: Turn Arduino on with timer every 24h

Answers: 4

body:
The timer or timer-circuit itself would have to draw some current. Any of the pico-power AVR chips draw very little current in sleep mode - in the 10s of micro-amps for the 328, if I recall correctly. Sleeping an AVR for the least current draw needs just about everything shut down but the watchdog timer, and the maximum WDT period is 8 sec. A library like Narcoleptic will manage longer periods for you. What you would need to do though, is to provide a much more efficient regulated power supply than the one built onto the Arduino board (if that is what you'll be using). That done, the Arduino's load on your car battery should be microscopic.

One possible design for an efficient supply is an array of alkaline batteries, say 3 in series for a 4.5 output (while fresh) times 2 or more such strings in parallel, connected directly to the 5v bus.

I haven't done the power budgeting to know the capacity you'd need and whether you'd need D cells or could make a practical array from smaller ones, say AAs, but that is a way to achieve zero load on the car battery (discounting the car-battery voltage sensor's requirement). You might want to include the Arduino battery-array's health in the daily report, or, for the price of a few Alkalines, you might so over-design the Arduino battery that monitoring it would become unnecessary.

A couple of data points suggest a separate battery is a feasible approach:

- A single 9v Alkaline runs a smoke detector for over a year including over-wintering in an unheated attic (in my own experience), and 9v Alkalines are _not_ known for their capacity.
- My digital setback thermostat has run for a couple of years on 2 AA cells, before a) they died, and b) I wised-up and started changing them annually. :)

body:
One approach would be use of a DS3231 (Precision Real Time Clock) module.  Such modules sell on Ebay for under $1.  Search for `ds3231 arduino`.

Typically, these modules have a six-pin connector, with pins labeled 32K, SQW, SCL, SDA, VCC, and GND.  As noted in DS3231 specs, the INT/SQW pin is used either for square-wave output or for interrupt output.  On page 13 of specs, in the Control Register section, it says:
>Bit 2: Interrupt Control (INTCN). This bit controls the INT/SQW signal. When the INTCN bit is set to logic 0, a square wave is output on the INT/SQW pin. When the INTCN bit is set to logic 1, then a match between the time-keeping registers and either of the alarm registers activates the INT/SQW output (if the alarm is also enabled).

Initially, you would run a sketch to set up the DS3231: turn on a daily alarm, enable an interrupt rather than square wave, set the current time, etc.  Then, load an operational program that reads car-battery voltage each time it runs, and acts appropriately.

The DS3231 INT/SQW pin would be wired to the gate of a P-channel mosfet that switches 12V power to the Arduino.  The P-fet would turn on when the alarm's open-drain output pin INT/SQW turns on.  The operational program does its business and then clears the DS3231 interrupt flag, to shut down power until the next alarm occurs.  (For debugging, set briefer intervals than a day; for example, once a minute, as described in Table 2, Alarm Mask Bits, on page 12 of specs.)

Typically, the DS3231 draws 0.84 μA when running from a 3.3V battery, or 1 μA from 5V.  See Electrical Characteristics, page 3 of specs.

body:
you can use a timer switch. you can buy it from ebay for around 5 euros. i am using this one

https://www.ebay.com/itm/CN101-DC-12V-16A-Digital-LCD-Power-Programmable-Timer-Time-Relay-Switch-New/401190616827?hash=item5d68d2fefb:g:K3sAAOSwNRdX3ggT

i have also tried ds3231 but the arduino is on standby mode and it consume energy. this is the best solution i found

body:
Consider using "Adafruit TPL5110 Power Timer" <BR>
https://learn.adafruit.com/adafruit-tpl5110-power-timer-breakout/overview


body:
My Situation and Problem:

I am wanting to put together a system to help monitor the soil moisture content in my garden and a small heated greenhouse I use in the winter. Also, In the near future I would like to build a system to remotely monitor the nutrients in my soil and other grow media, and have it accessible through my computer using a system similar to the one I'll have monitoring the moisture levels. In both situations I am growing nearly all crops hydroponically.

I have found several instances of people doing this by having the information posted to a service provider's website. Then it is possible to access the information by way of email or connecting in some manner to the service provider's site.

I plan to store the data in the cloud, but where I live we get internet access through satellite dish or land based re-transmission sites. So, I am planning to keep all gathered data in "The Cloud" manually, once received when I turn on my computer. I even have to use a booster device in my house to get dependable cell phone service. My land line telephone service provider doesn't offer high speed internet service, so I don't presently use a smart phone. I recently read a news article talking about a similar, though more widespread situation in Australia. In Australia they call it the tyranny of distance.

In addition to my garden and greenhouse, I have several other ideas for using Arduino to gather data using wifi and do any number of other things, and most of these ideas include accessing the gathered data through my computer connected to an Arduino device as required. It would certainly be helpful if anyone would be willing to share any ideas or point me toward inexpensive solutions.

Thanks for your kind consideration.

title: Is it possible to use Wi-Fi as a wireless connection to my Arduino/Windows PC LAN without using the internet

Answers: 2

body:
Ok, my idea is that you could connect the arduino AND your computer to the same router ( that doesn't need to internet access) to create a simple LAN. Then program the arduino to send every X amount of time data to the computer with a simple protocol like UDP knowing the LAN address of the computer ( example would be 192.168.1.2) and the one of the arduino, you could send UDP packets with IP address of the computer and since the router sees that the IP is in its internal LAN it just sends it straight away. Now there are a few problems to this approach:

1) The arduino needs to have signal to be connected with the router, so the distances need to be reasonable.

2) Both the arduino and the computer needs to be always on. The arduino isn't a big issue, just remember that if for some reason you'll use the millis() or micros() functions eventually they'll reset to 0 and start again. As for the computer instead, this could be a bit expansive, since having a normal pc on for all the time can impact the electricity bill quite a bit. The solution to this would be for example to make the arduino write data on a  SD card and when it sees that the computer is on and that it's able to send it to it, it starts retriving data from the SD, sending it to the PC and then deleting it. The problem with this is that the SD has a limit as well, so just keep this in mind.

body:
I have a hydroponic setup working. Actually I'm working in a second version. My solution is this:

[![Monitor setup][1]][1]

I'm using a nodeMCU, because it have WiFi and lots of memory. In the breadboard I also have a real time clock (RTC), a LDR to measure real light level, and a temp/humidity sensor (DH-11), plus a small OLED display. The green led represent the HID light for testing purposes. I still need to add more elements, but it's good enough to show you my setup.

The nodeMCU send information to a MQTT *broker* . I can watch that information using an MQTT *client* in my Android smartphone. With the same client I can send orders to the nodeMCU (like changing light schedule, etc.)

MQTT is a protocol designed for Internet of Thing. It small and simple. You need a *broker* (server) to receive and send messages. I'm using Mosquitto running on Linux, on a old laptop that is on all time.

This is the big picture (no Internet involved):

[![Local Area Network][2]][2]

Mosquitto is free, and it's available for PC, Mac and Linux [here][3].

You have free clients for Android, iPhone, Windows, Mac, and Chrome. I'm using [MQTT Dash][4].

MQTT is lightweight, easy, multiplatform, multiclient, and the best part of it: minimal programming.

  [1]: https://i.stack.imgur.com/VGBrE.jpg
  [2]: https://i.stack.imgur.com/lASo3.png
  [3]: https://mosquitto.org/download/
  [4]: https://play.google.com/store/apps/details?id=net.routix.mqttdash&hl=en


body:
I am working on creating sensor poller that is going to be polling multiple sensors and then, on request, provides its data to the master.

The master polls the slave (SPI) at 50hz and the slave is polling it's sensor (BNO055) (I2C) at 100hz.

The transaction works most of the time but every once in a while it returns an overflow.

Any ideas why this might occur?

Slave code:

    /*************************************************************************
     *
     * objeeAirlines
     * __________________
     *
     *  Written by Julian Blanco
     *
     *  Spi slave code written by
        Nick Gammon
        February 2011
     */

    #include "Adafruit_BNO055.h"

    float yawInput=0;
    float yawOffset=0;
    float pitchInput=0;
    float rollInput=0;

    int calibration=0;

    volatile byte command = 0;
    Adafruit_BNO055 bno = Adafruit_BNO055();

    void setup (void)
    {

      if(!bno.begin())while(1){};
      bno.setExtCrystalUse(true);
      // have to send on master in, *slave out*
      pinMode(MISO, OUTPUT);
      // turn on SPI in slave mode
      SPCR |= _BV(SPE);
      // turn on interrupts
      SPCR |= _BV(SPIE);
    }  // end of setup

    // SPI interrupt routine
    ISR (SPI_STC_vect)
    {
      union first_union{
        float f;
        byte b[4];}
      data;

      byte c = SPDR;

      data.f = yawInput;

      command = c;

      switch (command)
      {
      // no command? then this is the command
      case 0:

        SPDR = 0;
        break;

      // incoming byte, return byte result
      case 'a':

        SPDR = data.b[0];
        break;

      // incoming byte, return byte result
      case 'b':

        SPDR = data.b[1];
        break;

      // incoming byte, return byte result
      case 'c':

        SPDR = data.b[2];
        break;

      // incoming byte, return byte result
      case 'd':

        SPDR = data.b[3];
        break;

      } // end of switch

    }  // end of interrupt service routine (ISR) SPI_STC_vect
    float tiempo=millis();
    void loop (void)
    {

      // if SPI not active, clear current command
      if (digitalRead (SS) == HIGH) command = 0;

        if(millis()>(tiempo+10))
        {
          tiempo=millis();
          SampleGyro(bno);
        }

    }  // end of loop

    void SampleGyro(Adafruit_BNO055 &gyroIMU){
        /* Display the floating  point data */
        imu::Vector<3> euler = gyroIMU.getVector(Adafruit_BNO055::VECTOR_EULER);
        yawInput=euler.x()-yawOffset;

        if (yawInput >= 360)
        {
              yawInput -= 360;
            }
        else
        {if (yawInput < 0)yawInput += 360;
        }
        pitchInput=euler.y();
        //rollInput=fmod((euler.z()+(360+90)), 360)-180;
        rollInput=euler.z();
        uint8_t system, gyro, accel, mag = 0;
        gyroIMU.getCalibration(&system, &gyro, &accel, &mag);
        calibration=system;
    }

Master Code:

    #include <SPI.h>

    #define SS 10
    void setup (void)
    {
        pinMode(MOSI, OUTPUT);
        pinMode(MISO, INPUT);
        pinMode(SCK, OUTPUT);
        pinMode(SS, OUTPUT);

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

      digitalWrite(SS, HIGH);

      SPI.begin ();

      SPI.setClockDivider(SPI_CLOCK_DIV8);
    }

      byte transferAndWait (const byte what)
    {
      byte a = SPI.transfer (what);
      delayMicroseconds (10);
      return a;
    }

      union first_union{
        float f;
        byte b[4];}
      data;

    void loop (void)
    {

      digitalWrite(SS, LOW);

      transferAndWait ('a');

      data.b[0] = transferAndWait ('b');
      data.b[1] = transferAndWait ('c');
      data.b[2] = transferAndWait ('d');
      data.b[3] = transferAndWait (0);

      digitalWrite(SS, HIGH);

      Serial.print("data.f = ");Serial.println(data.f);

      //Serial.print("data.b[0] = ");Serial.println(data.b[0]);
      //Serial.print("data.b[1] = ");Serial.println(data.b[1]);
      //Serial.print("data.b[2] = ");Serial.println(data.b[2]);
      //Serial.print("data.b[3] = ");Serial.println(data.b[3]);

      delay(10);
    }

title: SPI Overflow in 328 slave with i2c sensor

Answers: 1

body:
It is likely that your SPI interrupt on the slave is firing in the middle of updating your global `yawInput` variable. This would cause the value to be partially updated when you send it back to the master. You might even be sending part of the old value and part of the new value back to the master. It depends on when the interrupts fire.

You need to lock your `SampleGyro` function somehow. The easiest way would be to disable interrupts when modifying any interrupt accessible variables (i.e. `yawInput`).

Something like this should tell you if the interrupt timing is the issue:

    void SampleGyro(Adafruit_BNO055 &gyroIMU){
        /* Display the floating  point data */
        imu::Vector<3> euler = gyroIMU.getVector(Adafruit_BNO055::VECTOR_EULER);
        uint8_t system, gyro, accel, mag = 0;
        gyroIMU.getCalibration(&system, &gyro, &accel, &mag);

     // Disable interrupts while modifying the global variable
        noInterrupts()
        yawInput=euler.x()-yawOffset;
        if (yawInput >= 360) {
              yawInput -= 360;
        } else if (yawInput < 0) {
              yawInput += 360;
        }
        pitchInput=euler.y();
        //rollInput=fmod((euler.z()+(360+90)), 360)-180;
        rollInput=euler.z();
        calibration=system;
        // re-enable interrupts once your global variable
        // modification is done.
        interrupts();
    }

It's also worth noting that you want to put as little code between the `noInterrupts()` and `interrupts()` calls as possible. Things like I2C and SPI and basically any other communication will likely not work inside of that block. I rearranged your `SampleGyro` function to put all calls to the gyro outside of the lock. This is to prevent the sensor reading from failing.


body:
My aim is to create a simple obstacle avoiding robot using Arduino.

I have used L293D motor shield to drive the DC motors and supply it all with 12 V. I am using a sonar module to detect the obstacles. I have used an IR Receiver to control the motors of the robot.

From the serial prints I can tell that every IR signal is received and the expected functions are called. Unfortunately, when I press the button to start the motor, the motor does not start.

When I remove IR Receiver and start robot the code works fine.

In my code posted below I have commented some code so that it only calls the `startFan()` function.

What is wrong with my code? And how do I fix it?

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

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

    #include <boarddefs.h>
    #include <IRremote.h>
    #include <IRremoteInt.h>
    #include <ir_Lego_PF_BitStreamEncoder.h>

    #define TRIG_PIN A4
    #define ECHO_PIN A5
    #define MAX_DISTANCE 200
    #define MAX_SPEED 75 // sets speed of DC  motors

    NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

    AF_DCMotor motor1(1, MOTOR12_1KHZ);
    AF_DCMotor motor2(3, MOTOR12_1KHZ);
    AF_DCMotor motor3(2, MOTOR12_1KHZ);

    Servo myservo;

    boolean goesForward = false;
    int distance = 100;
    int speedSet = 0;

    int DisObstaclePin = 0; // This is our input pin
    int DisObstacle = HIGH; // HIGH MEANS NO OBSTACLE

    int receiver = 6; // Signal Pin of IR receiver to Arduino Digital Pin 11
    int power_status ;

    IRrecv irrecv(receiver);           // create instance of 'irrecv'
    decode_results results; // create instance of 'decode_results'

    //----( SETUP: RUNS ONCE )----//
    void setup()
    {
      Serial.begin(9600);
      Serial.println("IR Receiver Button Decode");

      int power_status = 0;
      motor3.setSpeed(150);
      motor3.run(FORWARD);

      pinMode(DisObstaclePin, INPUT);
      myservo.attach(9);
      myservo.write(115);
      delay(1000);

      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      DisObstacle = digitalRead(DisObstaclePin);
      delay(100);

      irrecv.enableIRIn(); // Start the receiver

    }

    void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
    {

      Serial.println("Begin loop");
      delay(1000);
      if (irrecv.decode(&results)) // have we received an IR signal?
      {
        Serial.println("wada");
        translateIR();
        irrecv.resume(); // receive the next value
        delay(500);
      }

     /* else {
        if (power_status == 1) {
          Serial.println("POWER ON");
          int distanceR = 0;
          int distanceL =  0;
          delay(40);
          if (distance <= 25 || DisObstacle == HIGH)
          {
            Serial.print("Turning");
            moveStop();
            delay(100);
            moveBackward();
            delay(300);
            moveStop();
            delay(200);
            distanceR = lookRight();
            delay(200);
            distanceL = lookLeft();
            delay(200);

            if (distanceR >= distanceL)
            {
              turnRight();
              moveStop();
            } else
            {
              turnLeft();
              moveStop();
            }
          } else
          {
            moveForward();
            Serial.print("Forword");
          }
          distance = readPing();
          delay(50);
          DisObstacle = digitalRead(DisObstaclePin);
          delay(50);
        }if (power_status == 0) {
           Serial.print("POWER OFF");
        }
      }
      */

    }/* --(end main loop )-- */

    /*-----( Functions )-----*/
    void translateIR() // takes an action based on the IR code received
    {
      switch (results.value)
      {

        case 0xFF30CF: Serial.println("Movement-ON- 1");
          power_status = 1;
          break;
        case 0xFF18E7: Serial.println("Movement-OFF -2");
          power_status = 0;
          break;
        case 0xFF10EF: Serial.println("Fan-on-3");
          startFan();
          break;
        case 0xFF38C7: Serial.println("Fan-off-4");
          stopFan();
          break;
        default:
          Serial.println(" other button   ");
      }
      delay(500); // Do not get immediate repeat
    } //END translateIR

    int lookRight()
    {
      myservo.write(50);
      delay(500);
      int distance = readPing();
      delay(100);
      myservo.write(115);
      return distance;
    }

    int lookLeft()
    {
      myservo.write(170);
      delay(500);
      int distance = readPing();
      delay(100);
      myservo.write(115);
      return distance;
      delay(100);
    }

    int readPing() {
      delay(70);
      int cm = sonar.ping_cm();
      if (cm == 0)
      {
        cm = 250;
      }
      return cm;
    }

    void moveStop() {
      motor1.run(RELEASE);
      motor2.run(RELEASE);
      delay(100);
    }

    void moveForward() {

      if (!goesForward)
      {
        goesForward = true;
        motor1.run(FORWARD);
        motor2.run(FORWARD);

        motor1.setSpeed(100); //set the speed of the motors, between 0-255
        motor2.setSpeed(100);
        delay(100);
        motor1.setSpeed(55); //set the speed of the motors, between 0-255
        motor2.setSpeed(55);
      }
    }

    void moveBackward() {
      goesForward = false;
      motor1.run(BACKWARD);
      motor2.run(BACKWARD);

      motor1.setSpeed(100); //set the speed of the motors, between 0-255
      motor2.setSpeed(100);
      delay(500);
    }

    void turnRight() {
      motor1.run(FORWARD);
      motor2.run(BACKWARD);
      delay(300);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
    }

    void turnLeft() {
      motor1.run(BACKWARD);
      motor2.run(FORWARD);
      delay(300);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
    }

    void startFan() {
      motor3.setSpeed(150);
      motor3.run(FORWARD);
      Serial.println("FAN  start  ");
      delay(2000);

    }

    void stopFan() {
      motor3.run(RELEASE);
      Serial.println("FAN  stop  ");
      delay(2000);
    }

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

==============After change pin attachment =============================
I will change my code as follow and remove , 0,1 pin attachment sensor. Now code like below.

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

    #include <boarddefs.h>
    #include <IRremote.h>
    #include <IRremoteInt.h>
    #include <ir_Lego_PF_BitStreamEncoder.h>

    #define TRIG_PIN A4
    #define ECHO_PIN A5
    #define MAX_DISTANCE 200
    #define MAX_SPEED 75 // sets speed of DC  motors

    NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

    AF_DCMotor motor1(1, MOTOR12_1KHZ);
    AF_DCMotor motor3(2, MOTOR12_1KHZ);
    AF_DCMotor motor2(3, MOTOR12_1KHZ);

    Servo myservo;

    boolean goesForward = false;
    int distance = 100;
    int speedSet = 0;

    int DisObstaclePin = 2; // This is our input pin
    int DisObstacle = HIGH; // HIGH MEANS NO OBSTACLE

    int receiver = 13; // Signal Pin of IR receiver to Arduino Digital Pin 11
    //int power_on;
    int fan_status,power_on;

    IRrecv irrecv(receiver);           // create instance of 'irrecv'
    decode_results results; // create instance of 'decode_results'

    //----( SETUP: RUNS ONCE )----//
    void setup()
    {
      Serial.begin(9600);
      Serial.println("IR Receiver Button Decode");

      power_on = 1;
      fan_status = 0;

      pinMode(DisObstaclePin, INPUT);
      myservo.attach(9);
      myservo.write(115);
      delay(1000);

      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      DisObstacle = digitalRead(DisObstaclePin);
      delay(100);

      irrecv.enableIRIn(); // Start the receiver

    }

    void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
    {

      Serial.println("Begin loop");
      delay(1000);
      if (irrecv.decode(&results)) // have we received an IR signal?
      {
        Serial.print("Start reciving");
        translateIR();
        irrecv.resume(); // receive the next value
      }

      //delay(2000);
      if (power_on == 1) {
        Serial.println("POWER ON");
        int distanceR = 0;
        int distanceL =  0;
        delay(40);
        if (distance <= 25 || DisObstacle == HIGH)
        {
          Serial.print("Turning");
          moveStop();
          delay(100);
          moveBackward();
          delay(300);
          moveStop();
          delay(200);
          distanceR = lookRight();
          delay(200);
          distanceL = lookLeft();
          delay(200);

          if (distanceR >= distanceL)
          {
            turnRight();
            moveStop();
          } else
          {
            turnLeft();
            moveStop();
          }
        } else
        {
          moveForward();
          Serial.print("Forword");
        }
        distance = readPing();
        delay(50);
        DisObstacle = digitalRead(DisObstaclePin);
        delay(50);
      }

      if (fan_status == 1) {
        startFan();
        delay(50);
      } else {
        stopFan();
        delay(50);
      }

     // irrecv.resume(); // receive the next value
    }/* --(end main loop )-- */

    /*-----( Functions )-----*/
    void translateIR() // takes action based on IR code received
    {
      switch (results.value)
      {
        case 0xFF30CF: Serial.println("Movement-ON- 1");
          //power_on = 1;
          break;
        case 0xFF18E7: Serial.println("Movement-OFF -2");
          //power_on = 0;
          break;
        case 0xFF10EF: Serial.println("Fan-on-3");
          fan_status = 1 ;
          break;
        case 0xFF38C7: Serial.println("Fan-off-4");
          fan_status = 0;
          break;
        default:
          Serial.println(" other button   ");
      }
      delay(500); // Do not get immediate repeat
    } //END translateIR

    int lookRight()
    {
      myservo.write(50);
      delay(500);
      int distance = readPing();
      delay(100);
      myservo.write(115);
      return distance;
    }

    int lookLeft()
    {
      myservo.write(170);
      delay(500);
      int distance = readPing();
      delay(100);
      myservo.write(115);
      return distance;
      delay(100);
    }

    int readPing() {
      delay(70);
      int cm = sonar.ping_cm();
      if (cm == 0)
      {
        cm = 250;
      }
      return cm;
    }

    void moveStop() {
      motor1.run(RELEASE);
      motor2.run(RELEASE);
      delay(100);
    }

    void moveForward() {
      if (!goesForward)
      {
        goesForward = true;
        motor1.run(FORWARD);
        motor2.run(FORWARD);

        motor1.setSpeed(100); //set the speed of the motors, between 0-255
        motor2.setSpeed(100);
        delay(100);
        motor1.setSpeed(55); //set the speed of the motors, between 0-255
        motor2.setSpeed(55);
      }
    }

    void moveBackward() {
      goesForward = false;
      motor1.run(BACKWARD);
      motor2.run(BACKWARD);

      motor1.setSpeed(100); //set the speed of the motors, between 0-255
      motor2.setSpeed(100);
      delay(500);
    }

    void turnRight() {
      motor1.run(FORWARD);
      motor2.run(BACKWARD);
      delay(300);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
    }

    void turnLeft() {
      motor1.run(BACKWARD);
      motor2.run(FORWARD);
      delay(300);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
    }

    void startFan() {
      motor3.setSpeed(30);
      motor3.run(FORWARD);
      Serial.println("FAN start  ");
      delay(100);
    }

    void stopFan() {
      motor3.setSpeed(RELEASE);
      Serial.println("FAN  stop  ");
      delay(100);
    }

Now I notice the M1 motor is not working. My question is also same as this: [ Motor shield question][2] But I couldn't understand how to resolve it using my code. Other trouble I notice, a lot of the time the IR Receiver receives my signal. It executes without noticing a new signal. Sometimes it catches my signal.

  [1]: https://i.stack.imgur.com/1jZO4.png
  [2]: http://help.wickeddevice.com/t/motor-shield-question/87

title: DC motor not start?

Answers: 1

body:
Based on this thread:

 - https://forums.adafruit.com/viewtopic.php?f=31&t=27069
 - https://stackoverflow.com/questions/18705363/arduino-uno-pwm-pins-conflict
 - http://forum.arduino.cc/index.php?topic=97133.0

Both AFmotor library and IRremote are using timer feature. And in addition, IRremote also use TIMER_RESET, which probably causing the motor not function as expected (on comment section)

So the solution available is :

 1. Use another library to drive motor, or you can make you own. See this [tutorial][1].
 2. Edit the library (IRremote or AFmotor) timer configuration (as you can found in the last post of the link I posted)

  [1]: https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM


body:
My problem is an interrupt service routine (ISR) that seemingly never executes! Here's some info on my set up: I am flashing an avr attiny85. I have the bare bones of a project set up so far with simply a main.c and two modules: timer and hardwareInit. In the timer module, I have a timer0_init function that I am using to set up timer0 for CTC mode to overflow ever 1 ms. Here is the function:

    void timer0_init( void )
    {
        cli();
        TCCR0B |= 3;    //clock select is divided by 64.
        TCCR0A |= 2;    //sets mode to CTC
        OCR0A = 0x7C;   //sets TOP to 124 so the timer will overflow every 1 ms.
        TIMSK |= 2;     //Enable overflow interrupt
        sei();          //enable global interrupts
    }

with the timer set up, I added an ISR to increment ticks every time the counter overflows, so I can keep track of how much time has elapsed, etc.

    ISR(TIMER0_OVF_vect)
    {
        cli();
        //ticks ++;
        PORTB |= ( 1 << PORTB0 );
        sei();
    }

as you can see, I commented out the ticks++ because it wasn't working, and replaced it with `PORTB |= ( 1 << PORTB0 );` which simply turns on an LED, so if the interrupt is ever executed, I will know by proof of the LED being on.
Unfortunately, I can't get it to turn on and can't see what I'm missing. (to prove that I 1. have the LED set up on the right pin, and 2. am manipulating the correct bit in the correct register, I put just this statement `PORTB |= ( 1 << PORTB0 );` in my infinite loop and confirmed the LED came on)

For further explanation, here is my main.c:

    /*================================= main.c =================================*/

    #define F_CPU   8000000UL

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

    #include "timer.h"
    #include "hardwareInit.h"

    int main(){

        //Initialize hardware HERE
        DDRB |= ( 1 << PORTB0 );    //set this pin as an output for an LED

        SetClockPrescale(1);    //internal clock divided by 1 = 8 MHz, from hardwareInit

        timer0_init();          //set up timer0 for 1 ms overflow

        while(1)
        {
            /* if( getTicks() > 0 )
            {
                PORTB |= ( 1 << PORTB0 );
                _delay_ms(1000);
                PORTB &= ~( 1 << PORTB0 );
                _delay_ms(1000);
            } */

        }
        return 0;
    }

So, what you see in the infinite loop is what I tried first, but after that didn't work, I tried something simpler, just having an empty loop (commented out previous stuff), and waiting for the interrupt to get triggered which would turn on the LED.

Any help you could give would be really appreciated. I'm quite puzzled why this hasn't been working.

title: AVR timer overflow interrupt not working

Answers: 1

body:
You are misunderstanding what an overflow interrupt is. That is called when the timer overflows (ie. it reaches TOP which in the case of an 8-bit timer is 255). Since you are counting to 124 that will never happen, and thus the interrupt will not fire.

You want the "compare A vector" which is called when the "A" register compares to the limit. Example code:

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

    void timer0_init( void )
    {
        TCCR0B = bit (CS01) | bit (CS00);    //clock select is divided by 64.
        TCCR0A = bit (WGM01);     //sets mode to CTC
        OCR0A = 0x7C;             //what to count to
        TIMSK = bit (OCIE0A);     //Enable compare match A interrupt
    }

    ISR(TIMER0_COMPA_vect)
    {
        PINB = bit (PINB0);   // toggle pin 5
    }

    int main(){

        DDRB |= bit (DDB0);    //set this pin as an output for an LED
        timer0_init();         //set up timer0 for 1 ms overflow
        sei ();                // allow interrupts
        while(true) { }        // forever
        return 0;
    }

I changed it to toggle pin 5 (which happens extremely quickly) so it will seem to be on but a bit dim. You can see on an oscilloscope or logic analyzer that it is toggling rapidly.

You don't need to turn interrupts off or on inside an ISR. You are better off using the bit names rather than "magic numbers" in your code, as my example shows.


body:
I am trying to modify the original code from these guys GRA & AFCH, who have made an Arduino Sketch Program that runs a Arduino powered Nixie Clock.

Here is the link to their Firmware file:[NixieClockShieldNCS314.ino][1]

Here is the specific part I want to modify.
<!-- language-all: lang-cpp -->

    void setup()
    {
      digitalWrite(DHVpin, LOW);    // off MAX1771 Driver  Hight Voltage(DHV) 110-220V

      Wire.begin();
      //setRTCDateTime(23,40,00,25,7,15,1);

      Serial.begin(115200);

        if (EEPROM.read(HourFormatEEPROMAddress)!=12) value[hModeValueIndex]=24; else value[hModeValueIndex]=12;
        if (EEPROM.read(RGBLEDsEEPROMAddress)!=0) RGBLedsOn=true; else RGBLedsOn=false;
        if (EEPROM.read(AlarmTimeEEPROMAddress)==255) value[AlarmHourIndex]=0; else value[AlarmHourIndex]=EEPROM.read(AlarmTimeEEPROMAddress);
        if (EEPROM.read(AlarmTimeEEPROMAddress+1)==255) value[AlarmMinuteIndex]=0; else value[AlarmMinuteIndex]=EEPROM.read(AlarmTimeEEPROMAddress+1);
        if (EEPROM.read(AlarmTimeEEPROMAddress+2)==255) value[AlarmSecondIndex]=0; else value[AlarmSecondIndex]=EEPROM.read(AlarmTimeEEPROMAddress+2);
        if (EEPROM.read(AlarmArmedEEPROMAddress)==255) value[Alarm01]=0; else value[Alarm01]=EEPROM.read(AlarmArmedEEPROMAddress);
        if (EEPROM.read(LEDsLockEEPROMAddress)==255) LEDsLock=false; else LEDsLock=EEPROM.read(LEDsLockEEPROMAddress);
        Serial.print("led lock=");
        Serial.println(LEDsLock);

      pinMode(RedLedPin, OUTPUT);
      pinMode(GreenLedPin, OUTPUT);
      pinMode(BlueLedPin, OUTPUT);

      tone1.begin(pinBuzzer);
      song=parseSong(song);

      pinMode(LEpin, OUTPUT);
      pinMode(DHVpin, OUTPUT);

     // SPI setup

      SPI.begin(); //
      SPI.setDataMode (SPI_MODE3); // Mode 3 SPI
      SPI.setClockDivider(SPI_CLOCK_DIV128); // SCK = 16MHz/128= 125kHz

      //buttons pins inits
      pinMode(pinSet,  INPUT_PULLUP);
      pinMode(pinUp,  INPUT_PULLUP);
      pinMode(pinDown,  INPUT_PULLUP);
      ////////////////////////////
      pinMode(pinBuzzer, OUTPUT);

      //buttons objects inits
      setButton.debounceTime   = 20;   // Debounce timer in ms
      setButton.multiclickTime = 30;  // Time limit for multi clicks
      setButton.longClickTime  = 2000; // time until "held-down clicks" register

      upButton.debounceTime   = 20;   // Debounce timer in ms
      upButton.multiclickTime = 30;  // Time limit for multi clicks
      upButton.longClickTime  = 2000; // time until "held-down clicks" register

      downButton.debounceTime   = 20;   // Debounce timer in ms
      downButton.multiclickTime = 30;  // Time limit for multi clicks
      downButton.longClickTime  = 2000; // time until "held-down clicks" register

      //
      //digitalWrite(DHVpin, HIGH); // on MAX1771 Driver  Hight Voltage(DHV) 110-220V
      //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      doTest();
      //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      if (LEDsLock==1)
        {
          setLEDsFromEEPROM();
        }
      getRTCTime();
      setTime(RTC_hours, RTC_minutes, RTC_seconds, RTC_day, RTC_month, RTC_year);
      digitalWrite(DHVpin, LOW); // off MAX1771 Driver  Hight Voltage(DHV) 110-220V
      setRTCDateTime(RTC_hours,RTC_minutes,RTC_seconds,RTC_day,RTC_month,RTC_year,1); //записываем только что считанное время в RTC чтобы запустить новую микросхему
      digitalWrite(DHVpin, HIGH); // on MAX1771 Driver  Hight Voltage(DHV) 110-220V
      //p=song;
    }

Now, I need to be able to constantly access the standard Serial USB to be able to receive a string from my Raspbery Pi. I was thinking of adding the following after their code in void setup()

    Serial.begin(9600);

Now I doubt this alone could let me constantly listen to input from Serial USB. But how can I make the code not conflict with the EEPROM.read() commands (I believe this takes in the value from an RTC module attached to the kit)

Thus, a simple loop like the following might not work:

    void loop(){
    if (Serial.available()) {
        light(Serial.read() – ‘0’);
    }
    delay(500);
    }

So my question is how can I add functionality such that the Arduino is constantly listening to the Serial port for instructions?

If you are interested in the potential things I want to be able to do with this functionality, please refer to this code: [Potentiall Additions][2]

Thank you

  [1]: https://github.com/afch/NixeTubesShieldNCS314/raw/master/NixieClockShieldNCS314.ino
  [2]: https://github.com/gilgameshskytrooper/NixeTubesShieldNCS314/raw/master/addedCode.cpp

title: I want to modify setup, to also keep the serial USB port opens so I can send strings via a Raspberry Pi

Answers: 0


body:
    #include <Keyboard.h>
    int IRpin = 5;
    int IRpin2 = 6;
    int IRpin3 = 8;
    int IRpin4 = 9;
    int led = 13;

    void setup() {
      Serial.begin(9600);
      //start the serial port
      Keyboard.begin();
      pinMode(led, OUTPUT);
      digitalWrite(led, LOW);
    }

    void loop() {
      float volts = analogRead(IRpin);
      Serial.println("volts1:");
      Serial.println(volts);
      delay(1000);
      if (volts>500.00){
        Keyboard.press(KEY_RIGHT_ARROW);
        Keyboard.releaseAll();
      }
      float voltss = analogRead(IRpin2);
      Serial.println("volts2:");
      Serial.println(voltss);
      delay(1000);
      if (voltss>600.00){
        Keyboard.press(KEY_LEFT_ARROW);
        Keyboard.releaseAll();
      }
      float voltsss = analogRead(IRpin3);
      Serial.println("volts3:");
      Serial.println(voltsss);
      delay(1000);
      if (voltsss > 500.00) {
        Keyboard.press(KEY_UP_ARROW);
        Keyboard.releaseAll();
      }
      float voltssss = analogRead(IRpin4);
      Serial.println("volts4:");
      Serial.println(voltssss);
      delay(500);
      if (voltssss > 600.00) {
        Keyboard.press(KEY_DOWN_ARROW);
        Keyboard.releaseAll();
      }
    }

I connected 4 IR infrared sensors to Pro micro and only 2 of them are working. The other 2 are sending random values.
Connection for all 4 IR sensors.:
IR VCC->Arduino VCC
IR GND -> Arduino GND
Output-> 5,6,8,9

title: 4 IR sensors on Arduino pro micro. 2 are working other aren't

Answers: 1

body:
Pin 5 is not analog pins.

On the pro-micro only pins A0-5 and D4, D6, D8-10, D12 can convert an analog voltage to a value.

Just use the A0-5 pins instead, as that will work on any Arduino.


body:
I'm hoping someone can help me since I've been struggling with this all weekend. I've got 2 nRF24L01+ breakout cards and I'm trying to send data from a ATTiny85 to a Raspberry Pi 3.

My setup is (the attiny85 breadboard has a 3.3V power supply):

[![ATTiny85][1]][1]

[![RaspberryPi3][2]][2]

And the code I'm testing is for the ATTiny85:

    #define CE_PIN 3
    #define CSN_PIN 4

    #include "RF24.h"

    RF24 radio(CE_PIN, CSN_PIN);

    const byte addr[6] = "00001";
    int count = 0;

    void setup() {
      radio.begin();
      radio.openWritingPipe(addr);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();
    }

    void loop(void){
      radio.write( &count, sizeof(count) );
      count++;
      delay(1000);
    }

And for the Raspberry Pi 3:

    #include <cstdlib>
    #include <iostream>
    #include <sstream>
    #include <string>
    #include <unistd.h>
    #include <RF24/RF24.h>

    using namespace std;

    // Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 8Mhz
    RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ);

    // Radio pipe addresses for the 2 nodes to communicate.
    const uint8_t addr[6] = "00001";

    int main(int argc, char** argv){
      radio.begin();
      radio.setPALevel(RF24_PA_MIN);
      radio.openReadingPipe(1, addr);
      radio.startListening();

      // Dump the configuration of the rf unit for debugging
      radio.printDetails();

      int count = 0;

      while (1)
      {
        while ( radio.available() )
        {
          radio.read( &count, sizeof(count) );
          printf("Count: %d\n", count);
        }
        sleep(1);
      }

      return 0;
    }

  [1]: https://i.stack.imgur.com/zqUPP.png
  [2]: https://i.stack.imgur.com/qibQr.png

title: Connection between ATTiny85 and RaspberryPi3 with nRF24L01+

Answers: 1

body:
As Mikael Patel pointed out, my MOSI and MISO pins were switched.

On the pinout for the ATtiny85, the MOSI and MISO pins are for when the chip is a slave (i.e. programming). DO and DI and used for output as SPI master.

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

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


body:
As the answers to [this question][1] and [this one][2] state, `setup()` and `loop()` are identical in the way they execute code (apart from the obvious looping function of `loop()`).

However.

I get different results with following two pieces of code:
###Code run once, in `setup()`###

    /*
     * light_ws2812 library test
     */

    #include <WS2812.h>

    WS2812 LED(1); // 1 LED

    cRGB value;

    void setup() {
        LED.setOutput(13); // Digital Pin 13

        value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Yellow?
        LED.set_crgb_at(0, value); // Set value at LED found at index 0
        LED.sync(); // Sends the value to the LED
    }

    void loop() {
    }

###Code run once, in `loop()`###

    /*
     * light_ws2812 library test
     */

    #include <WS2812.h>

    WS2812 LED(1); // 1 LED

    cRGB value;

    bool hasBeenSet = false;

    void setup() {
     LED.setOutput(13); // Digital Pin 13
    }

    void loop() {
      if (hasBeenSet == false){
       value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Red
       LED.set_crgb_at(0, value); // Set value at LED found at index 0
       LED.sync(); // Sends the value to the LED
        hasBeenSet = true;
      }
    }

###The difference:###

The code run in `setup()` makes the LED _flash once_ with the desired color.

The code run in `loop()` makes the LED _stay lit_ with the desired color.

With the data being transmitted on pin 13, I can tell (because of the LED on there) in both cases data is being sent only once. With the `loop()` version I can even disconnect the data line after the color has been set, and it will stay lit.

I can only conclude the same code is executed differently in both cases.

Is there some sort of (soft) power reset after `setup()`? That could be a potential cause, as the color is stored in volatile memory on the WS2812B (if I'm not mistaken).

Link to the library used: [http://github.com/cpldcpu/light_ws2812][3]

  [1]: https://arduino.stackexchange.com/questions/4039/is-setup-and-loop-provided-for-convenience
  [2]: https://arduino.stackexchange.com/questions/142/code-for-one-time-execution-in-arduino
  [3]: http://github.com/cpldcpu/light_ws2812

title: Same code in setup() and loop() give different results

Answers: 2

body:
As you can see in the [source code][1] there is really nothing going on between the setup call and the first loop iteration.

If I'm not mistaken, this type of LED needs a frequent "update" on which color to display, at a precisely timed interval (I suppose this gets more important the more LEDs you have, since they are "addressed" bases on this signal timing.)

I think you really should keep calling `sync()` in the loop even if you are not actually changing the desired color, to keep "refreshing" the LED. This is just based of a quick analysis of the library code and examples though.

Why you get different results in the samples below could simply be due to the LED randomly "settling" in two different states when no longer getting data. The chst conversation seems to indicate there may have been other reasons as well.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino "source code"

body:
After [some discussion](http://chat.stackexchange.com/rooms/48846/discussion-between-nick-gammon-and-dajf) it turned out to be a hardware problem. For the sake of completeness I'll outline the suggestions I made.

* There was some initial confusion (see the edits) where the `hasBeenSet` flag was initialized the wrong way around.
* I could not reproduce the problem on my Uno and my WS2812 chip, so the issue was: what was different between his setup and mine?
* Possible wiring issue. Make sure +5V, Gnd and Din (data in) are wired correctly.
* Possibly faulty WS2812 chip - try with another one.
* Possibly faulty Arduino - try with another one.
* Possibly Arduino running at the wrong clock speed which would throw the timings out.
* Possible extra components (eg. capacitors) added to the circuit which were throwing timing out.
* Possible bug in the library. We eliminated that by trying with [my library for Neopixels](https://www.gammon.com.au/forum/?id=13357).

In the end DaJF reported that the problem was solved by using another (or no) breadboard. It seems the breadboard was introducing issues, maybe noise or bad connections.

We never really worked out why doing it in `loop` rather than `setup` made such a difference. I can only conclude that the slight timing difference compensated for the bad connections (or capacitance) on the breadboard.

I'm going to stick my neck out a bit and suggest that the capacitance in the breadboard was affecting the "shape" of the signal (we are talking about timings of around 350 ns here). Possibly if you measured with an oscilloscope you would see the problem.


body:
im trying to arrange the vector in descending order but its not happening..

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

    int fibonacci[15]={0, 1};
    int a=0;

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

      for (int i=0; i<=14; i++) //loop to create the array
      {
        fibonacci[i+2]=(fibonacci[i])+(fibonacci[i+1]);
      }

      //Now arrange in descending order
      for (int i=0; i<16; i++)
      {
        for (int j=i+1; j<16; j++)
        {
          if (fibonacci[i]>fibonacci[j])
          {
            a=fibonacci[i]; //mux number
            fibonacci[i]=fibonacci[j];
            fibonacci[j]=a;
          }
        }
      }

      for (int k=0; k<16; k++)
      {
        Serial.println(fibonacci[k]);
      }
    }

    void loop() {
    }

title: arrange vector in descending order

Answers: 2

body:
I guess that what you want is a descending sort algorithm, but in the case of Fibonacci numbers you can take advantage that they are already sorted at the beginning. Here are different strategies that you can try :

    /*
      SORTING IN DESCENDING ORDER
    */

    const int nbElem = 15; // 24 max
    int fibonacci[ nbElem ] = { 0, 1 };

    void createFibonacciArray( int inputArray[], int arraySize )
    {
      fibonacci[ 0 ] = 0;
      fibonacci[ 1 ] = 1;
      for( int i=0; i<nbElem-2; i++ )
        fibonacci[ i+2 ] = fibonacci[ i ] + fibonacci[ i+1 ];
    }

    void displayArray( int inputArray[], int arraySize )
    {
      for( int i=0; i<arraySize; i++ )
        Serial.println( inputArray[ i ] );
    }

    void displayArrayReverse( int inputArray[], int arraySize )
    {
      for( int i=arraySize-1; i>=0; i-- )
        Serial.println( inputArray[ i ] );
    }

    void reverseArray( int inputArray[], int arraySize )
    {
      for( int i=0; i<nbElem/2; i++ )
      {
        int fTemp = fibonacci[ i ];
        fibonacci[ i ] = fibonacci[ nbElem-i-1 ];
        fibonacci[ nbElem-i-1 ] = fTemp;
      }
    }

    void inverseBubbleSort( int inputArray[], int arraySize )
    {
      for( int i=0; i<arraySize-1; i++ )
      {
        for( int j=0; j<arraySize-1-i; j++ )
        {
          if( inputArray[ j ] < inputArray[ j+1 ] )
          {
            int temp = inputArray[ j+1 ];
            inputArray[ j+1 ] = inputArray[ j ];
            inputArray[ j ] = temp;
          }
        }
      }
    }

    void bubbleSort( int inputArray[], int arraySize )
    {
      for( int i=0; i<arraySize-1; i++ )
      {
        for( int j=0; j<arraySize-1-i; j++ )
        {
          if( inputArray[ j ] > inputArray[ j+1 ] )
          {
            int temp = inputArray[ j+1 ];
            inputArray[ j+1 ] = inputArray[ j ];
            inputArray[ j ] = temp;
          }
        }
      }
    }

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

      // Create and display Fibonacci array
      createFibonacciArray( fibonacci, nbElem );
      Serial.print( "\n\nFIBONACCI ARRAY\n" );
      Serial.print( "===============\n" );
      displayArray( fibonacci, nbElem );

      // Solution 1: Display array starting from the end
      Serial.print( "\n\nFIBONACCI ARRAY STARTING FROM THE END\n" );
      Serial.print( "=====================================\n" );
      displayArrayReverse( fibonacci, nbElem );

      // Solution 2: Reverse array
      reverseArray( fibonacci, nbElem );
      Serial.print( "\n\nFIBONACCI REVERSED ARRAY\n" );
      Serial.print( "========================\n" );
      displayArray( fibonacci, nbElem );

      // Solution 3: Inverse bubble sort array
      createFibonacciArray( fibonacci, nbElem );
      inverseBubbleSort( fibonacci, nbElem );
      Serial.print( "\n\nFIBONACCI SORTED IN DESCENDED ORDER WITH BUBBLE SORT\n" );
      Serial.print( "====================================================\n" );
      displayArray( fibonacci, nbElem );

      // Ascending order sort array
      bubbleSort( fibonacci, nbElem );
      Serial.print( "\n\nFIBONACCI SORTED WITH BUBBLE SORT\n" );
      Serial.print( "=================================\n" );
      displayArray( fibonacci, nbElem );
    }

    void loop()
    {}

body:
You can use it using bubble sort algorithm (which is most simple but inefficient)

    int fibonacci[15]={0, 1};
    int a=0;

    int arraysize=2; // variable to store size or array

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

      for (int i=0; i<=14; i++) //loop to create the array
      {
        fibonacci[i+2]=(fibonacci[i])+(fibonacci[i+1]);
     arraysize++;
      }

      //Now arrange in descending order using bubble sort
      for (int i=0; i<arraysize; i++)
      {
        for (int j=0; j<arraysize-1; j++)
        {
          if (fibonacci[j]<fibonacci[j+1])
          {
            a=fibonacci[j+1]; //max number
            fibonacci[j+1]=fibonacci[j];
            fibonacci[j]=a;
          }
        }
      }
      //------------------------------------------------

      for (int k=0; k<16; k++)
      {
        Serial.println(fibonacci[k]);
      }
    }


body:
I want to build a temperature control network over my house reading data from each room and sending it to the main board for further processing. I need about 6 sensor nodes sending the data over the air to the main node.
There are tons of tutorials of making master-slave temperature/pressure etc control systems of 2 Arduino boards communicating via wireless channel.
I find it a bit expensive to have a board per sensor node. **Is that possible to build a sensor device without a controller using just a sensor, a battery and a wireless transmitter plus required radio components?** It's ok to send raw data to the main node. Assuming it knows the protocol it will be able to decode the data there from all the incoming channels.

title: Remote temperature sensor system without slave board

Answers: 2

body:
As @Majenko said on comment, its possible. One of the choice is ESP8266. Your project has been successfully accomplished, you can check [here][1], [here][2], or [here][3]. NSP8266 only needs 3-3.6V (low current) supply voltage.

  [1]: https://github.com/astoklas/ESP8266-Temperature-Sensor
  [2]: http://www.instructables.com/id/Low-cost-WIFI-temperature-data-logger-based-on-ESP/
  [3]: https://forum.mysensors.org/topic/2519/temperature-sensor-on-esp8266/10

body: @Sergey if its cost what's bothering you , there are numerous low-cost options for MCUs. For eg you can club a MSP 430 ( probably <1$) chip with a cheap RF transmitter which wont burn a hole in your pocket and is absolutely reliable. Wifi modules can be a little expensive and need constant connectivity. So, you have a choice on this.


body:
I am working on a project that records the elevation changes of a 1 foot wide section using sonar distance measurement. I have 10 HC-SR04 sensors arranged in a straight line over this 1 foot section.

The issue I am having is that when I send an output from my sonar sensor, I must wait until the return signal is recorded before I can trigger the next sonar sensor to take a measurement. This is rather slow and decreases the sampling frequency significantly. I need each sonar sensor to take 1000 measurements per second for my project.

Is there a way to have the HC-SR04 sensors simultaneously output and listen for the return signal? I would want all 10 sensors to send a 40 kHz pulse at the same time, and then when a return signal is recorded, another 40 kHz pulse is sent out.

The average distance to the 1 foot wide section is about 11 inch. If the Arduino is limited and there are other control boards that can accomplish this, it would help a lot if you can point me in the right direction.

title: Simultaneous output from sonar array

Answers: 1

body:
1000 measurement for 10 sensors per seconds, it means there are 10000 measurement per sec with 0.1 mS time slot for each measurement.

According to [SRF-04 Documentation][1],

**(1)**
> If nothing is detected then the SRF04 will lower its echo line anyway after about 36mS.

So, **time slot for each reading is 36 mS** ("if" nothing is detected), which means for 10 SRF04 x 1000 reading, it will take 360000 mS = **360 Sec**.

**(2)**

> I would want all 10 sensors to send a 40kHz pulse at the same time, and then when a return signal is recorded, another 40kHz pulse is sent out.

Its seems reasonable. **But**,
[![enter image description here][2]][2]
According to the timing diagram, 1 cycle minimum period consist of :

 1. 100 us Trigger pulse ==> 0.0001 s
 2. 8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
 3. 100 us Echo pulse ==> 0.0001 s
 4. 10 ms delay time ==> 0.01 s

Total for 1 cycle is 0.0104 s, so for **1000 readings x 10 sensors (object to detect is present) will be 104 s**.

All sensor burst at the same frequency, great idea. **However** it's not advised (or rather not possible) because that will disturb each sensor reading unless you successfully change each sensors frequency or doing sound modulation. Even if you success in modulating 10 sensors frequency, the needed time is still not met 1 s interval

 1. 100uS for 10 sensors trigger pulse at once ==> 0.0001 s
 2. 8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
 3. 100 us (minimum) Echo pulse --> 0.0001 s x 10 sensors ==> 0.001 s, because Arduino does not support threading, which mean there is no way you can read all at same time
 4. 10 ms delay time ==> 0.01 s

Time for 1 cycle (10 sensors reading): 0.0113, **1000 readings : 11.3 s**

**(3)**

  "How about changing the beam pattern?"

> **Changing beam pattern and beam width**
You can't! This is a question which crops up regularly, however there is no easy way to reduce or change the beam width that I'm aware of. The beam pattern of the SRF04 is conical with the width of the beam being a function of the surface area of the transducers and is fixed.

So, rather than trying to modify the ultrasonic, more reasonable solution is changing the way you do elevation measurement.

  [1]: https://www.robot-electronics.co.uk/htm/srf04tech.htm
  [2]: https://i.stack.imgur.com/XMim8.gif


body:
I want to run an arduino out in the cold (-40), and use the serial communication - I believe that the crystal is the weakest link (the one for the serial chip) - however I don't see any drop-in (through-hole) replacement crystals that would work in such cold, so would a SMT version work instead? if so, which one would be possible to solder (package?), and do I need to change the caps to match?

P.S. - Yes, I could heat it/insulate it, but that comes at a fairly high power/complexity cost

title: Replacement crystal on Uno for cold temperatures

Answers: 1

body:
There is a solution for just this problem, it's a "crystal oven". It is used to keep a crystal at a constant temperature so that the oscillating ferquency remains very stable.

Crystal ovens are usually expensive as they are quite precise and have good insultaion, but here's a kit that you might adapt for your uses: http://www.minikits.com.au/Oscillator-Heater, or google around to see if you find something that might suit you better.

You could also consider making a heater with a simple temperature regulator of your own to keep the crystal warm  (many temperature sensors for Arduino are available on the web).


body:
When I make any GET request to my shield, the only thing I get when I read the request is '\r\n'.  I am sending query parameters, and when the request has been read in the past, there was the full http request.

EDIT:  Could this be due to some memory issue?  It seems to be fairly non-deterministic when it fails, and I have 69% of memory taken when the program starts.

    /************************************************************
    ESP8266_Shield_Demo.h
    SparkFun ESP8266 AT library - Demo
    Jim Lindblom @ SparkFun Electronics
    Original Creation Date: July 16, 2015
    https://github.com/sparkfun/SparkFun_ESP8266_AT_Arduino_Library

    This example demonstrates the basics of the SparkFun ESP8266
    AT library. It'll show you how to connect to a WiFi network,
    get an IP address, connect over TCP to a server (as a client),
    and set up a TCP server of our own.

    Development environment specifics:
      IDE: Arduino 1.6.5
      Hardware Platform: Arduino Uno
      ESP8266 WiFi Shield Version: 1.0

    This code is released under the MIT license.

    Distributed as-is; no warranty is given.
    ************************************************************/

    //////////////////////
    // Library Includes //
    //////////////////////
    // SoftwareSerial is required (even you don't intend on
    // using it).
    #include <SoftwareSerial.h>
    #include <SparkFunESP8266WiFi.h>

    //////////////////////////////
    // WiFi Network Definitions //
    //////////////////////////////
    // Replace these two character strings with the name and
    // password of your WiFi network.
    const char mySSID[] = "ssid";
    const char myPSK[] = "pass";

    const short out1 = 10;
    const short out2 = 11;
    const short out3 = 12;
    const short out4 = 13;

    bool on1 = false;
    bool on2 = false;
    bool on3 = false;
    bool on4 = false;

    //////////////////////////////
    // ESP8266Server definition //
    //////////////////////////////
    // server object used towards the end of the demo.
    // (This is only global because it's called in both setup()
    // and loop()).
    ESP8266Server server = ESP8266Server(80);

    //////////////////
    // HTTP Strings //
    //////////////////
    const String html = "HTTP/1.1 200 OK\r\n"
                              "Content-Type: text/html\r\n"
                              "Connection: close\r\n\r\n"
                              "<!DOCTYPE HTML>\r\n"
                              "\r\n"
                              "<link rel=\"icon\" href=\"data:,\">\r\n"
                              "<button>Toggle 1</button>\r\n"
                              "<button>Toggle 2</button>\r\n"
                              "<button>Toggle 3</button>\r\n"
                              "<button>Toggle 4</button>\r\n"
                              "\r\n";

    // All functions called from setup() are defined below the
    // loop() function. They modularized to make it easier to
    // copy/paste into sketches of your own.
    void setup()
    {
      // Set pins
      pinMode(out1, OUTPUT);
      pinMode(out2, OUTPUT);
      pinMode(out3, OUTPUT);
      pinMode(out4, OUTPUT);

      digitalWrite(out1, LOW);
      digitalWrite(out2, LOW);
      digitalWrite(out3, LOW);
      digitalWrite(out4, LOW);

      // Serial Monitor is used to control the demo and view
      // debug information.
      Serial.begin(9600);

      // initializeESP8266() verifies communication with the WiFi
      // shield, and sets it up.
      initializeESP8266();

      // connectESP8266() connects to the defined WiFi network.
      connectESP8266();

      // displayConnectInfo prints the Shield's local IP
      // and the network it's connected to.
      displayConnectInfo();

      serverSetup();
    }

    void loop()
    {
      serverDemo();
    }

    void initializeESP8266()
    {
      // esp8266.begin() verifies that the ESP8266 is operational
      // and sets it up for the rest of the sketch.
      // It returns either true or false -- indicating whether
      // communication was successul or not.
      // true
      int test = esp8266.begin();
      if (test != true)
      {
        Serial.println(F("Error talking to ESP8266."));
        errorLoop(test);
      }
      Serial.println(F("ESP8266 Shield Present"));
    }

    void connectESP8266()
    {
      // The ESP8266 can be set to one of three modes:
      //  1 - ESP8266_MODE_STA - Station only
      //  2 - ESP8266_MODE_AP - Access point only
      //  3 - ESP8266_MODE_STAAP - Station/AP combo
      // Use esp8266.getMode() to check which mode it's in:
      int retVal = esp8266.getMode();
      if (retVal != ESP8266_MODE_STA)
      { // If it's not in station mode.
        // Use esp8266.setMode([mode]) to set it to a specified
        // mode.
        retVal = esp8266.setMode(ESP8266_MODE_STA);
        if (retVal < 0)
        {
          Serial.println(F("Error setting mode."));
          errorLoop(retVal);
        }
      }
      Serial.println(F("Mode set to station"));

      // esp8266.status() indicates the ESP8266's WiFi connect
      // status.
      // A return value of 1 indicates the device is already
      // connected. 0 indicates disconnected. (Negative values
      // equate to communication errors.)
      retVal = esp8266.status();
      if (retVal <= 0)
      {
        Serial.print(F("Connecting to "));
        Serial.println(mySSID);
        // esp8266.connect([ssid], [psk]) connects the ESP8266
        // to a network.
        // On success the connect function returns a value >0
        // On fail, the function will either return:
        //  -1: TIMEOUT - The library has a set 30s timeout
        //  -3: FAIL - Couldn't connect to network.
        retVal = esp8266.connect(mySSID, myPSK);
        if (retVal < 0)
        {
          Serial.println(F("Error connecting"));
          errorLoop(retVal);
        }
      }
    }

    void displayConnectInfo()
    {
      char connectedSSID[24];
      memset(connectedSSID, 0, 24);
      // esp8266.getAP() can be used to check which AP the
      // ESP8266 is connected to. It returns an error code.
      // The connected AP is returned by reference as a parameter.
      int retVal = esp8266.getAP(connectedSSID);
      if (retVal > 0)
      {
        Serial.print(F("Connected to: "));
        Serial.println(connectedSSID);
      }

      // esp8266.localIP returns an IPAddress variable with the
      // ESP8266's current local IP address.
      IPAddress myIP = esp8266.localIP();
      Serial.print(F("My IP: ")); Serial.println(myIP);
    }

    void serverSetup()
    {
      // begin initializes a ESP8266Server object. It will
      // start a server on the port specified in the object's
      // constructor (in global area)
      server.begin();
      Serial.print(F("Server started! Go to "));
      Serial.println(esp8266.localIP());
      Serial.println();
    }

    void serverDemo()
    {
      // available() is an ESP8266Server function which will
      // return an ESP8266Client object for printing and reading.
      // available() has one parameter -- a timeout value. This
      // is the number of milliseconds the function waits,
      // checking for a connection.
      ESP8266Client client = server.available(500);

      if (client)
      {
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        String req;
        while (client.connected())
        {
          if (client.available())
          {
            char c = client.read();
            req += c;
            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank)
            {
              Serial.println(req);
              if (req.indexOf("toggle=1") != -1){
                if (on1){
                  Serial.println(F("TURN 1 ON"));
                  digitalWrite(out1, LOW);
                }
                else {
                  Serial.println(F("TURN 1 OFF"));
                  digitalWrite(out1, HIGH);
                }
                on1 = !on1;
              }
              else if (req.indexOf("toggle=2") != -1){
                if (on2){
                  digitalWrite(out2, LOW);
                  Serial.println(F("TURN 2 OFF"));
                }
                else {
                  Serial.println(F("TURN 2 ON"));
                  digitalWrite(out2, HIGH);
                }
                on2 = !on2;
              }
              else if (req.indexOf("toggle=3") != -1){
                if (on3){
                  Serial.println(F("TURN 3 OFF"));
                  digitalWrite(out3, LOW);
                }
                else {
                  Serial.println(F("TURN 3 ON"));
                  digitalWrite(out3, HIGH);
                }
                on3 = !on3;
              }
              else if (req.indexOf("toggle=4") != -1){
                if (on4){
                  Serial.println(F("TURN 4 OFF"));
                  digitalWrite(out4, LOW);
                }
                else {
                  Serial.println(F("TURN 4 ON"));
                  digitalWrite(out4, HIGH);
                }
                on4 = !on4;
              }

              // send html
              client.print(html);
              break;
            }
            if (c == '\n')
            {
              // you're starting a new line
              currentLineIsBlank = true;
            }
            else if (c != '\r')
            {
              // you've gotten a character on the current line
              currentLineIsBlank = false;
            }
          }
        }
        // give the web browser time to receive the data
        delay(1);

        // close the connection:
        client.stop();
      }

    }

    // errorLoop prints an error code, then loops forever.
    void errorLoop(int error)
    {
      Serial.print(F("Error: ")); Serial.println(error);
      Serial.println(F("Looping forever."));
      for (;;)
        ;
    }

title: Sparkfun ESP8266 Wifi Shield does not receive data

Answers: 2

body:
In `serverDemo()` you are setting `currentLineIsBlank` to `true`. Then you are reading in each char until you get to a `\n` at which point you are assuming the http request has ended.

    boolean currentLineIsBlank = true;
    ....

    // if you've gotten to the end of the line (received a newline
    // character) and the line is blank, the http request has ended,
    // so you can send a reply
    if (c == '\n' && currentLineIsBlank)

I think you want to set `currentLineIsBlank` to `false` to begin with ?...

body: It's an issue using String with arduino.  I've changed to use char[] and now it is working fine.


body:
I'm using an RTC DS1307 to keep track of time for long periods. It seems to be stuck in a function. I'm using the RTClib suggested by adafruit.

How can I get it unstuck and get values returned? Are there any debugging or troubleshooting tips that would be helpful?

Referencing this excerpt for the code I'm running.

    void setup () {
      while (!Serial); // for Leonardo/Micro/Zero

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

      if (! rtc.isrunning()) { //// **Where I think my code errors.**
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
        // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
      }
    }

This is the example code modified slightly to increase logging, included with RTClib. It's for the DS1307.

Currently the output from the serial port is as follows:

>RTC is found.

I changed the code to the below:

        // Date and time functions using a DS1307 RTC connected via I2C and Wire lib
        #include <Wire.h>
        #include "RTClib.h"

        RTC_DS1307 rtc;

        char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

        void setup () {
          while (!Serial); // for Leonardo/Micro/Zero

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

          if (! rtc.isrunning()) {
            Serial.println("RTC is NOT running!");
            // following line sets the RTC to the date & time this sketch was compiled
            // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
            // This line sets the RTC with an explicit date & time, for example to set
            // January 21, 2014 at 3am you would call:
            // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
          } else {
            Serial.println("RTC is RUNNING.");
          }
        }

        void loop () {
            DateTime now = rtc.now();

            Serial.print(now.year(), DEC);
            Serial.print('/');
            Serial.print(now.month(), DEC);
            Serial.print('/');
            Serial.print(now.day(), DEC);
            Serial.print(" (");
            Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
            Serial.print(") ");
            Serial.print(now.hour(), DEC);
            Serial.print(':');
            Serial.print(now.minute(), DEC);
            Serial.print(':');
            Serial.print(now.second(), DEC);
            Serial.println();

            Serial.print(" since midnight 1/1/1970 = ");
            Serial.print(now.unixtime());
            Serial.print("s = ");
            Serial.print(now.unixtime() / 86400L);
            Serial.println("d");

            // calculate a date which is 7 days and 30 seconds into the future
            DateTime future (now + TimeSpan(7,12,30,6));

            Serial.print(" now + 7d + 30s: ");
            Serial.print(future.year(), DEC);
            Serial.print('/');
            Serial.print(future.month(), DEC);
            Serial.print('/');
            Serial.print(future.day(), DEC);
            Serial.print(' ');
            Serial.print(future.hour(), DEC);
            Serial.print(':');
            Serial.print(future.minute(), DEC);
            Serial.print(':');
            Serial.print(future.second(), DEC);
            Serial.println();

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

title: My RTC DS1307 isn't returning any information. It seems to be stuck in the isrunning() function. Does anyone have debugging tips?

Answers: 2

body:
First thing I see is the Serial setup seems a bit backward:

      while (!Serial); // for Leonardo/Micro/Zero
      Serial.begin(57600);

First, begin Serial; then wait for it to become ready:

      Serial.begin(57600);
      while (!Serial); // for Leonardo/Micro/Zero

Next, is this while(1); inside the if statement:

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

Which says "if !rtc.begin(), then println and go into an infinite loop that does nothing".

Try:

    while (!rtc.begin()) {
        Serial.println("Couldn't find RTC");
        //delay(500);  // depending on how fast you want this thing to retry/print
    }

the final thing I see, is the next section of code appears like it might be "work code" but is in the setup() function and is missing any kind of a loop.  So it's going to run the if statement once, then setup() exits (and loop() starts getting called).

Either replace the "if" with a "while" and wait for "rtc.running()"

    while (!rtc.running()); // Waiting for RTC to be running
    // Set the clock time

or move it out of setup() and put it inside loop()

    void loop() {
      if (! rtc.isrunning()) { //// **Where I think my code errors.**
        Serial.println("RTC is NOT running!");
        // Perhaps try and fix it?
      } else {
        // If the time hasn't been set; set it; then move on
      }
    }

body:
Wow, that was hard to figure out. My RTC DS1307 came with an extra pin. This tripped me up when wiring the circuitry. I was off by a pin on my breadboard. Thank you everyone for your help.

Specifically, I had the ground going to the empty pin, and the 5v line going to the ground. Perhaps the circuitry allowed some current to go from the ground up and triggered the "i am here" part of the circuitry.


body:
I am using Arduino UNO/MEGA, I want to

    analogWrite(pin, val);

where the value is 0-1023.

How can I make that ?

Thanks.

title: ArduinoUNO/MEGA, Is there a way to exceed 256 in analogWrite

Answers: 4

body:
The simplest way is to change your value range to 0-255. You can't change analogWrite's range, since that is fixed in the core software.

    analogWrite(5, val >> 2);

The `>> 2` bit-shifts the value two bits to the right, turning a 10-bit value (0-1023) into an 8-bit value (0-255). It's by far the most efficient way of dividing by 4.

On more complex 32-bit boards, like the Arduino Due, or the chipKIT range of boards, etc, you have the function [analogWriteResolution()](https://www.arduino.cc/en/Reference/AnalogWriteResolution) which can change the range, but that cannot be done on the 8-bit boards.

From what I have read online it looks like the ATMega chips may support higher resolutions for PWM - however there is no support in the core for that. If you need a higher resolution for some specific reason then you will need to program the registers manually yourself and not rely on the Arduino API to do the work for you. For that you will need to consult the datasheet for your chosen chip.

body:
I agree with @Majenko's answer, though here is a more "beginner" friendly method of doing the same.

    val = map(val,0,1023,0,255);
    analogWrite(pin, val);

Not the most efficient, but still...

body:
Section 16, "16-bit Timer/Counter1 with PWM" of *[Atmel-8271J-AVR- ATmega-Datasheet_11/2015][1]* describes using Timer/Counter-1 for 16-bit PWM, including sample code in both C and assembler. It might take a couple of reads over that section to get familiar with the hardware and learn what else T/C-1 is used for, and that you might have to give up while using it for PWM, but the code is fairly straightforward.

Using this T/C would give you 2-bits more resolution in your PWM output than mapping onto an 8-bit counter, if that is what your project needs.

+1 for the question. Not having needed PWM output for anything more than a demo with my DMM (yet), it hadn't occurred to me to look for a higher resolution until now.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

body:
The other questions so far have correctly addressed one possible meaning of this question, "how can I increase the resolution?"  Here's another possible interpretation.

# How can I increase the output magnitude?

It sounds like you might want to output a higher maximum voltage than what you get from using `analogWrite(pin,255)` on the Uno or Mega.  This is not possible using the Arduino by itself, because PWM represents a fraction of the maximum output, not an absolute value.

On the Uno and Mega, that maximum output is 5V, so the approximate values come out to:

    analogWrite(pin,0);   // (0 / 255) * 5V   (0% of 5V == 0V)
    analogWrite(pin,127); // (127 / 255) * 5V (50% of 5V == 2.5V)
    analogWrite(pin,255); // (255 / 255) * 5V (100% of 5V == 5V)

If you want to make a higher absolute voltage, you will need an external power source and a method of translating the 0-5V output into another voltage range.  This is called "level shifting" and there are standalone ICs which can do this job.  Motor drivers and H-Bridge devices utilize this principle as well.

If you use some sort of level shifting circuitry, then you can map the analogWrite to a different range, such as 0-20V:

    analogWrite(pin,0);   // (0 / 255) * 20V   (0V)
    analogWrite(pin,127); // (127 / 255) * 20V (10V)
    analogWrite(pin,255); // (255 / 255) * 20V (20V)


body:
my plan is to create a two dimensional array with 3 characters in each cell.

what i have tried:

    char keys[3][8][8] = {
      {' ','4','5','6','x','/',' ',' '},
      {'x10','7','8','9',' ',' ',' ',' '},
      {'.','rcl','eng','(',')','sd','m+','^2'},
      {'0','(-)','..,,','hyp','sin','cos','tan','hyp'},
      {' ','br','wur','^2','^x','log','ln',' '},
      {' ',' ',' ',' ',' ','mode','log',' '},
      {'=',' ',' ',' ',' ',' ','^3',' '},
      {'=','1','2','3','+','-',' ',' '}
    };

unfortunatelly this gives me the error:

> error: too many initializers for 'char [3][8][8]'

so what is wrong?

title: two dimensional array with 3 characters per entry?

Answers: 1

body:
> error: too many initializers for 'char [3][8][8]'

The order is wrong:

    char keys[8][8][3]

But then some of the literals are larger than int and give a warning as they are truncated.

Easiest is to define as string literals:

    const char* keys[8][8] = {
      {" ","4","5","6","x","/"," "," "},
      {"x10","7","8","9"," "," "," "," "},
      {".","rcl","eng","(",")","sd","m+","^2"},
      {"0","(-)","..,,","hyp","sin","cos","tan","hyp"},
      {" ","br","wur","^2","^x","log","ln"," "},
      {" "," "," "," "," ","mode","log"," "},
      {"="," "," "," "," "," ","^3"," "},
      {"=","1","2","3","+","-"," "," "}
    };

This can be further improved (stored in program memory, etc).

Cheers!


body:
I am new to coding and this website so I apologize if I make any mistakes. I am trying to get servos to move when a random number is generated. Like if I roll a 2 I want servos 1, 2 and 3 to open and then if I roll a 3 after I want servos 4, 5 and 6 to open. I am able to hold the previous values in the code now but can't get the servos to go with it. Any help is great! Thanks!

    #include <Servo.h>

    Servo myservo;

    int pos = 0;    // variable to store the servo     position
    int x = 0;
    int button = 8;
    int BUTTON;
    int randomNumber;
    int xPrevious = 0;
    int oldNumber;

    void setup() {
    pinMode(button, INPUT);
    Serial.begin(9600);
    }

    void loop() {

    BUTTON = digitalRead(button);
    Serial.println(BUTTON);
     if(BUTTON == LOW){
      randomNumber = random(1,4);
      delay(275);
      Serial.print("Random Number ");
     Serial.println(randomNumber);
     if( xPrevious == 0) {
       randomNumber = randomNumber + 1;
     }

      // Only want it to do this on the first roll.
         xPrevious = randomNumber + xPrevious;
         Serial.print("xPrevious ");
         Serial.println(xPrevious);
        oldNumber = xPrevious;

     for (x = randomNumber; x <= xPrevious; x += 1) {
      myservo.attach(x);
      Serial.println(x);

      for (pos = 0; pos <= 180; pos += 1) { // goes     from 0 degrees to 180     degrees
     //in steps of 1 degree
        myservo.write(pos);              // tell servo to go   to position in variable 'pos'
        delay(15);                       // waits 15ms for the     servo to reach the position
      }
      for (pos = 180; pos >= 0; pos -= 1) { // goes  from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go    to position in variable 'pos'
        delay(15);                       // waits 15ms for the  servo to reach the position
      }

     }
     }
     }

title: Servos and Random Number

Answers: 1

body:
You planning to use multiple servo, but only declare one.
I still don't get about the pattern, but maybe this will give some image:

    Servo myservo[5]; // assuming you have 5-servo
          // servo[0]--> pin 0
          // servo[1]--> pin 1
          // servo[2]--> pin 2
          // servo[3]--> pin 3
          // servo[4]--> pin 4
    pos = 0;

    void loop() {

    BUTTON = digitalRead(button);
    Serial.println(BUTTON);
     if(BUTTON == LOW){
      randomNumber = random(1,4);
      delay(275);
      pos+=randomNumber;
      Serial.print("Random Number ");
      Serial.println(randomNumber);
      Serial.print("Current pos ");
      Serial.println(pos);

     for (x = 0; x < randomNumber; x++) {
      myservo[x+pos].attach(x+pos);
      Serial.print("attach servo-");
      Serial.println(x+pos); }

    //open (move from 0-180 degrees)
     for (x = 0; x < randomNumber; x++) {
      myservo[x+pos].write(180);
     }
     delay(2000);

    //close (move from 180-0 degrees)
     for (x = 0; x < randomNumber; x++) {
      myservo[x+pos].write(0);
     }
     delay(2000);

    //detach servo
     for (x = 0; x < randomNumber; x++) {
      myservo[x+pos].detach();
     }
     delay(2000);
    }
    }


body:
[![LED Circuit][1]][1]

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

Hi all,

In the screenshot of a circuit I've included, I'm attempting to light up 4 LEDs off of pin 2. In circuits.io, everything works great. 3 blue LEDs and 1 red LED light up and blink as planned. When I create this same circuit on a Arduino Uno Chinese clone, IF the LEDs are all blue, they all light up and blink. If I change one of them to red, yellow, or green, ONLY the red, yellow, or green one lights up. The three blue LEDs no longer light up. It also doesn't seem to matter, where the off blue LED is put.

Not sure what's wrong.

title: Arduino UNO Chinese Clone LEDs not lighting up

Answers: 1

body:
Use one resistor per led, not one for all of them.

This is because different color leds have different forward voltages. Red requires a lower voltage to light up. So it will guzzle up all available current, while the blue leds are waiting for the voltage to go higher (which never happens).