message:
What is this PIND command

I have a code that reads the value of a sensor and because it needs to be very fast it does not use digitalRead but a strange form of reading. In the top of the code it shows:

    #define IRSENSOR PIND
    int irpin = 2;

I have no idea why this PIND referes to my arduino pin 2, but it only work if my sensor is in pin 2. If I want to change to pin 9 and only change the irpin varialbe it does not work. Why?

To read the sensor I use this code:

    while (IRSENSOR & (1 << irpin )) {

Have no idea why this work. Does anyone know this kind of programming with arduino?

body:
PIND refers to the arduino's IO register for input in port D

Without arduino, one has to refer to pins by specific bits in 3 different sets of registers for each port (PIN*, DDR*, and PORT*; B,C, and D).

The arduino code makes it simpler to pick out a single pin by hiding all of this, but it does make reading a pin take much longer.

In the code, the specific pin is being selected by masking off all but the "irpin" bit in PIND, so changing irpin will pick a different bit and thus a different pin.

Pin 9 is actually bit 1 of port B, not D, so see if this works:

    #define IRSENSOR PINB
    int irpin = 1;

alternatly, using a reference instead of define,

    volatile uint8_t& IRSENSOR = PINB;
    int irpin = 1;


sender: user

sender: assistant

body:
Reason explained by @BrettM. To be more perfect use macros everywhere, e.g.:

    #define IRSENSOR PIND
    #define IRSENSOR_PIN PD2

    while (IRSENSOR & _BV(IRSENSOR_PIN)) {

Arduino's *digitalWrite(),digitalRead(),pinMode()* functions are useless for more serious coding because they are 1) slow 2) you cannot address pins not connected to headers (e.g. at *Arduino2560*).


message:
Port register not working

I am trying to read my ultrasonic sensor. It sends a pulse in the trigger pin and the echo pin receives the pulse. Using pulseIn I can know exactly the time it took to the pulse go and back. But I need to use port register which is much faster and I need it to be fast in this specific case.

My code is very simple:

    void setup() {

     Serial.begin(9600);
     //pin 12 as output
     DDRB = B00010000;
     //pin 12 as low
     PORTB = B00000000;

    }

    void loop() {

     //pin 12 as high
     PORTB = B00010000;
     delayMicroseconds(10);
     //pin 12 as low
     PORTB = B00000000;

     long start_time = micros();

     //While reading high in pin 13 keep running the loop
     while (PINB & B00100000)) {

     }

     Serial.println(micros() - start_time);

     delay(1000);

    }

The problem is that it does not work, I mean, the while loop is not being processed so the serial is always printing a very small number. It doesnt matter if I move the ultrasonic sensor to distant walls the while loop still does not work. What am I doing wrong?

body:
According to anything I could find, the Echo output is normally *low* and then goes *high* for a duration equal to the range. Your initial while condition is inverted, and you need to check for *both* edges.

    unsigned long up, down;

    // trigger pulse
    while (!(PINB & _BV(PB5)))
      ; // wait for leading edge
    up = millis();
    while (PINB & _BV(PB5))
      ; // wait for trailing edge
    down = millis();
    Serial.println(down - up);


message:
Arduino Mega: which Digital pins are already used for something?

I got an Ethermega, and learned that Pin 13 already has a LED.

Are there other digital pins with special circuitry or already allocated to a specific function? (like usb,serial,ethernet,sd, etc)

I need about 30 inputs so I can skip some if that would avoid headaches.

body:
Don't worry about the led on pin 13, it just sits there but doesn't block anything.

You can still use the pin as a normal IO pin.

You didn't mention whether your 30 inputs are digital or analog, so let's have a look at digital input first.

I have never used the **MCP23017** mentioned by *Martynas*, but the linked article looks very interesting and I'll definitely order one of these amazing chips!

Another option might be using 8 bit PISO (*parallel in - serial out* shift registers, such as the **74HC165**. Consider this as the complement to the 75HC595 for output. These shift registers are dirt cheap (around 0.3 €), are available as DIP (important for breadboarding) and can be run via [SPI](http://arduino.cc/en/Reference/SPI).

Advantages:

- it's fast to read in 8 digital lines into a byte (why would one want to use more than a bit for the state of a digital input?)

- the shift registers can be *daisychained*, subsequent calls of [ShiftIn](http://arduino.cc/en/Reference/ShiftIn) allows to read all (digital) input states into a corresponding data structure (array of bytes, etc.) using just **three pins** on your Arduino.


body:
D4: ChipSelect for the SD card reader (can be used if no SD is present)

D0 and D1 are Serial RX and TX (just like any other arduino)

D10: Ethernet enable line

D13: led. Led is connected via a mosfet, so it doesn't interfer (like on the uno)

D50, D51, D52: SPI for the ethernet chip and SD card

All this was found in the [schematic](https://github.com/freetronics/EtherMega/raw/master/EtherMega.pdf)


message:
delayMicroseconds- error?

running a very short program on a mega, just to generate a 8 microsecond wide clock pulse on pin 18, every 250 microseconds-
closest 'delay' values I can get are delayMicroseconds(3), and (83) off, gives a 7.5 microsecond wide pulse every 249 microseconds- any suggestions on a better way?

here is whats running:

    int i=0;
    int req=18;

    void setup(){
    Serial.begin(115200);
     DDRD = DDRD | B10000010;
     interrupts();
    pinMode(req,OUTPUT);
    }

    void loop(){
    i=1;
    digitalWrite(req, HIGH);
    delayMicroseconds(3); //gives 7.5 microsecond pulse?
    digitalWrite(req, LOW);

    while(i<83){//gives 249 microseconds start of pulse to start of next pulse?
     delayMicroseconds(1);
     i=(i+1);}
     }

body:
Unless you want program PWM timer as suggested in comment then for short delays you need calculate how many instruction cycles are needed to make such a delay based on clock/crystal frequency and make that delay in inline assembler to have code under control. To manipulate digital output use writing data to PINx (which is equal to xoring PORTx).

To satisfy exact 250ms you need compensate errors because of rounding. Arduino's delay/tick functions do it. For the long delays you need a simple scheduler not to spend all the CPU time for pulse generating.


body:
This a very partial answer. I do not know your requirements, whether or
not PWM can do the job, etc... I just wanted to point out that you can
make a pulse exactly 8 µs long with this:

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

    #include <util/delay.h>
    #include <util/atomic.h>

    // Pulse PD3 (digital 18 on Mega 2560)
    // for exactly 8 us (128 clock cycles @ 16 MHz)
    static void pulse() {
        ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
            PORTD |= 1 << 3;
            _delay_us(8 - 0.125);
            PORTD &= ~(1 << 3);
        }
    }

The `_delay_us()` function from avr-libc is actually cycle-accurate
inline assembly. The 0.125 µs I subtracted is the time needed by
the actual port writes: both the sbi and cbi instructions take two cycles
(0.125 µs), but that delay should only be counted once.
`digitalWrite()` should always be avoided in time-critical code.

The 242 µs delay between pulses would be harder to generate without
PWM. A timer interrupt at 4 kHz seems like the simplest option, but
it is not cycle-accurate.

**Edit**: here is the scope trace, showing a quite accurate timing:

![oscilloscope trace](https://i.stack.imgur.com/0ekEE.png)


message:
Measuring power consumption on Arduino off of DC supply

I am working on a project involving the Uno, and I would like to benchmark the power requirements of Arduino. I am using the external 9V supply option.

Specifically, the Uno will be in to states,`power-intensive` and `power-save`. In the first mode, I am doing some heavy processing tasks (RF and some sensors are the only external loads), and the Arduino typically runs `loop()` without any delays. In the second mode, `loop()` is execued about every 10-40 seconds.

I am interested in benchmarking how much power is consumed in both states (I need this to estimate the size of the battery required for the 9V supply).

Obviously, googling yielded me solutions that involved measuring current using chips in series with the supply (I probably can pull this off with a multimeter). What I am wondering is whether there exists an elegant solution for this, with (highly) accurate results (I would most likely quote the power values, so accuracy is a must for me)? Something I can dynamically measure on the Uno itself?

body:
>  What I am wondering is whether there exists an elegant solution for this, with (highly) accurate results (I would most likely quote the power values, so accuracy is a must for me)? Something I can dynamically measure on the Uno itself?

The Uno cannot measure its own power consumption. Indeed, a Uno which has a voltage regulator, power LED, and USB interface chip is not your ideal solution for low-power applications.

See [Power saving techniques for microprocessors](http://www.gammon.com.au/power)


message:
Interrupts for analog inputs

I have an Arduino Uno. I've been reading about pin change interrupts, and one vector covers the analog pins. However, is it possible to trigger interrupts using analog pins as analog inputs (not digital)?

I actually want to analogRead() a potentiometer inside the ISR.

This is my code so far, http://pastebin.com/ykpp78GB

And my circuit is just two potentiometers connected to pin A0 and A1.

body:
It is not possible to trigger an interrupt when an analog input has reached a threshold on any tinyAVR or megaAVR. It is possible to trigger an interrupt when an analog input of an AVR XMEGA with the event system.

It is possible to use the built-in analog comparator on the ATmegaXX8 and ATmegaXXU4 in the Uno, Leonardo, and comparable boards to trigger an interrupt when an internal or external threshold has been met. It is only possible to compare to an internal threshold on the Mega, Mega 2560, or comparable boards since the pin for the external threshold is not broken out, although actual breakout boards for the ATmegaXXX0/1 will have the pin broken out.

In all cases, examine the appropriate datasheet (in particular the "Analog Comparator" section) as well as the pin mappings on the Arduino website for full details.


message:
Different Arduino packages on Raspbian

I'm working on using my Raspberry Pi (Raspbian) to upload sketches. However, I'm not sure which package is appropriate for command line usage (like described [here on Github][1]).

It seems like `sudo apt-get install arduino` would install the whole IDE, not just the command line. It seems like `arduino-core` would be more fitted for this purpose. However, the repository has a note online to use a package called `arduino-mk` for a CLI, which is what I want. However, this concerns me [in the repository's page][2]:

> This package will install a **Makefile** to allow for CLI programming of the Arduino platform.

(Emphasis mine)

What exactly does this mean? What are the differences between the three packages available?

  [1]: https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc
  [2]: https://packages.debian.org/wheezy/arduino-mk

body:
I have not actually interacted with the debian packages, but If I'm reading this right, this how they are organized:

**arduino**: The whole java IDE and avr code libraries

**arduino-core**: the libraries and code that comes with arduino to be compiled for avr

**arduino-mk**: a makefile for compiling arduino code without the IDE (but no code)

The normal arduino package has a command line interface, but the code for this is (currently) very closely tied to the java GUI code and cannot be used without the whole thing being installed. To make using the raw atmel avr tools easier, the makefile is available; However, the makefile does not include all of the cpp libraries that come packaged with the arduino installation that a normal arduino sketch would reference (Arduino.h, Servo, SPI, etc). The arduino-core package exists to bring in all this supporting code.

I imagine it is done with these three packages so if you already have arduino installed, the makefile will not bring a second copy of all the libraries with it.

The makefile is a configuration for the [gnu make][1] software. There is some information on the specific usage of the arduino makefile on its github page [here][2]

  [1]: https://www.gnu.org/software/make/
  [2]: https://github.com/sudar/Arduino-Makefile


body: Previous versions of arduino-mk had a dependency on arduino, which was everything, but with the split out of arduino-core, which both of the other packages now depend, arduino only includes the ide, everything else is in core so that you do not need the ide to develop, compile and load standard projects to your Arduino. I have only used the ide for less than 15 minutes And do all my work using vi and the command line. the makefile allows you to compile ino files with a make just by linking it into your project directory, it also has options for uploading using make.


message:
Global Arrays read as Zero

I have written a code for my Arduino which spans multiple files, In the file containing the main task, i have a Global Array like this

    addr_t childAddr[NUM_CHILDS] = { CHILD1_I2C_ADDR, CHILD2_I2C_ADDR };

where

    #define NUM_CHILDS 0x02
    #define CHILD1_I2C_ADDR   0x10
    #define CHILD2_I2C_ADDR   0x02

Now to debug my issue, in my Task i do this

    Serial.print(childAddr[0]);
    Serial.print(childAddr[1]);

All i receive is

    00

I looked at the issue online, someone pointed it towards overshooting the RAM, I am working on a Pro Mini with ATmega328P with 2K RAM.
![This is my Output for analyzing the eld with "avr-size"  utility][1]

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

body:
Since `addr_t` is a character type, I suspect `Serial.print()` is trying to output the ASCII character representation of your two values. ASCII codes 0x10 and 0x02 are non-printing characters, so it might just be outputting 0's for lack of anything better to do.

To output the data as actual numbers, try casting them to integers:
<!-- lang-all:cpp -->

    Serial.print( static_cast<unsigned int>(childAddr[0]) );
    Serial.print( static_cast<unsigned int>(childAddr[1]) );


body:
You should try to post a minimal piece of code that reproduces your problem. From what you posted I assembled this:

    typedef unsigned char addr_t;

    #define NUM_CHILDS  0x02
    #define CHILD1_I2C_ADDR         0x10
    #define CHILD2_I2C_ADDR         0x02

    addr_t childAddr[NUM_CHILDS] = { CHILD1_I2C_ADDR, CHILD2_I2C_ADDR };

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      Serial.println(childAddr[0]);
      Serial.println(childAddr[1]);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

Output is:

    16
    2

Clearly the problem isn't where you think it is.

---

By the way, in your file `Project.h` you have this:

    #include "Project.h"

Why is it including itself?

---

    void commRxISR(int count){
     /*
      ISR for the dats received on the I2C bus
     */
     Serial.write("Inside serial receive ISR\n");
     while (1);
     while (0 < Wire.available()){
      MyNode.commChild.commWriteInBuffer(Wire.read()); // Project specific implementation
     }
    }

The infinite loop in the ISR is interesting. Also don't do Serial prints inside an ISR. They can (almost certainly will) hang the system.


message:
Shift register on Attiny85 programmed by Arduino

Shift registers need 3 digital pins in order to work (data, clock and latch), but Attiny45/85 chips provides 2 digital and 2 analog pins.

Would I use 1 analog pin as digital pin? How?

body: The ATtinyX5 does not have *any* analog-only pins; all 5 pins are usable as digital I/O (all 6 if you know what you're doing, but if you need to ask how then you're not ready to do so).


body:
As *Ingnacio has already pointed out*, **PB0** to **PB4** can be used as digital IO ports **without problems**. It night be a good idea though not to touch **PB6**, the `RESET` pin.

Btw, this isn't different from an Arduino, where all so-called *analog pins* can be used for digital output as well.

If you want to drive shift registers from an ATtiny85 using SPI, you might want to have a look at the [tinySPI](https://github.com/JChristensen/tinySPI) library written by **Jack Christensen**. *Please note that I haven't used this library personally!*


message:
Using Arduino audio to control an LED light

I am looking for a way to control an LED on a circuit board using audio input for learning purposes.

I have written my own speech recognition system using dynamic time warping in Python, but I would like to know if (and maybe what models if not all can do) Arduino can possibly handle the processing of a 70 by 70 O(n^2) matrix traversal with **fft** or **dct** operations on audio input divided into 10ms frames.

Any advice will be appreciated.

body: The Due or Tre may have enough power for this. The Yún may be able to offload it to the more powerful CPU. Every other Arduino will struggle with it.


message:
Wire.endTransmission() Hangs

I have written a code that transmits data over the I2C channel, The device ID and every other stuff is working fine. The only issue being that my code gets stuck at Wire.endTrasnmission().

I found the issue using Serial debug messages.

Strange thing:

When i disconnect the SCL line (A5 on arduino Pro Mini), the hang disappears and the code starts to function again.

A search brought me to this forum
http://forum.arduino.cc/index.php?topic=66353.0

where a guy talks about the code snippet

    if(hang)
    unfreeze();

is this possible, if yes where do i place it?

Observation:  The hang goes away if i disconnect the SCL line on either of the arduinos communicating, the sam edoes not happen if i disconnect the SDA.

body:
> The device ID and every other stuff is working fine. The only issue being that my code gets stuck at Wire.endTransmission().

* Nothing is transmitted until you call `Wire.endTransmission()` so that is where it will hang.

* You should not try to do Wire transmissions inside an ISR (if you are doing that).

* There is an alternative to the Wire library which times-out rather than hanging. It is at: [Arduino I2C Master Library](https://github.com/rambo/I2C).

* Make sure you have pull-up resistors on SDA and SCL. Typically 4.7 k from both to +5 V.

* If none of that helps, please post your code.


message:
Ultrassonic sensor

Hi I have this ultrasonic sensor:

http://www.micropik.com/PDF/HCSR04.pdf

I use this code to read distances:

<!-- lang-all:cpp -->

    digitalWrite(trigPin, LOW);
    delayMicroseconds(5);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    long time = pulseIn(echoPin,HIGH);

My question is this: in the datasheet says that the sensor will send 8 pulses at 40khz. Every pulse will take 0.000025 seconds so 8 pulses would be 200 usec.

So why the delay is only 10 usec if it should be 200usec?

body: The 10us delay is just your trigger pulse HIGH phase. Refer to the timing diagram on bottom of page two in your datasheet.


body: The 10 us pulse to the TRIG pin activates the ultrasonic detector. It then sends 8 pulses at 40 kHz, and finally, sends a pulse to the ECHO pin. That pulse sent to the ECHO pin has a pulse-width proportional to the distance of the nearest object.


message:
Using Intel Galileo Ethernet Port

Is it possible to use the galileo's ethernet port through arduino IDE? Or should I buy an arduino ethernet shield? Will I be able to use galileo as a server to which arduino board can send data to?

body:
The Galileo board is Arduino compatible; meaning that you can run Arduino sketches on it, and use its I/O pins the same way you would with, say, Arduino Uno.

Therefor you can communicate between Galileo and Arduino the same way you would with two Arduino devices. This can be done using your favorite communication channel - Serial, I2C, OneWire, RF or even Infrared - it all depends what exactly are your needs, knowledge and timing requirements. Of course, doing it this way, would require you to have code running on both the Galileo and the Arduino, in charge of the inter-communication.

By doing so, you could utilize the Galileo as a 'server' as you say, that will receive commands from the Arduino, send them over the network and reply to the Arduino with the response.


body:
I suppose you mean the "Galileo integrated Ethernet port" (the on-board RJ45). Then the answer is "no, not directly". The whole code provided by Intel in Arduino 1.6 IDE applies to the W5100 based shield, not the integrated Ethernet interface (which is a bit stupid, imho...)

Technically, however, this is possible, but you will need to create a library in C/C++, which interfaces with the system lib (the Linux one). You can then access the wonderful world of BSD sockets (much more powerful than the sockets within the W5100).

Note however that the configuration of the integrated Ethernet board is not very easy with the Galileo, because the default Yocto image does not allow you to change default IP parameters (the Yocto image uses DHCP by default). So technically, you need then to deal with a startup script that changes the IP parameters at startup, but it's pretty heavy to do.


message:
Blend with SD Shield

Building a data logging and transmission system here. I've a RedBearLab Blend with built-in BLE capabilities and a (cheap) SD / Data logging shield that looks very suspiciously like it's copied from the Adafruit one.

Using a Stock Arduino Uno board, the Data logging shield works out of the box - both RTC TimeSet and cardinfo come back successfully.

Stacking the shield on the Blend, both examples lead nowhere. The TimeSet states that no connection could be made, and the cardinfo says it can't find the card.

I assume it's a pin conflict of some sort, but I'm really unsure what I should do to debug/fix it.

[edit] As I found out below, the SD Module works now - but I still face the problem of not getting the RTC to work. Neither on the shield nor a Tiny RTC module. Again, both work fine on the Arduino Uno.

[edit2] I had basically the same problem for the RTC module as well - see the answer below.

body:
Sometimes it helps just adding the tags.....

The Blend is a Arduino Leonardo Chip -
and as Lady Ada helpfully points out, you need a special SD Library to use this. The advice on https://learn.adafruit.com/adafruit-data-logger-shield/for-the-mega-and-leonardo is everything I needed to get the cardinfo working, especially the     `while (!card.init(SPI_HALF_SPEED, 10, 11, 12, 13)) {`
part.

Also, the I2C Pins for the RTC Clock are not the "standard" Analog Pins 4 and 5, but D2 and D3 (see http://arduino.cc/en/Reference/Wire)


message:
Which reflectance sensor array for a line following robot?

I'm working on a line-following robot with my son. We've found a sensor array on Robot Shop that will help us but .. there's two and I'm not sure which will be the best for us.

The difference between them, as described in [this PDF][1] is "The QTR-8A uses a voltage divider for each sensor’s output while the QTR-8RC uses an RC circuit."

What I want to do is detect which sensor the followed line is triggering. All I need is a yes/no. But I'm too new to this to decide which of these two sensors would be best for me.

  [1]: https://secure.robotshop.com/media/files/pdf/pololu-qtr-8x-reflectance-sensor-array-user-guide.pdf

body:
The main difference between the two models, as stated in the PDF you provided, is the output they provide to the MCU.

The QTR-8A will provide an **Analog** output, requiring a corresponding analog pin on the microcontroller. The QTR-8RC will provide a **Digital** output, but will allow the same accuracy of the QTA-8A by measuring the discharge time of the capacitor (HIGH to LOW time), with the advantage of higher accuracy due to the use of RC circuit instead of a voltage divider.

Both seems pretty straight forward, but for your needs, the QTR-8RC might seem more compatible, considering the Arduino Uno has 6 analog I/O pins (you didn't mention which Arduino is going to be used, the Arduino Nano has 8 and the Arduino Mega has 16), and that the QTR sensor provides 8 outputs. The way you could accomplish that with QTR-8RC and 8 **digital** I/O pins is described in the PDF:

> 1. Turn on IR LEDs (optional)
> 2. Set the I/O line to an output and drive it high
> 3. Allow at least 10 us for the 10 nF capacitor to charge
> 4. Make the I/O line an input (high impedance)
> 5. Measure the time for the capacitor to discharge by waiting for the I/O line to go low
> 6. Turn off IR LEDs (optional)


message:
Delay() function and I2C interrupt

In my design, one arduino pulls a line high on other arduino, the other arduino polls this pin and if that is high sends the data on I2C bus.

The first arduino holds the line high for 100ms using the delay() method, the other arduino is sending the data during this time, but the I2C receive interrupt is not being triggered.![enter image description here][1]

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

I have attached a sequence diagram for a better explanation for what is happening.

I suspect that the delay() method somehow is disabling the I2C ISR from triggering.

body:
Sorry guys, I made a very silly mistake here, i was using Serial.print here in ISR, following the Slave_Receiver example in the Arduino examples. I got a bit carried away with the use of those Serial debug messages and added lots of them,

I got this info from
https://stackoverflow.com/questions/17985830/arduino-using-interrupts-freezes-processing-and-serial-output

checkout answer by **elias**

The code does not freeze now. Sorry for the troubles, i hope this helps someone else in return.


message:
NRF24L01+ scanning and connecting to wifi hotspots or creating one

I've seen this [video][1] so I think I can connect it through my wifi router to any device. How can I scan for and discover wifi hotspots and then connect to it? Or is there a way to create wifi hotspot of it's own?

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

body: I believe nRF2401 is low level tx/rx chip working in 2.4GHz band. But it's not WiFi module. To use it as WiFi you probably need implement WiFi stack. I think guy in video set up channel and counting receved data only.


body:
It does seem possible, check out [this thread][1] on Arduino forums, where cpixip worked directly with the NRF24 SPI interface to accomplish that.

Here is the code he published, in case the link won't be available:

    #include <SPI.h>

    // Poor Man's Wireless 2.4GHz Scanner
    //
    // uses an nRF24L01p connected to an Arduino
    //
    // Cables are:
    //     SS       -> 10
    //     MOSI     -> 11
    //     MISO     -> 12
    //     SCK      -> 13
    //
    // and CE       ->  9
    //
    // created March 2011 by Rolf Henkel
    //

    #define CE  9

    // Array to hold Channel data
    #define CHANNELS  64
    int channel[CHANNELS];

    // greyscale mapping
    int  line;
    char grey[] = " .:-=+*aRW";

    // nRF24L01P registers we need
    #define _NRF24_CONFIG      0x00
    #define _NRF24_EN_AA       0x01
    #define _NRF24_RF_CH       0x05
    #define _NRF24_RF_SETUP    0x06
    #define _NRF24_RPD         0x09

    // get the value of a nRF24L01p register
    byte getRegister(byte r)
    {
     byte c;

     PORTB &=~_BV(2);
     c = SPI.transfer(r&0x1F);
     c = SPI.transfer(0);
     PORTB |= _BV(2);

     return(c);
    }

    // set the value of a nRF24L01p register
    void setRegister(byte r, byte v)
    {
     PORTB &=~_BV(2);
     SPI.transfer((r&0x1F)|0x20);
     SPI.transfer(v);
     PORTB |= _BV(2);
    }

    // power up the nRF24L01p chip
    void powerUp(void)
    {
     setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)|0x02);
     delayMicroseconds(130);
    }

    // switch nRF24L01p off
    void powerDown(void)
    {
     setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)&~0x02);
    }

    // enable RX
    void enable(void)
    {
       PORTB |= _BV(1);
    }

    // disable RX
    void disable(void)
    {
       PORTB &=~_BV(1);
    }

    // setup RX-Mode of nRF24L01p
    void setRX(void)
    {
     setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)|0x01);
     enable();
     // this is slightly shorter than
     // the recommended delay of 130 usec
     // - but it works for me and speeds things up a little...
     delayMicroseconds(100);
    }

    // scanning all channels in the 2.4GHz band
    void scanChannels(void)
    {
     disable();
     for( int j=0 ; j<200  ; j++)
     {
       for( int i=0 ; i<CHANNELS ; i++)
       {
         // select a new channel
         setRegister(_NRF24_RF_CH,(128*i)/CHANNELS);

         // switch on RX
         setRX();

         // wait enough for RX-things to settle
         delayMicroseconds(40);

         // this is actually the point where the RPD-flag
         // is set, when CE goes low
         disable();

         // read out RPD flag; set to 1 if
         // received power > -64dBm
         if( getRegister(_NRF24_RPD)>0 )   channel[i]++;
       }
     }
    }

    // outputs channel data as a simple grey map
    void outputChannels(void)
    {
     int norm = 0;

     // find the maximal count in channel array
     for( int i=0 ; i<CHANNELS ; i++)
       if( channel[i]>norm ) norm = channel[i];

     // now output the data
     Serial.print('|');
     for( int i=0 ; i<CHANNELS ; i++)
     {
       int pos;

       // calculate grey value position
       if( norm!=0 ) pos = (channel[i]*10)/norm;
       else          pos = 0;

       // boost low values
       if( pos==0 && channel[i]>0 ) pos++;

       // clamp large values
       if( pos>9 ) pos = 9;

       // print it out
       Serial.print(grey[pos]);
       channel[i] = 0;
     }

     // indicate overall power
     Serial.print("| ");
     Serial.println(norm);
    }

    // give a visual reference between WLAN-channels and displayed data
    void printChannels(void)
    {
     // output approximate positions of WLAN-channels
     Serial.println(">      1 2  3 4  5  6 7 8  9 10 11 12 13  14                     <");
    }

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

     Serial.println("Starting Poor Man's Wireless 2.4GHz Scanner ...");
     Serial.println();

     // Channel Layout
     // 0         1         2         3         4         5         6
     // 0123456789012345678901234567890123456789012345678901234567890123
     //       1 2  3 4  5  6 7 8  9 10 11 12 13  14                     |
     //
     Serial.println("Channel Layout");
     printChannels();

     // Setup SPI
     SPI.begin();
     SPI.setDataMode(SPI_MODE0);
     SPI.setClockDivider(SPI_CLOCK_DIV2);
     SPI.setBitOrder(MSBFIRST);

     // Activate Chip Enable
     pinMode(CE,OUTPUT);
     disable();

     // now start receiver
     powerUp();

     // switch off Shockburst
     setRegister(_NRF24_EN_AA,0x0);

     // make sure RF-section is set properly
     // - just write default value...
     setRegister(_NRF24_RF_SETUP,0x0F);

     // reset line counter
     line = 0;
    }

    void loop()
    {
     // do the scan
     scanChannels();

     // output the result
     outputChannels();

     // output WLAN-channel reference every 12th line
     if( line++>12 )
     {
       printChannels();
       line = 0;
     }
    }

The pinout seems to match the NRF24 library pinout.
Please note that it seems this project does not implement the WiFi stack, but only check a high enough signal ( > -64dBm) for a given channel.

In order to create a WiFi hotspot, implementing the 802.11 stack is inevitable, and it seems like the Arduino core chip (atmega328) is not suitable for implementing it using software and bit-banging, so a dedicated hardware will be necessary.

  [1]: http://forum.arduino.cc/index.php?topic=54795.0


message:
Using Arduino's hardware serial to control SIM900

I have a SIM900 board which has a serial interface. I'm trying to control it using Arduino Uno. I've tried using SoftwareSerial on pins 10 (RX) and 11 (TX) to talk to my board. It works OK with different baud rates (SIM900 has auto-bauding). I'm connecting pin 10 directly to my board, but pin 11 is connected through a voltage divider in order to lower voltage from 5 V to 2.8 V (SIM900 uses 2.8 V CMOS logic levels).

But now I want to use Arduino's hardware UART to talk to SIM900. I'm using pins 0 and 1 with similar design as above (also using voltage divider). I just can't get it to work. No matter what I do I can't see any communication. I've tried different baud rates, but it just doesn't work. Here is my code:

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

    void setup()
    {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);

      delay(10000);
      Serial.write("AT\r");
      delay(1000);
      if (Serial.available())
      {
        digitalWrite(13, HIGH);
      }
    }

    void loop()
    {
    }

So I should see a LED light up but nothing happens (SIM900 responds with "\r\nOK\r\n" to "AT\r"). What am I doing wrong?

body: 2.8V is not high enough to register as a high on an AVR input. You will need to use a level converter to raise the TX line of the SIM900 from 2.8V to 5V.


body:
Arduino with sim900 module is disabled after a day or course sim900 module is completely safe and always receives sms but the Arduino module led after one or more days is no longer able to enable or disable.

    #include <SoftwareSerial.h>
    SoftwareSerial SIM900 (7, 8);
    char incoming_char = 0; // Will hold the incoming character from the Serial Port.
    int led_status = 0;
    int led1 = 10;
    int led2 = 13;
    void setup () {
     pinMode (led1, OUTPUT);
     pinMode (led2, OUTPUT);
     SIM900power ();
      Serial.begin (19200); // Set the baud rate
     SIM900.begin (19200); // For GSM shield
     delay (20000); // Give time to log on to network.

     SIM900.print ( "AT + CMGF = 1 \ r"); // Set SMS mode to text
     delay (100);
     SIM900.println ( "AT + CNMI = 2,2,0,0,0 \ r");
     //SIM900.print("AT+CLIP=1\r "); // Turn on caller ID notification

     digitalWrite (led1, LOW); // Set led to LOW
     digitalWrite (led2, LOW);
    // Serial.println ( "AT + CMGD = 1,4"); // Delete all SMS in box
    }

    void sendSMS (char led_status) {// SEND SMS

     SIM900.print ( "AT + CMGF = 1 \ r"); // AT command to send SMS message
     delay (1000);
     SIM900.println ( "AT + CMGS = \" + 9xxxxxxxx \ "\ r"); // Recipient's mobile number, in international format
     delay (1000);
     if (led_status == 0)
        {
          SIM900.println ( "ALARM ON");
          }
    else

        {
          SIM900.println ( "ALARM OFF");
        }
      delay (1000);
     SIM900.println ();
     delay (5000); // Give module time to send SMS
    }
    void SIM900power ()
    // Software equivalent of pressing the GSM shield "power" button
    {
      digitalWrite (9, HIGH);
      delay (1000);
      digitalWrite (9, LOW);
      delay (7000);

    }

    void loop () {
    // # A1s on & # a0s off
    if (SIM900.available ()> 0)
    {
    incoming_char = SIM900.read ();
    if (incoming_char == '#')
      {
      delay (10);
      incoming_char = SIM900.read ();
      if (incoming_char == 'a')
        {
      delay (10);
      incoming_char = SIM900.read ();
      if (incoming_char == '0')
      {
      digitalWrite (led1, LOW);
      digitalWrite (led2, LOW);
      }
    else if (incoming_char == '1')
      {
      digitalWrite (led1, HIGH);
     digitalWrite (led2, HIGH);
      }
    else if (incoming_char == 'S')
      {
      digitalRead (led1);
      led_status = digitalRead (led1);
      led_status = digitalRead (led2);
      Serial.print (led_status); // Prints status on serial terminal
      sendSMS (led_status);
      }
    delay (10);
         }
                            // End AT command with a ^ Z, ASCII code 26

      delay (5000);

      led_status = digitalRead (led1);
      led_status = digitalRead (led2);
      Serial.print (led_status); // Prints status on serial terminal
      sendSMS (led_status);
      SIM900.println ((char) 26);
              }
       }
    }


message:
How to use bitset/read on 16bit numbers (Arduino)

I'm working on an Arduino powered Tetris game. To keep track of the pieces that have fallen and become fixed I have an array of bytes

    byte theGrid[] = {
    B00000000,
    B00000000,
    B00000000,
    B00000000,
    B00000000,
    ...

This works great when the well is only 8 LEDs wide, but I need it to be 16 wide. Is there a way to perform bitwise operations on a 16 bit number, like a short? I tried just declaring theGrid as a short, but I'm getting this error no matter what I do.

    tetris:62: error: 'B0000000000000000' was not declared in this scope

The reason I was using byte is so I could use bitread and bitset. So if an L piece comes down and lands, I can bitset the appropriate bits like this

    bitSet(theGrid[pixelY], 15-pixelX);

and end up with

    B1000000000000000, B1110000000000000

body:
The main problem that you're having is that *binary literals don't exist in C*; the Arduino libraries get around this by having **every single binary value** from 1'b0 to 8'b1111_1111 defined as a macro in `cores/arduino/binary.h`. The obvious workaround is to use octal, decimal, or hexadecimal literals instead.

    unsigned short theGrid[] = {
    00,
    0,
    0x0,
     ...
    };

Bitwise operations work as normal.

    theGrid[pixelY] |= _BV(15 - pixelX);


message:
Is it possible to use Arduino UNO programmer for other AVR microcontrollers?

I got an Arduino UNO which I started using with microc for avr to add more customizations.
I'm wondering if it is possible to use the Arduino UNO programmer to program other AVR microcontrollers (I know that it is possible using ATmega 328p and 168).

body:
The AVR microcontrollers that support ISP are all tinyAVRs other than the 4/5/9/10/20/40, and all megaAVRs.

The ATtiny4/5/9/10/20/40 requires TPI (Tiny Programming Interface). AVR XMEGA devices require the use of PDI (Program and Debug Interface). Neither can be programmed using ArduinoISP.


body:
If you are using avrisp you can basically program every AVR compatible with ISP protocol.

For example you can program ATTINY85, ATMEGA8, ATMEGA16 etc...
Basically for cheap and usable project with a usable flash size i use ATMEGA8 or 88.
Avoid ATMEGA48, you have only 4 kb of flash and that mean you can not do anything instead of blinking LED.

Another way to do this is by using Raspberry pi GPIO for burning code on AVR.

Here is some doc [from ozzmaker][1]

  [1]: http://ozzmaker.com/program-avr-using-raspberry-pi-gpio/


message:
Is the used clock for the Baudrate generator adjustable on an arduino due?

I hope to find some answers or pointers to a boggling task of mine:

Having an Arduino DUE that I want to push to its serial limits, I came up with the idea of hooking it up to my rPi via serial at least at 921600 baud.

Technically both seem capable of that. A loopback test with the rPi was successful up to 921600 and I've managed to get a "good" quality transmission up to 576000 bps already (error-rate should be around 1,3%), but anything higher gets problematic.

Problems:

 - DebugConsole, CuteCom and minicom don't have support for any speeds in-between, so either 921600 works or it doesn't

 - minicom supports 1.000.000 baud, but this would still mean a ~5% error-rate, which is according to my calculations and tests, but they are in question here as well ...

---

From the Atmel Doc I've got

    BaudRate = MCK ⁄ CD × 16

From that I've derived that with the 84MHz Due a baudrate of 1.050.000 would be the actual rate I should aim for, as CD must(?) be an INT.

    1050000 = 84000000 / 5 * 16

Questions:

 - Is my assumption of an optimal 1.050.000 baudrate right?
 - Is it possible to use a different clock for the baudrate generator than the 84MHz?

Remarks:

A Clock of 14,7456MHz should be optimal as it is equal to 921600 * 16.

I am using TXD/RXD1 on the Due.

The Due is transmitting on 921600 but the data is scrambled due to the errors.

In case somebody is wondering, my hope is that it is easier to adjust the arduino to 921600 baud than it is to setup a tool and configure the rPi to support 1050000 baud - but I am working both ways, only that with the rPi I know what to do ..

body:
The clock of the transmitter and receiver have to be matched.

**In theory**, the worst case error tolerable is 1/2 bit per byte.  For the 10 bit byte (1 start, 8 data, 1 stop) that leads to a +/- 5% clock error tolerance that you will find reported.  Note that this actually depends on the specific UART implementation, either chip or internal.  There are various methods of sampling that make some UART's better than others.  It is common to sample in the middle, but some chips have methods to improve noise rejection.

For the receiver side, do not rely on what the terminal program is showing you.  Few applications would manipulate the clock directly; they commonly just call an API with an enumerator for the speed.  You need to know exactly what hardware the receiver side has and its clock.

**In practice**, the theoretical limit is not going to work.  At high data rates, the noise on the cable will eat away at that safe margin.  More common recommendations will say +/- 1% which allows for noise on the edges of the bit transitions.

The noise on the signal is important at these data rates.  You indicate you are using TXD/RXD which is just logic level.  You cannot connect logic level any significant distance.  If the two are directly next to each other with excellent attention to wiring, you might have a chance.  Adding transceivers will help your chances significantly.

Also, note that changing to 7 bits helps.  Do you need 8 bit data?

So in summary:
- The receiver is more important than the transmitter, but they both have to match.  If you can't find a match of clocks to 1%, you will have data errors.
- At these speeds, the cabling and connection is critical.

This article at Maxim is a good starter [Maxim "Determining Clock Accuracy Requirements for UART Communications][1].

  [1]: http://www.maximintegrated.com/en/app-notes/index.mvp/id/2141


body:
Yes you can set the Master clock slightly slower and use Serial.begin(921600) and it will come out close enough to work with a HC05 bluetooth module set to 921600.
// multiplier 0x25 , divider 0x3
REG_CKGR_PLLAR=0x20253F03;// works at 921600
this will throw all other timings off but you can always compensate by changing the master clock definition in the Due ? .h file. if you want to print out of Serial0 port this will need to be set to 921600 also and you can monitor it with something like realterm that can do higher baud rates.

Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A.pdf


message:
Which IDE should I use to write Pythonic-programs for Arduino

I'm doing my first baby-steps to build tools using Arduino. I'd like to know if there is a way to write python scripts to build programs for Arduino. Most of IDEs I found are non-supported IDEs. Is there any "recommended" IDEs that I should use.

body:
The recommended IDE for writing **C/C++** for Arduino for beginners is the formal Arduino IDE, of which you can read more on the [arduino.cc website][1].

**Python** is an interpreter language, and as such, require an interpreter running on the target machine. Unfortunately, the Arduino does not natively support running an Python interpreter, although some efforts has been made in that direction, for example the [Python on a chip project][2], or the [Python Arduino Proto API v2][3].
See [this SO question][4] for more details. If you go with any of these options, the IDE you would use would be your favorite Python IDE.

Note that both projects have their downsides, and actually there is no real alternative equivalent to running compiled C/C++ code on the Arduino. If you have strong Python programming abilities, this shouldn't be too hard for you as well :)

  [1]: http://arduino.cc/en/main/software
  [2]: https://code.google.com/p/python-on-a-chip/
  [3]: https://github.com/vascop/Python-Arduino-Proto-API-v2
  [4]: https://arduino.stackexchange.com/questions/105/programming-an-arduino-using-python-rather-than-c-c


message:
analogWrite causes value from IR receiver to change

I'm playing around with an IR receiver and an RGB led.

I had it up and running, until I changed around some code. The remote seeming stopped working, but after looking at the values in the Serial Monitor it appeared that the values that were being printed out weren't the same.

After playing around a bit I found that if analogWrite is run on pin 11, the value changes. Why is this so?

Code is as follows:

    #include <IRremote.h>

    int ir_recv_pin = 2;

    IRrecv irrecv(ir_recv_pin);

    decode_results results;

    void setup()
    {
     Serial.begin(9600);
     irrecv.enableIRIn();
    }

    void loop()
    {
     if (irrecv.decode(&results))
     {
      //Serial.println(results.value);
      Serial.println(results.value == CH_MINUS);
      Serial.println(results.value);
      Serial.println(CH_MINUS);

      analogWrite(11, 125);
      irrecv.resume();
     }
    }

Output is as such when pressing the button twice in a row (without holding the button down):

    1
    16753245
    16753245
    0
    3810010651
    16753245

Initially the values come out as expected (16753245), but after the analogWrite, the value changes (3810010651).

Looking at the [documentation][1] it says that pin 11 runs at 980Hz. Is this why the value changes? If so, why?

  [1]: http://arduino.cc/en/Reference/analogWrite

body: Because IRremote uses timer 2 by default, and the PWM output on pin 11 is generated via OC2A. Either edit `IRremoteInt.h` to use timer 1, use a pin on timer 1 for PWM, or frob OCR2A directly instead.


message:
Record video with CMOS camera using Arduino

Is it possible to use this with Arduino to record and store videos on memory card?

Additionally, if someone has already done it, a tutorial link would be appreciated.

body:
Arduinos have two major drawbacks:

 1. Not enough memory.
 2. Way too slow.

There's a shield to help you do that:

http://nootropicdesign.com/ve/
http://blog.arduino.cc/2011/03/24/arduino-computer-vision-with-video-experimenter-shield/


message:
Using a relay to control a lamp

Okay, so I'm using an Arduino Uno R3 and I wanted to start of my own home automation project. I have a 4 channel 12V relay board and I normally connect it to a 12V 500mA adapter. What is the maximum wattage bulb (or CFL) that I can power with this configuration?

body: Unless you feel like starting a fire, none. Find a 220V 2A relay with a 5V coil and use that instead, switching the hot wire and not the neutral.


message:
Garbled serial on custom arduino UNO

I built my own Arduino UNO for a project at school. I think I have got the USB bootloader and Windows drivers all situated as the UNO shows up as an UNO in the device manager. When I try to load a sketch I get the error: avrdude: stk500_getsync(): not in sync: resp=0x10. (previously I received the same message with the message ending with resp=0x00)

I loaded a serial echo program using the ICSP and sent the message "serial test" to the UNO. I received this message back: {u{m}o¿wu{w

Can anyone help me troubleshoot this problem as I have ran out of things to test or look into.

Thanks in advance.

Edit: Added requested pictures of TX and RX. These were taken at Pin 0 and 1 of the headers. The scope showed the same results at the pins of the 328P but I couldn't operate the scope and hold the probe at the same time.

![Pin 0][1]

![Pin 1][2]

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

body: Sorry for the delay. I posted this question on the EE board as suggested and forgot to come back here and close this out. It was an issue with the fuses. My initial attempt to setup the 16u2 missed the step where I was supposed to change the fuses. I thought this was accomplished when loading the firmware, but was mistaken.


body: From the scope picture it appears you have a ground problem. All the grounds must be connected together even the scope. It appears like you have a pseudo phantom ground via the mains power system. Did you set the baud in the uno with Serial.begin(your baud rate);? The baud must be the same on both ends. For a check you should get a UNO and see if it works with that the problem is your board. Also be sure Tx on the UNO goes to RX on the receiving end and visa versa.


message:
Arduino uno AVR assembly with LEDs

I am currently in an introductory assembly language class.
My assignment is to use a sparkfun joystick shield kit to do something with an arduino uno. I figure turning on LEDs is the easiest. We must program it in AVR assembly(note: we have only used nasm assembly all semester).

I don't really know how this needs to be done, but I would like the lights to turn on when a button is pressed (one LED per button). I also want to use the analog pins to have the joystick LEDs fade in and out.

below is the code I have right now, and don't have the equipment to test it.

Am I on the right track, or is it a horrible mess?
The professor was referring to the arduino pins with hex, but I couldn't find a mapping of the pins and their hex values.

Thanks in advance.

    .include "/usr/local/include/atmega32u4.def"

            .global  main

            .section .text

    main:

            cbi     PortD, 2            ; joystick button
            cbi     PortD, 3            ; right button
            cbi     PortD, 4            ; up button
            cbi     PortD, 5            ; down button
            cbi     PortD, 6            ; left button

            cbi     PortC, 0            ; joystick vertical output
            cbi     PortC, 1            ; joystick horizontal output

            ldi     r16, 0x7c           ; select pins 2-6 for button input mask
            in      ddrd, r16           ; set digital button pins as input
            ldi     r17, 0x03           ; select pins 0 & 1 for joystick input
            in      ddrc, r17           ; set analog joystick pins as input

            ldi     r18, 0x1f           ; select pins 8-12 for button LED output
            out     ddrb, r18           ; set digital button LED pins as output
            ldi     r18, 0x0c           ; select pins 2 & 3 for joystick LED ouput
            out     ddrc, r18           ; set analog joystick LED pins as output

    loop:

            ldi     r20, PortD          ; read in from digital pins 0-7
            and     r20, r16            ; apply button input mask
            mov     r20, r20 >> 2       ; shift left twice
            sts     PortB, r20          ; turn on LEDs of pushed buttons

            ldi     r20, PortC          ; read in from analog pins
            and     r20, r17            ; apply joystick input mask
            mov     r20, r20 >> 2       ; shift left twice
            sts     PortC, r20          ; turn on LEDs of joystick movement
            rjmp    loop

body:
Did you know that the Arduino Uno uses the [Atmel ATmega328P processor][1]?

using the ADC for analog input in assembly language
---------------------------------------------------

You may want to skim through Chapter "24. Analog-to-Digital Converter" of the [ATmega328P datasheet][2].

You may want to read application note ["AVR126: ADC of megaAVR in Single Ended Mode"][3] and browse through the corresponding [AVR126 example software][4].
(It's in the C language, but it mentions all the registers you'll need to read the ADC in your assembly language program).
(As you can tell from the ATmega328 datasheet, the ATmega88 has exactly the same ADC as the ATmega328).

["Assembler source code for the conversion of an analogue voltage to an 8-bit-number"][5],
["AVR ASM Introduction: A moron's guide to ADC"][6]
and
["ATmega8 ADC Example"][7]
have a pure assembly language program for reading the ADC on a Atmel AVR chip
-- alas, on a slightly different chip that may have slightly different registers than the ATmega328P.

Good luck!

  [1]: http://www.atmel.com/devices/atmega328.aspx
  [2]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [3]: http://www.atmel.com/Images/doc8444.pdf
  [4]: http://www.atmel.com/images/AVR126.zip
  [5]: http://www.avr-asm-tutorial.net/avr_en/ADC8.html
  [6]: https://sites.google.com/site/avrasmintro/home/usisng-the-adc
  [7]: http://www.avrbeginners.net/architecture/adc/m8_adc_example.html


message:
Arduino to Home Speakers

I know little about electronics in general. I wanted to connect Arduino, and play a tone using tone() through my home speakers.

I've used a 1/8'' audio jack and connect ground to ground and left/right to pin 2. Run it and it was too loud.

Then I read the specification and it says,

Input impedance = 20 kOhm

Input sensibility = 400mV +/- 50mV

Arduino sends 5V so that should be a lot. Did I damage my speaker? They still work.

body:
It's probably not damaged, but you shouldn't do it again.

To get the 5V signal down to 400mV you need to create a voltage divider. As such you will need a:

5V / (400mV / 20kohm) − 20kohm = 230kohm

resistor between the pin and the input. 220kohm should be close enough.


message:
Arduino Mega read of serial encoder read at 1,024,000 baudrate?

![77 bit serial waveform at 1.024Mbaud][1]

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

Reading a 1.024m baud rate 77 bit stream from a serial encoder- `begin.serial1(1024000);` is accepted - but no idea if UART can actually run there.

In the screen grab, channel 7 is a 8 microsecond clock pulse generated by the Arduino, channel 6 is the encoder response - always begins 13 microseconds after rising edge of clock pulse, first part is always 10101101, after that it's pretty random as encoder rotates.

I tried unsuccessfully to read the pins at that speed, no way, then tried reading the repeating data at synchronous microseconds +1 to try reading one bit at a time through sequential 77 bit words while not rotating - but clocking varies in Arduino program by up to 8 microseconds over the 2 millisecond repeating patterns though.

I tried the serial read through serial1 port, getting some data, but random... with no terminator to rely on, wondering if anyone has a suggestion as to how to clear/load serial buffer after a long pause (long being almost two milliseconds) followed by the 10101101 that always starts the next read (but could possibly repeat inside of it).

I'm a newbie to these things, just tinkering around thought decoding a serial encoder would be fun... many many many hours later, have learned a bit about them and more so learned how little I know about them :)

body:
I think the problem is that there is more to serial I/O than just bits coming in. Otherwise, if nothing was sending, you would always read 0 from the serial port. Serial has a start and stop bit, for example. I doubt you could use the hardware serial to read in random bits.

If you are going to do this in software, you will have less than 16 clock cycles per bit - enough time to run about 15 instructions. It is not impossible, but very difficult.

There are two ways to read the data in code.

Option 1: Disable interrupts, and hand-write assembler that takes exactly the right amount of time. If you branch, make sure all branches take the same amount of time. I think all assembler instructions on Atmel take 1 cycle. You will need to pad out your loop to a predictable size. At 1.024mhz, the clock will drift by 2.4%, which means you'll either have to supersample (e.g. take one sample every 12 instructions, then throw away the samples closest to the clock interval) or you'll have to make some loops longer than others. If you store 8 bits per byte (as opposed to having an array of 77 bytes, storing 1 bit in each, which would be quicker), then you might get away with making "move to next byte" a different length.  Try to measure each sample in the MIDDLE of the allowed period, or as close to it as you can. You may have to unroll your loops (i.e. instead of "repeat this 77 times", do "do it, do it again, do it again....).

Or you might be able to write an ISR - Your ISR would have to be very short, basically "write the current time to a pre-defined array". Now you have 15 instructions to get the data out, but padding it OUT isn't so critical. With this method, you will get one datapoint per CHANGE (rising or falling signal). I don't know if micros() would be quick enough. Then, once the read is complete, you can post-process the data at your leisure. The ISR will be called at the start of the clock cycle following the change in signal, so this is likely to be easier.

UPDATE:

Micros only has a resolution of 4 microseconds, so you will have to make your own "clock". The easiest way to do this, is to set a counter with about how long you think it will take (, then hand-code a loop to decrement this, until zero. As far as I can make out, the decrement loop should take 2 cycle (decrement the counter, if-not-zero jump back to decrement). So if you start it at 800, it should take 100ms to reach zero. Remember that the ISR will stop the counter for the duration, you will need to compensate. Make sure that this loop isn't optimized out! Your ISR will be: copy the (above) counter into an array, increment your array pointer by 1 (so next time you put it in a different slot in your array). After the counter reaches zero, disable your ISR, and find the difference between each number and the next; add a constant (worked out by trial and error), round to the nearest 8 (which should be pretty close). Divide by 8. The first result should be the delay to the start of the data (first 1); the second will be the number of consecutive 1's, then the number of consecutive 0's, etc.


message:
Calculating Angles from MPU6050

I've been playing with a GY521 breakout recently with the MPU6050 chip on it, though i've hit a bit of a problem that I can't quite work out

I know when I rotated the board I rotated ~90 degrees about the Y axis, and using the sensitivity numbers from the datasheet (131) and integrating i've managed to get something that looks believable from the gyroscope, but am having problems with the accelerometer.

From a number of sources, [this being one of them][1], I've managed to get the three equations seen on here, however when I apply them to either the raw or scaled data (as they're scalers is shouldn't make a difference?) I get a set of data that varies from 0 to 90, but only on the X and Z axes, while nothing happens to the Y.

Updated to include code:

    #include "I2Cdev.h"
    #include "MPU6050.h"
    #include "Wire.h"

    MPU6050 accelgyro;

    int16_t ax, ay, az, gx, gy, gz;

    double timeStep, time, timePrev;
    double arx, ary, arz, grx, gry, grz, gsx, gsy, gsz, rx, ry, rz;

    int i;
    double gyroScale = 131;

    void setup() {

      Wire.begin();
      Serial.begin(9600);
      accelgyro.initialize();

      time = millis();

      i = 1;

    }

    void loop() {

      // set up time for integration
      timePrev = time;
      time = millis();
      timeStep = (time - timePrev) / 1000; // time-step in s

      // collect readings
      accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

      // apply gyro scale from datasheet
      gsx = gx/gyroScale;   gsy = gy/gyroScale;   gsz = gz/gyroScale;

      // calculate accelerometer angles
      arx = (180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
      ary = (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));
      arz = (180/3.141592) * atan(sqrt(square(ay) + square(ax)) / az);

      // set initial values equal to accel values
      if (i == 1) {
        grx = arx;
        gry = ary;
        grz = arz;
      }
      // integrate to find the gyro angle
      else{
        grx = grx + (timeStep * gsx);
        gry = gry + (timeStep * gsy);
        grz = grz + (timeStep * gsz);
      }

      // apply filter
      rx = (0.1 * arx) + (0.9 * grx);
      ry = (0.1 * ary) + (0.9 * gry);
      rz = (0.1 * arz) + (0.9 * grz);

      // print result
      Serial.print(i);   Serial.print("\t");
      Serial.print(timePrev);   Serial.print("\t");
      Serial.print(time);   Serial.print("\t");
      Serial.print(timeStep, 5);   Serial.print("\t\t");
      Serial.print(ax);   Serial.print("\t");
      Serial.print(ay);   Serial.print("\t");
      Serial.print(az);   Serial.print("\t\t");
      Serial.print(gx);   Serial.print("\t");
      Serial.print(gy);   Serial.print("\t");
      Serial.print(gz);   Serial.print("\t\t");
      Serial.print(arx);   Serial.print("\t");
      Serial.print(ary);   Serial.print("\t");
      Serial.print(arz);   Serial.print("\t\t");
      Serial.print(grx);   Serial.print("\t");
      Serial.print(gry);   Serial.print("\t");
      Serial.print(grz);   Serial.print("\t\t");
      Serial.print(rx);   Serial.print("\t");
      Serial.print(ry);   Serial.print("\t");
      Serial.println(rz);

      i = i + 1;
      delay(50);

    }

Results:

![plottedResults][2]

Strikes me as a little odd, as I was expecting only a rotational change in Y.  Any suggestions?

  [1]: http://www.geekmomprojects.com/gyroscopes-and-accelerometers-on-a-chip/
  [2]: https://i.stack.imgur.com/Jssg5.png

body:
If I understand your question, the main issues are that the axis don't match up, and z from the accel is not accurate?

with respect to the axis: just swap the values. Rotation math is self-consistent and "correct" in many different permutations. What makes it correct is the set of equations, not any single equation; So, copying equations from one reference frame to another will yield incorrect results even if they were correct originally.

your link addresses this difference:

> "Interpreting the diagram at left is a little tricky, since the tilt
> of the X-axis actually shows rotation around the Y-axis, and the
> angling of the Y-axis shows (negative) rotation around the X-axis."

      ary = -(180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
      arx =  (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));

should work better for you

On the second point: accelerometers can't measure yaw, the "z" equation can safely be ignored. that isn't yaw it calculates. Calculating z from the gyro alone should fix your second issue.

Other considerations:

 - The gyroscope tracking can be made more accurate by using the midpoint rule in your integration
 - Your code is not integrating the gyroscope's signal with the best estimate of its last position (rx, ry, rz), instead it integrates the gyro with separate numbers (grx, gry, grz). In effect information from the accelerometer is discarded each loop and gyro drift is not corrected for.
 - Thanks for including those graphs with your code samples =] rotation math is extremely tricky, and graphs help a lot


message:
Ambiguity in Software Serial

HW:
2 Arduino ProMini 16Mhz, 5V
Software serial directly connected using male jumpers on bredboard.

I have creates a software serial port for communication between two arduinos, __Parent__ and __child__

as per the documentation
http://arduino.cc/en/Reference/SoftwareSerialAvailable

    mySerial.available()

should return the number of bytes available in the buffer.
and

    mySerial.read();

should give me the byte or return -1 (255) on error.
http://arduino.cc/en/Reference/SoftwareSerialRead

here is my code snippet where i read the values

    if(child1.available() > 0){
        Serial.print("ParentReceived Something from child 1\n");
        while(child1.available()){
          recvBuffer1[i] = child1.read();
          Serial.print(recvBuffer1[i], DEC); Serial.print(" ");
          Serial.print(i, DEC); Serial.print(" ");
          i++;
          if(i == FRAME_SIZE) break;
        }
      }

the Serial outputs are for debugging,
The condition for while is true. we go inside.
Now what i receive with child1.read() is the following

    ParentReceived Something from child 2
    255 0 255 1 255 2 255 3 255 4 255 5 255 6 255 7

all i see is 255.

what i did:
     I first suspected the child of sending these data, but i used a TTL to USB converter to directly read the values being sent by the child and they are received correctly as they should be. even if i TAP the serial ports to another
TTL to USB converter i get 255 on my arduino Serial monitor and the correct data on the sniffer.

body:
I notice that your code only mentions "child1", but the output you've displayed mentions "child 2". I assume that means you're using more than one instance of `SoftwareSerial`.

It's important to note that only one instance can receive data at any given time. You need to call `listen()` on an instance to enable it, which will prevent any other instance from receiving data. (Anything which would have been received by another instance will be discarded.)

See the documentation here: http://www.arduino.cc/en/Reference/SoftwareSerialListen


body: I would suggest trying this with only one Arduino using Software Serial at first. Try using the receiver board's Hardware Serial to listen, possibly using its Software Serial for the debug output. The Hardware Serial is full duplex - it can talk and listen at the same time. Software Serial is not; only xmit or recv can run at one time, and nothing else on the board runs while it does. That can make synchronizing your two boards difficult if the communication needs to be bi-directional.


body:
The question is - are you "listening"  to the port?
Per doc SoftwareSerial will discard the data if not in"listening state".

The real question is - when not in listening state how does "available" becomes > 0 (true) AKA there is data in SoftwareSerial "buffer"?
It really looks as if there is no real data in the buffer - character count 1 and up to 254 , the buffer content is 255 == -1 which "available" will evaluate as "true".

It can be verified using code to actually get the buffer character count returned from "available" and not just test for if () validity.

    if(int count = child1.available())
    {
        than print count - how many characters in buffer for real
    or

    if(child1.available() != -1) to test for real data in buffer.

    if(child1.available() > 0){ // anything != 0 will ring true
        Serial.print("ParentReceived Something from child 1\n");
        while(child1.available()){// anything != 0 will ring true
          recvBuffer1[i] = child1.read();
          Serial.print(recvBuffer1[i], DEC); Serial.print(" ");
          Serial.print(i, DEC); Serial.print(" ");
          i++;
          if(i == FRAME_SIZE) break;
        }
      }


message:
arduino nano V3 updated schematics

Does anybody know where to find an updated scematics of Arduino Nano V3? All the Nano drawings I found (even in the Arduino official site) are based on ATMEGA 168 , no one including ATMEGA 328!!!

Thanks

Mike

body:
Go for the manufacturer of this board website i.e. [www.gravitech.us][1]. You can get the eagle files and all the data you need. Alternatively, you can download the eagle file of nanov3 directly using this link: http://site.gravitech.us/Arduino/NANO30/ArduinoNano30_Eagle.zip

  [1]: http://www.gravitech.us


message:
Bipolar LEDs flicker when sensors are polled

Or at least that's what I believe is the problem.

I had to add a bipolar LED library to my sketch to get them to work.

As it is now I only have it activated by a specified bit so it can properly drive yellow. Green and Red were working fine (the flickering problem not withstanding) without the bipolar library.

If I have no sensors enabled in the software (java model railroad interface) I'm using with the sketch, then the bipolar LEDs work fine.

The second I add a sensor, then the arduino starts polling the inputs, at which time the bipolar LEDs (all colors) go all wonky. Their flickering coincides with the flickering of the tx/rx lights on the board, so I'm assuming that the polling of the sensors is what is causing it.

Note that the bipolars are the only LEDs attached to another output pin instead of the ground. It's almost like it's polling any pin that's low at the time, which we obviously don't need/want with the pins for the LEDs.

I even changed the order of the sketch which seemed to slightly effect the flickering, but not enough not to be annoying. Keep in mind my level of understanding programming this is at the level of being able to combine sketches...which conflict led us here.

    #include <CMRI.h>
    #include <CrossingFlasher.h>
    #include <BiColorLED.h>

    CMRI cmri; // defaults to a SMINI with address 0. SMINI = 24 inputs, 48 outputs
    CrossingFlasher crossing(10, 11); // crossbucks
    BiColorLED led=BiColorLED(46,47); // (pin 1, pin 2)
    BiColorLED led2=BiColorLED(48,49); // (pin 1, pin 2)
    BiColorLED led3=BiColorLED(50,51); // (pin 1, pin 2)
    BiColorLED led4=BiColorLED(52,53); // (pin 1, pin 2)

    void setup() {
      Serial.begin(9600); // make sure this matches your speed set in JMRI
      for (int i=34; i<=53; i++) { pinMode(i, OUTPUT); }
      for (int i=22; i<=33; i++) { pinMode(i, INPUT); digitalWrite(i, HIGH); }
      for (int i=10; i<=11; i++) { pinMode(i, OUTPUT); }
    }

    void loop() {
      // 1: build up a packet
      cmri.process();

      // 4: update crossing lights. Reads bit 0
      if (cmri.get_bit(0) == true)
        crossing.on();
      else
        crossing.off();

      // 5: update crossing lights
      crossing.update();

      // 6: update Yellow lights. Reads bit 1
      if (cmri.get_bit(1) == true)
        led.setColor(3);
      else
        led.setColor(0);

      led.drive();

      // 7: update Yellow lights. Reads bit 2
      if (cmri.get_bit(2) == true)
        led2.setColor(3);
      else
        led2.setColor(0);

      led.drive();

      // 8: update Yellow lights.
      if (cmri.get_bit(3) == true)
        led3.setColor(3);
      else
        led3.setColor(0);

      led.drive();

      // 9: update Yellow lights.
      if (cmri.get_bit(4) == true)
        led4.setColor(3);
      else
        led4.setColor(0);

      led.drive();

      // 2: update outputs
      digitalWrite(34, cmri.get_bit(5));
      digitalWrite(35, cmri.get_bit(6));
      digitalWrite(36, cmri.get_bit(7));
      digitalWrite(37, cmri.get_bit(8));
      digitalWrite(38, cmri.get_bit(9));
      digitalWrite(39, cmri.get_bit(10));
      digitalWrite(40, cmri.get_bit(11));
      digitalWrite(41, cmri.get_bit(12));
      digitalWrite(42, cmri.get_bit(13));
      digitalWrite(43, cmri.get_bit(14));
      digitalWrite(44, cmri.get_bit(15));
      digitalWrite(45, cmri.get_bit(16));
      digitalWrite(46, cmri.get_bit(17));
      digitalWrite(47, cmri.get_bit(18));
      digitalWrite(48, cmri.get_bit(19));
      digitalWrite(49, cmri.get_bit(20));
      digitalWrite(50, cmri.get_bit(21));
      digitalWrite(51, cmri.get_bit(22));
      digitalWrite(52, cmri.get_bit(23));
      digitalWrite(53, cmri.get_bit(24));

      // 3: update inputs (invert digitalRead due to the pullups)
      cmri.set_bit(0, !digitalRead(22));
      cmri.set_bit(1, !digitalRead(23));
      cmri.set_bit(2, !digitalRead(24));
      cmri.set_bit(3, !digitalRead(25));
      cmri.set_bit(4, !digitalRead(26));
      cmri.set_bit(5, !digitalRead(27));
      cmri.set_bit(6, !digitalRead(28));
      cmri.set_bit(7, !digitalRead(29));
      cmri.set_bit(8, !digitalRead(30));
      cmri.set_bit(9, !digitalRead(31));
      cmri.set_bit(10, !digitalRead(32));
      cmri.set_bit(11, !digitalRead(33));
    }

I tried all the suggestions and more, same results.

My uneducated guess is the problem is probably with the CMRI.h library.
Because I FINALLY managed to actually get the native support for yellow in the software I was using (JMRI)
working without any extra bipolar libraries, and guess what? STILL flickers, though this native JMRI
support tends to make it more orange/red in color than the bipolar library did (I prefer the later).

The cmri library is actually attempting to make the arduino emulate another piece of hardware, so for all
I know it might not even be possible to get it to act right.

I've included both cpp and h scripts.
If no one actually figures this out, thanks anyway.

The CMRI.cpp file:

    /*
 CMRI - a small library for Arduino to interface with the C/MRI
 computer control system for model railroads
 Copyright (C) 2012 Michael Adams (www.michael.net.nz)
 All rights reserved.

 Permission is hereby granted, free of charge, to any person obtaining a
 copy of this software and associated documentation files (the "Software"),
 to deal in the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included
 in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
    */

    #include "CMRI.h"
    #include <Arduino.h>

    CMRI::CMRI(unsigned int address, unsigned int input_bits, unsigned int output_bits, Stream &serial_class)
     // store details
    : _address(address)
    , _rx_length((output_bits + 7) / 8)
    , _tx_length((input_bits + 7) / 8)
    , _serial(serial_class)

     // set state
    , _rx_buffer((char *) malloc(_rx_length))
    , _tx_buffer((char *) malloc(_tx_length))

     // parsing state
    , _mode(PREAMBLE_1)
    , _rx_index(0)

    {
     // clear to zero
     for(int i=0; i<_rx_length; i++)
      _rx_buffer[i] = 0;
     for(int i=0; i<_tx_length; i++)
      _tx_buffer[i] = 0;
    }

    void CMRI::set_address(unsigned int address)
    {
     _address = address;
    }

    // reads in serial data, decodes packets
    // automatically responds to POLL requests
    // returns packet type so if we got a SET request you know to update your outputs
    bool CMRI::process()
    {
     while (_serial.available() > 0)
     {
      if (process_char(_serial.read()))
      {
       return true;
      }
     }
     return false;
    }

    bool CMRI::process_char(char c)
    {
     // if it's a SET that's fine do nothing
     // if it's an INIT that's also fine, we don't really care
     // if it's a GET, well, do nothing since it must be someone else replying
     // if it's a POLL then reply straight away with our data
     switch (_decode(c))
     {
      case POLL:
       transmit();
       return true;

      case SET:
       return true;

      default:
       return false;
     }
    }

    // public methods

    bool CMRI::get_bit(int pos)
    {
     // 1: divide index by 8 to get byte offset
     char c = get_byte(pos / 8);
     // 2: return bit at that location
     return (bool) ((c >> (pos % 8)) & 0x01);
    }

    char CMRI::get_byte(int pos)
    {
     if (pos > _rx_length)
      return 0; // out of bounds
     else
      return _rx_buffer[pos];
    }

    bool CMRI::set_bit(int pos, bool bit)
    {
     if ((pos + 7) / 8 > _tx_length)
      return false; // out of bounds
     else
     {
      int index = pos / 8;
      _tx_buffer[index] = bit
       ? _tx_buffer[index] | 1 << pos % 8  // if bit=1, then OR it
       : _tx_buffer[index] & ~(1 << pos % 8) // if bit=0, then NAND it
      ;
      return true;
     }
    }

    bool CMRI::set_byte(int pos, char b)
    {
     if (pos > _tx_length)
      return false; // out of bounds
     else
     {
      _tx_buffer[pos] = b;
      return true;
     }
    }

    void CMRI::transmit()
    {
     delay(50); // tiny delay to let things recover
     _serial.write(255);
     _serial.write(255);
     _serial.write(STX);
     _serial.write(65 + _address);
     _serial.write(GET);
     for (int i=0; i<_tx_length; i++)
     {
      if (_tx_buffer[i] == ETX)
       _serial.write(ESC); // escape because this looks like an STX bit (very basic protocol)
      if (_tx_buffer[i] == ESC)
       _serial.write(ESC); // escape because this looks like an escape bit (very basic protocol)
      _serial.write(_tx_buffer[i]);
     }
     _serial.write(ETX);
     _serial.flush();
    }

    // Private methods
    uint8_t CMRI::_decode(uint8_t c)
    {
     switch(_mode)
     {
      case PREAMBLE_1:
       _rx_index = 0;
       if (c == 0xFF)
        _mode = PREAMBLE_2;
       break;

      case PREAMBLE_2:
       if (c == 0xFF)
        _mode = PREAMBLE_3;
       else
        _mode = PREAMBLE_1;
       break;

      case PREAMBLE_3:
       if (c == STX)
        _mode = DECODE_ADDR;
       else
        _mode = PREAMBLE_1;
       break;

      case DECODE_ADDR:
       if (c == 'A' + _address)
        _mode = DECODE_CMD;
       else if (c >= 'A')
        _mode = IGNORE_CMD;
       else
        _mode = PREAMBLE_1;
       break;

      case DECODE_CMD:
       if (c == SET)
        _mode = DECODE_DATA;
       else if (c == POLL)
        goto POSTAMBLE_POLL;
       else
        _mode = POSTAMBLE_OTHER;
       break;

      case IGNORE_CMD:
       _mode = IGNORE_DATA;
       break;

      case DECODE_DATA:
       if (c == ESC)
        _mode = DECODE_ESC_DATA;
       else if (c == ETX)
        goto POSTAMBLE_SET;
       else if (_rx_index >= _rx_length)
        { }
       else
        _rx_buffer[_rx_index++] = c;
       break;

      case DECODE_ESC_DATA:
       if (_rx_index >= _rx_length)
        { }
       else
        _rx_buffer[_rx_index++] = c;
       _mode = DECODE_DATA;
       break;

      case IGNORE_DATA:
       if (c == ESC)
        _mode = IGNORE_ESC_DATA;
       else if (c == ETX)
        goto POSTAMBLE_IGNORE;
       break;

      case IGNORE_ESC_DATA:
       _mode = IGNORE_DATA;
       break;

      case POSTAMBLE_OTHER:
       _mode = PREAMBLE_1;
       break;
     }
     return NULL;

    POSTAMBLE_SET:
      _mode = PREAMBLE_1;
      return SET;

    POSTAMBLE_POLL:
      _mode = PREAMBLE_1;
      return POLL;

    POSTAMBLE_IGNORE:
      _mode = PREAMBLE_1;
      return NULL;
    }

The CMRI.h file:

        /*
     CMRI - a small library for Arduino to interface with the C/MRI
     computer control system for model railroads
     Copyright (C) 2012 Michael Adams (www.michael.net.nz)
     All rights reserved.

     Permission is hereby granted, free of charge, to any person obtaining a
     copy of this software and associated documentation files (the "Software"),
     to deal in the Software without restriction, including without limitation
     the rights to use, copy, modify, merge, publish, distribute, sublicense,
     and/or sell copies of the Software, and to permit persons to whom the
     Software is furnished to do so, subject to the following conditions:

     The above copyright notice and this permission notice shall be included
     in all copies or substantial portions of the Software.

     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
     OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     SOFTWARE.
    */

    #ifndef CMRI_h
    #define CMRI_h

    #define _CMRI_VERSION 1.5 // version of this library
    #include <Arduino.h>

    class CMRI
    {
     public:
      CMRI(unsigned int address = 0, unsigned int input_bits = 24, unsigned int output_bits = 48, Stream& serial_class = Serial);
      void set_address(unsigned int address);

      bool process();
      bool process_char(char c);
      void transmit();

      bool get_bit(int n);
      char get_byte(int n);

      bool set_bit(int n, bool b);
      bool set_byte(int n, char b);

      enum {
       MAX  = 258, // max packet length in bytes (64 i/o cards @ 32 bits each + packet type and address bytes)
       INIT = 'I', // PC is telling us stuff we don't really care about
       SET  = 'T', // as in TX from the PC => Arduino, PC is SETing our status
       GET  = 'R', // as in TX from Arduino => PC, PC is GETing our status
       POLL = 'P', // PC wants to know our status
       STX  = 0x02, // start byte
       ETX  = 0x03, // end byte
       ESC  = 0x10, // escape byte
      };

    private:
      enum {PREAMBLE_1,PREAMBLE_2,PREAMBLE_3,DECODE_ADDR,DECODE_CMD,DECODE_DATA,DECODE_ESC_DATA,IGNORE_CMD,IGNORE_DATA,IGNORE_ESC_DATA,POSTAMBLE_SET,POSTAMBLE_POLL,POSTAMBLE_OTHER};

      int   _address;
      int   _rx_length;
      int   _tx_length;
      char _rx_packet_type;
      char* _tx_buffer;
      char* _rx_buffer;

      Stream& _serial;

      // parsing state variables
      int     _mode;
      int     _rx_index;

      uint8_t    _decode(uint8_t c); // process one character received from serial port
    };

    #endif

body:
The yellow color is make by very quickly alternating between red and green. If you do this fast enough your eyes won't notice. This alternating is done inside `led.drive();`. If you are polling the sensors, `led.drive();` isn't called and the leds aren't alternating for a moment.

Best way would be to use a timer to call `led.drive();` every 9ms or less. You could use the [timerOne library](http://playground.arduino.cc/Code/Timer1). I've never used that library, but I think you should use the following code.

    #include "TimerOne.h"

    ...

    void setup {
        Timer1.initialize(9000);// call every 9ms
        Timer1.attachInterrupt(callback);

    ...

    void callback()
    {
        led.drive();
    }

remove all other led.drive calls


body: You have your LED's across one of the serial I/O lines (Pin 1). Use different pins.


message:
SIM300cz AT command returns -1

I connected SIM300cz module's GSM board with Arduino Mega. The GSM board has the pins VCC, GND, RXD, TXD, GND, RI, DTR, STATUS, PWKEY and GND. I connected the GNDs with Arduino's GND, VCC to Arduinos 5V (took power from Arduino), RXD to pin 5, TXD to pin 6 (because of using software serial) and PWKEY to pin 53. My code is as follows:

<!-- language: c -->

    #include<SoftwareSerial.h>
    SoftwareSerial GPRS(5, 6);

    int inputPinTempSensor = 0;
    float tempCelsius = 0 ;
    float thresholdTemp = 45;

    void setup()
    {
      GPRS.begin(9600);               // the GPRS baud rate
      Serial.begin(9600);  // the Serial port of Arduino baud rate.
      pinMode(53, OUTPUT);
      digitalWrite(53, HIGH);
      delay(100);
    }

    void loop() {
      GPRS.print("AT+CREG/r");
      Serial.print(GPRS.read());
      delay(2000);
    }

The AT command response should be something like "ok" but it's returning -1 for every loop waiting 2 seconds. Why and what could be the solution?

**Edit:**

Sorry for the mistakes. I was trying different ways with carriage return and new line characters to make it work. Now the code is:

<!-- language: c -->

    #include<SoftwareSerial.h>
    SoftwareSerial GPRS(5, 6);

    void setup()
    {
      GPRS.begin(9600);               // the GPRS baud rate
      Serial.begin(9600);  // the Serial port of Arduino baud rate.
      pinMode(53, OUTPUT);
      digitalWrite(53, HIGH);
      delay(2000);
      GPRS.println("AT+CREG");
    }

    void loop() {
      while(GPRS.available()){
        Serial.print(GPRS.read());
      }
    }
Now it gives no responses at all. Actually after buying the module I was trying with [these][1] examples and they were not working either. So, I thought to test if the AT commands were working properly. I could be a problem with my wiring too.

  [1]: https://github.com/Arduino-IN/demos/tree/master/GSM+Arduino/Arduino-Code

body:
I think there are 2 mistakes in your code:

First, you should ensure that the 3AT3 commands are termintaed by a new line character:

    GPRS.print("AT+CREG/r");

should be changed into:

    GPRS.println("AT+CREG/r");

or:

    GPRS.print("AT+CREG/r\n");

Nite that I am not sure why you added `/r` at the end of the AT command, is that supposed to be part of the command? If your intention was to force a new line, then you meant `\r` not `/r`, which is not really a new line character but a carriage return (that might be interpreted the same by yur GSM module, but not necessarily).

The the second mistake in your code, is directly calling `GPRS.read()` **without** first waiting for a character to be available; in this situation, `GPRS.read()` will always return `-1` as a specific value meaning "no available character to read".

So you should change your code to something like:

    // 1st wait for a character to be available
    while (!GPRS.available()) {
    }
    // Then read all available characters and log them to Serial
    while (GPRS.available()) {
        Serial.print(GPRS.read());
    }


body: The correct AT command is `AT+CREG?\r`. A delay of at least 500ms is also advised after every command, though a timeout loop would be better. Since you didn't send any other commands, the modem will have no further responses for you and the Arduino will return -1 to any Serial.read()s, indicating there's nothing to be read.


message:
Setting timer3 in CTC mode - conflict with servo library

I would like to set up a timer in order to call a function 800 times per second. I'm using the Arduino Mega and Timer3 with a prescaler of 1024. To choose the prescaler factor I've considered the following steps:

 - CPU freq: 16MHz
 - Timer resolution: 65536 (16 bits)
 - Divide CPU freq by the chosen prescaler:
16x10^6/**1024**=15625
 - Divide the rest through the desired freq
62500/800=**19**.
 - Put the result + 1 in OCR3 register.

I've used the following table to set registers of TCCR3B:

![enter image description here][1]

**The error**

It is impossible to compile the code. This is the error returned by the compiler:

> Servo\Servo.cpp.o: In function '__vector_32': C:\Program Files
> (x86)\Arduino\libraries\Servo/Servo.cpp:110: multiple definition of
> '__vector_32' AccelPart1_35.cpp.o:C:\Program Files
> (x86)\Arduino/AccelPart1_35.ino:457: first defined here c:/program
> files
> (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.3.2/../../../../avr/bin/ld.exe:
> Disabling relaxation: it will not work with multiple definitions

**The code**

    volatile int cont = 0;
    unsigned long aCont = 0;
    void setup()
    {
     [...]
      // initialize Timer3
      cli();          // disable global interrupts
      TCCR3A = 0;     // set entire TCCR3A register to 0
      TCCR3B = 0;     // same for TCCR3B

      // set compare match register to desired timer count: 800 Hz
      OCR3A = 20;
      // turn on CTC mode:
      TCCR3B |= (1 << WGM12);
      // Set CS10 and CS12 bits for 1024 prescaler:
      TCCR3B |= (1 << CS30) | (1 << CS32);
      // enable timer compare interrupt:
      TIMSK3 |= (1 << OCIE3A);
      // enable global interrupts:
      sei();
    }

    void loop()
    {
     // Print every second the number of ISR invoked -> should be 100
     if ( millis() % 1000 == 0)
     {
       Serial.println();
       Serial.print(" tick: ");
       Serial.println(contatore);
       contatore = 0;
     }
    }

    [...]

    // This is the 457-th line
    ISR(TIMER3_COMPA_vect)
    {
        accRoutine();
        contatore++;
    }

    void accRoutine()
    {
      // reads analog values
    }

How to solve the conflict with the servo library?

**SOLUTION**

Conflict solved using the following code. It compiles but the counter associated with the 800Hz timer doesn't increment its value.

    volatile int cont = 0;

    void setup()
    {
      Serial.begin(9600);
      // Initialize Timer
      cli();          // disable global interrupts
      TCCR3A = 0;     // set entire TCCR3A register to 0
      TCCR3B = 0;     // same for TCCR3B

      // set compare match register to desired timer count: 800 Hz
      OCR3B = 20;
      // turn on CTC mode:
      TCCR3B |= (1 << WGM12);
      // Set CS10 and CS12 bits for 1024 prescaler:
      TCCR3B |= (1 << CS30) | (1 << CS32);
      // enable timer compare interrupt:
      TIMSK3 |= (1 << OCIE3B);
      // enable global interrupts:
      sei();

      Serial.println("Setup completed");
    }

    void loop()
    {
      if (millis() % 1000 == 0)
      {
        Serial.print(" tick: ");
        Serial.println(cont);
        cont = 0;
      }
    }

    ISR(TIMER3_COMPB_vect)
    {
      cont++;
    }

Since the main problem has been solved, I've created another question [here][2] related to the problem of the counter incrementation.

  [1]: https://i.stack.imgur.com/Z3H7p.png
  [2]: https://arduino.stackexchange.com/questions/5431/how-to-update-a-variable-in-an-isr-using-timers

body:
Unfortunately, The Servo library reserves output compare A (OCR\*A) on timers 1,3,4, and 5 when loaded on an arduino mega. Each can only have one ISR, so you will not be able to define your own TIMER\*_COMPA_vect while you use Servo without modifying the library.

However, each hardware timer is equipped with 2 output compare registers. Servo does not claim any TIMER\*_COMPB_vect interrupts, so those are free to use, and work exactly the same.

You should watch out for the Servo libraries activities, it could change the configuration of your timer. The default order is on megas is 5,1,3,4 and to give each 12 servos. It only configures the timer once it needs it, so you should be fine using timer 3 until you add that 25th servo.

To change your code, use OCR3B instead of OCR3A (the Output Compare Registers) and set bit OCIE3B instead of OCIE3A in TIMSK3 (the Output Compare Interrupt Enable bits). Then you to change your ISR function to  `ISR(TIMER3_COMPB_vect){}`

CTC mode only works with OCR3A, but if you set TCNT3 to 0 in your interrupt function you can get similar behavior. Remember to remove the line that turns CTC mode on using WGM12.


message:
Mac won't detect Serial Port for Leonardo

***EDIT:*** *The problem was the cable I was using (see answer below).*

***

I have a MacBook Pro running OS X Yosemite (10.10.1). I connected my Arduino Leonardo to my computer for the first time today (using a Micro USB to USB cable), but my computer isn't detecting it.

When I opened the Arduino IDE I selected Tools > Board > "Arduino Leonardo", but when I try to choose a Serial Port the only options are:

- /dev/tty.Bluetooth-Incoming-Port
- /dev/cu.Bluetooth-Incoming-Port
- /dev/tty.Bluetooth-Modem
- /dev/cu.Bluetooth-Modem

![screenshot of available serial ports][1]

I have tried closing and relaunching the Arduino IDE, disconnecting and reconnecting my Arduino Leonardo, and restarting my computer, but I still only see the four Bluetooth ports.

System Information (aka System Profiler) doesn't show anything connected to any of my USB ports.

Thanks in advance!

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

body: @IgnacioVazquez-Abrams's comment made me realize that the problem was the Micro USB cable I was using. It gave the Arduino 5V power from my computer, but didn't support any data connection. I'm buying a new cable.


message:
Assigning values to char array causes program to not run

I have the following code:

    #include "LCD12864RSPI.h"
    #include "DFrobot_bmp.h"
    #include "DFrobot_char.h"

    #define AR_SIZE( a ) sizeof( a ) / sizeof( a[0] )
    unsigned char wangzhi[]=" www.DFRobot.com ";
    unsigned char fused[1024];

    void setup()
    {
      pinMode(11, OUTPUT);
      for(int i=0;i<4;i++){
      digitalWrite(11,HIGH);
      delay(1000);
      digitalWrite(11,LOW);
      delay(1000);
      }
      LCDA.initDriverPin(2,7,10);
      LCDA.Initialise(); // INIT SCREEN
    }
    unsigned char* fuse3(unsigned char* a ,unsigned char* b,unsigned char* c){

      int i=0;
      int ac=0;//a counter
      int bc=0; //b counter
      int cc=0;//c counter

      for(int n=0;n<64;n++){
        for(int k=0;k<5;k++){
          fused[i]=a[ac];
           ac++;
           i++;
        }
           for(int k=0;k<5;k++){
            fused[i]=b[bc];
           bc++;
            i++;
        }
            for(int k=0;k<5;k++){
                fused[i]=c[cc];
                cc++;
                 i++;
        }
        fused[i]=0x00;
        i++;
      }

      return fused;
    }
    unsigned char* getMatch(int input){
      input = input & 0x000f;
      switch (input){
       case 0: return g0;
       case 1: return g1;
       case 2: return g2;
       case 3: return g3;
       case 4: return g4;
       case 5: return g5;
       case 6: return g6;
       case 7: return g7;
       case 8: return g8;
       case 9: return g9;
       case 10: return plus;
       case 11: return minus;
       case 12: return times;
       case 13: return g1;
       case 14: return g1;
       case 15: return g1;
       default: return g1;
      }

    }
    void displayfuse(int number){
    // LCDA.DrawFullScreen(fuse3(getMatch(1),getMatch(2),getMatch(3)));
    }
    void loop(){
      displayfuse(0x1234);

    }

This code is a stripped version of the code I need to run to get a bigger project working. But if it somewhat works than the setup should begin by flashing a LED 4 times before continuing. Currently this works. However as you can see I have commented out the line `LCDA.DrawFullScreen(fuse3(getMatch(1),getMatch(2),getMatch(3)));`. uncommenting this line causes the LED's to flash continuously rather then just 4 times. The library I'm using can be found [here][1]. Does anybody know what is going on? To me the first few lines of a program can be affected by a change somewhere this deep inside the code is a form of dark magic.

Weirdly when I change the setup to the following:
void setup()

    {
      pinMode(11, OUTPUT);
      for(int i=0;i<15;i++){
      digitalWrite(11,HIGH);
      delay(100);
      digitalWrite(11,LOW);
      delay(100);
      }
      for(int i=0;i<4;i++){
      digitalWrite(11,HIGH);
      delay(1000);
      digitalWrite(11,LOW);
      delay(1000);
      }
      LCDA.initDriverPin(2,7,10);
      LCDA.Initialise(); // INIT SCREEN
    }
it stops flashing completely.

Edit having just reuploaded the code again this time the led just remains on all the time.

edit edit
Now with the following code:

    #include "LCD12864RSPI.h"
    #include "DFrobot_bmp.h"
    #include "DFrobot_char.h"

    unsigned char fuse[1024];
    void setup()
    {

      LCDA.initDriverPin(2,7,10);

      LCDA.Initialise(); // INIT SCREEN
      pinMode(11, OUTPUT);
      digitalWrite(11,HIGH);

    }
    unsigned char* fuse3(unsigned char* a ,unsigned char* b,unsigned char* c){
     unsigned char* fused =(unsigned char*)malloc(sizeof(char)*1024);

      int i=0;
      int ac=0;//a counter
      int bc=0; //b counter
      int cc=0;//c counter

      for(int n=0;n<64;n++){
        for(int k=0;k<5;k++){
          fused[i]=a[ac];
          ac++;
           i++;
        }
            for(int k=0;k<5;k++){
          fused[i]=b[bc];
          bc++;
           i++;
        }
            for(int k=0;k<5;k++){
          fused[i]=c[cc];
          cc++;
           i++;
        }
        fused[i]=0x00;
        i++;
      }
      return fused;
    }
    unsigned char* getMatch(int input){

      input = input & 0x000f;

      switch (input){
       case 0: return g0;
       case 1: return g1;
       case 2: return g2;
       case 3: return g3;
       case 4: return g4;
       case 5: return g5;
       case 6: return g6;
       case 7: return g7;
       case 8: return g8;
       case 9: return g9;
       case 10: return plus;
       case 11: return minus;
       case 12: return times;
       case 13: return g1;
       case 14: return g1;
       case 15: return g1;
       default: return g1;
      }
    }
    void displayfuse(int number){
     LCDA.CLEAR();
       delay(100);

     int mask1 = 0xF000;
     int mask2 = 0x0F00;
     int mask3 = 0x00F0;

     int firstnumber = number&mask1>>12;
     int operation = number&mask2>>8;
     int secondnumber= number&mask3>>4;

      LCDA.DrawFullScreen(fuse3(getMatch(firstnumber),getMatch(operation),getMatch(secondnumber)));
      delay(5000);
    }
    void loop(){
      displayfuse(0x1234);
      delay(1000)
    }
This causes the led to not turn on but moving the lines where I make pin 11 output and high one up (beyond the  `LCDA.Initialise(); // INIT SCREEN` ) then the led will turn on. It can also be turned on by commenting out the       `LCDA.DrawFullScreen(fuse3(getMatch(firstnumber),getMatch(operation),getMatch(secondnumber)));` line.
Magic is happening...

  [1]: http://www.dfrobot.com/wiki/index.php?title=SPI_LCD_Module_(SKU:DFR0091)

body:
The 'dark magic' is going to be your program rebooting every time it gets to that line. I would imagine (this isn't a library I know) that you're exceeding an array bound & generating a 'segfault', although it could be that you light up your LCD array & the power draw causes a reboot..
Because the LED flash is at the start of setup, it executes quickly, so generating the appearance of continual flashing when  it re-enters repeatedly.
Your code is going to assign g1[0] when the line in question executes - is g1[] defined to point somewhere valid?


message:
How to stop Arduino from drawing power through USB

I'm working on an embedded project, where I use arduinos as a "sensor shield" for RaspberryPi (I have model B).

The problem is, that the RaspberryPi's USB port is not powerfull enough to drive WiFi adapter and arduino with sensors. The solution is easy, I will power the sensors externally, not through the RPi.

But I was wondering, **is it possible to power whole Arduino externally (through Vin) and use the USB only for serial communication.**

To clarify, I know how to solve my problem - use some other mean of communication, than USB - GPIO serial, I2C, wireless, etc... I'm just interested if the whole thing will work, with USB cable which has 5V lead cut, for example.

The main issue I can see with this is, that the USB<->Serial chip is powered through USB only, then it will now work.

body: If you provide power to the Arduino through `Vin` this will disconnect USB power through the MOSFET switch.