text:
Using a web server with Arduino
So I am not new to arduino, however, I am new with web servers. I am working on a project that can control a robotic arm that is at one location and I can be at my house. I know basic HTML, Basic CSS, Basic JavaScript, and a tiny bit of JQuery. Only reason I say basic is because I self taught all these languages to myself using codeacademy. So I have a few questions since I done research on the matter.
Can a project like this be done with just the languages I know? All the tutorials I have looked at say you have to know AJAX and JSON. I have no idea what these are.
Also, for the interface, I need to be able to take the value of the encoders on the robot and view them. I also need a button that will record the value at that point in time of the encoders so I can configure the points and maybe even name them. A box where I can see the points and their coordinates, and finally a box where i can place points in and then execute a sequence.
How tough should this be?

I cannot quite get what you are looking for. Could you explain what sort of architecture you have in mind? You have an Arduino board, with a WiFi (or Ethernet) adapter, right? and you want to connect it to a web server? or you want to run the web server on Arduino?

Uno with Ethernet shield.I want to run a server off the board that also is linked with the robot

You can use an Arduino Yun: it has a 32u4 microcontroller coupled with a cpu running linux. The linux side already has a webserver: together with the Bridge library, you can use REST-like APIs to control a sketch, or build a web app that uses that APIs.
One example of remotely control an Arduino (although using an Android app instead of html+js) is this. Here is its source code.

There is an example of using the ethernet shield as a simple web server on the arduino website:
http://arduino.cc/en/Tutorial/WebServer
Adafruit has another tutorial using an SDCard to hold the web application's files:
http://www.ladyada.net/learn/arduino/ethfiles.html
It would be possible to use the aforementioned techniques to host a simple web application.
Since the browser only understands HTML, CSS and JavaScript (browser plugins not withstanding), the application will have to be written using these languages.
The HTML file will describe the structure of the UI (text, buttons, etc.), the CSS will apply styles if necessary and the JavaScript will add the interaction code (e.g. what happens when you press a button). The JavaScript could request data from the arduino+ethernet shield using AJAX request and should be able to send data back the same way. Using jQuery, this should be pretty straightforward.
That said, it might be easier to use a full fledged network stack such as the one you can find on Linux (using a raspberry pi for example) and to communicate using the serial port with Linux. I have an example on GitHub (the documentation is lacking but I could update it if need be): https://github.com/ddm/arduino-express
But in that case you don't get to use the ethernet shield which you may have already bought...


text:
Using the ATMega328, from an Arduino UNO in a Standalone configuration, and bootloader - I am really lost
I am really despaired. I have spent a full day to understand this, and it seems that I still don't.
I have an Arduino UNO, with an ATMega328, for which I wrote a great piece of code.
Later, I have built a circuit on a bread board, where I want to use that same ATMega328, in a 3.3V configuration, and hence 8MHz oscillator .
So, I understood that I have to write a new boot loader to it (is that correct?)
So I follow many guides available, including the Arduino Standalone, and then I understood that I don't have another chip (ATMega328), in order to use the UNO as a boot loader.
So, I was trying to connect the ATMega328 directly from the bread board to the UNO's serial data, change the boards.txt file to add "ATMega on bread board 8MHz", and tried to boot-loading it, without success. I get the error that it can't connect with the board.
Now I have been told that I can't connect the ATMega328 directly to the UNO serial to boot load it, so my questions are:

Do I really need to go over this hell in order to work with the same
chip that worked with 16MHz, but now on 8MHz at 3.3V? (why
in microchip I could just switch xtal? )
If I do have to boot loading it, and I have one chip, and
an UNO, how can I do that?
How you do that in mass production?

More than a month passed since you posted this question, and there are two answers, below. Did any of them help you? Have you solved your issue?

So do I understand you correctly that you want to lift the ATmega328 IC from the Uno board and use it on a breadboard? That strikes me as an unnecessarily risky proposition just to save a dollar or two for a separate ATmega328p.
Second, you technically might not have to write a new boot loader to the chip, if you don’t intend to reprogram it while it’s on the breadboard, but you definitely need different fuse settings, and the two changes are closely related in the Arduino IDE.
Third, bootloaders on ATmega are incapable of modifying themselves, so if you want to write a new bootloader, you always need a programmer (which can e.g. be your Arduino UNO running the ArduinoISP sketch or ScratchMonkey); I don’t think your single-microcontroller idea would work.
For mass production, you’d just use a programmer. Bootloaders tend not to be used for this, which can lead to situations like this year’s mishap at SparkFun

There is a very nice tutorial by Adafruit, which explains how to get the Arduino Uno run at 3.3v, with minimum hussle and while keeping it's speed at 16Mhz, despite it's a bit out of specs (they claim it shouldn't pose a problem).
The main idea is to replace the voltage regulator and the fuse on the Uno board. This involves some soldering, but will probably give you the fastest results for prototyping.
I would not choose the Arduino Uno for mass production anyway, since there are plenty of Arduino compatible boards that runs at 3.3v (like Arduino Due, Lilypad, and Arduino Pro Mini to name a few. Full list can be found on Wikipedia). As a side note, for mass production, I would probably go with a custom made PCB, and not an off-the-shelf product, considering its high cost.
The link you provided explains how to recreate the Arduino  around the Atmega328p on a breadboard. For that, you will need a USB to serial converter such as the suggested FT232, but please note that this tutorial does not address the issue on stake, which is running the chip at 3.3v (note the specs of the voltage regulator they offer, which is a 5v regulator).

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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?

That's not a strange form of reading, that's the normal form of reading. The Arduino libraries are the strange form of reading.

Agree, but I am a beginner, sorry. Do you know how to create a variable/const of PIND without using define?

http://www.arduino.cc/en/Reference/PortManipulation

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;

Thank you so much, it worked perfectly! One final question: I would like to change #define pino_sensor_infravermelho_PIN  PIND -->> const byte pino_sensor_infravermelho_PIN = PIND;    BUT it does not work, IDE does not allow me to compile. How to solve this?

How did you know it's 1? It worked but I would like to know how to discover it!

I just looked at this cool image I found on google to get the pin numbers, http://www.pighixxx.com/test/portfolio-items/uno/?portfolioID=314 If you are really interested in how all these registers work it is all described in the atmega328 datasheet.

You can get rid of the #define with a reference to a volatile unsigned 8 bit value. See my edit for the code

Nice!!!! I am not lazy, I used the image http://arduino.cc/en/Hacking/PinMapping168 but your link is much better cause in the link I showed you the pins are not right. tHANK YOU so much really I could not use define and it helped me alot!

@Samul: I don't see any difference between the two, other than one shows the Arduino and the other shows the IC.

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).

Thank you so much! do you know how to declare those 2 variables without using define?

It's rather complex task because depends what is intended usage. To be precise you need consider using in inline assembler, proper resolving variables in debugger when watching, IO vs. MEM access (_SFR_MEM vs. _SFR_IO) etc. PIND, PD2 itself is also #define. I would not experiment with it without good reason to make more reusable and readable code (=writing common libs not hardcoded to particular device), e.g. define port+pin as WORD (hi=port, lo=pin) and implementing own macros.

BTW: You do not need using define at all, if define is problem:
*while (PIND & _BV(PD2))*

You are awsome, I will use it inside the while without declaring any variable. Could you please help me understand this: -->> while (porta_pino_sensor_infravermelho & (1 << pino_sensor_infravermelho)) { <<--. I know & is bitwise and and << is bitshift but it does not make any sense to me! Have you ever seen this way of reading a pin HIGH/LOW?

HIGH=1, LOW=0, it's just strange macroization of trivial things (done even wrong way because HIGH and LOW are really not too unique names in namespace). Almost any port has normally 8 pins, it equals BYTE, particular pin corresponds to bit. Just trivial bitwise opration if bit is high level then do looping.

so you are saying that if I am using pin 9 then pino_sensor_infravermelho should have 01000000 ? I cant understand this 'while" cause I dont know the value of pino_sensor_infravermelho

@Samul: I recommend retaining the macro definitions. They don't cause any slowdown during runtime and they make the code easier for others (and eventually yourself) to read and understand.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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?

How have you wired it up?

VCC to 5V, GND to GND, trigger to 12 and echo to 13.

And does echo follow the behavior described in your code (normally high, pulls low on receive)? Where is the datasheet for the sensor?

It's the HC-SR04 ultrasonic sensor. With pulseIn it works perfectly, but using PINB it does not.

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);

Thank you so much for helping but there is a problem: in your code you putted PIND, but it should be PINB right? Another thing: when I try to copile your code I get error saying that PB5 was not declared. I changed it to only 5 ok? But it still does not work. Could you please check what am I doing wrong? I edited your question to add my code cause I couldnt add it here in the coments ok? Sorry for that.

Use PINB5 instead.

still having problem. Look: when my sensor is doing nothing it registers LOW. When an ultrasonic pulse arrives it registers HIGH right? So why do I need 2 whiles? Couldnt I just start a timer when the trigger sends a pulse and stop the timer when sensor reads HIGH? I tried "while sensor is not high keep looping" but it does not work. What am I doing wrong? The HIGH/LOW logic of mine is wrong?

The duration the Echo signal is held high is proportional to the distance detected.

So you are saying that this image is wrong?  http://forum.arduino.cc/index.php?action=dlattach;topic=283286.0;attach=104940;image


text:
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.

Have you checked the schematic and datasheet yet?

http://arduino.cc/en/Main/arduinoBoardMega , also you could try some external IO inputs with http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/

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

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.
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 allows to read all (digital) input states into a corresponding data structure (array of bytes, etc.) using just three pins on your Arduino.

Klaus i wanted to mention 74HC165 :) but MCP23017 link was open already so i just copied it to give the main idea:) +1

@Martynas I think it was a splendid idea to mention the MCP23017! As written by John Boxall in the article that you linked: "...I think the I2C bus is underappreciated".


text:
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);}
 }

Is there any particular reason why you don't want to use PWM?

from what I understand, PWM frequency is 'roughly' 490 hz, I need exactly 4000 hz. is there a listing of instruction processing times published somewhere for calculating overhead? Micros will give the whole thing, but not just the while-loop

Only if you stick to what Arduino gives you. Breaking outside the box makes things more flexible all around.

Try out the TimerOne library.

thanks guys- rethinking, reading Micros at various parts of the program can let me shift timing as needed to read next bit in the next byte- will only work for static conditions, but thats OK for now. Thanks for suggesting PWM- yes standard it clocks very slow, but it is accurate- the pulse duration of 1% just happened to give a 8 microsecond tick, triggering the device to send- the extremely long off time it didnt mind at all. thanks for the comments- this things all pretty new to me, but i see a ton of potential for building tools to repair our CNC components :)

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:
#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:

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.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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?

If you're worried about power consumption then you need to move away from Arduino completely and work on a standalone solution with the bare MCU and a switching power supply.

I just need to benchmark for comparision. Can you please elaborate.

A multimeter will be fine for battery life expectancy. If you want more precision, you need something like a uCurrent and a oscilloscope that can calculate the area underneath the curve. But first, I'd try using a multimeter and a 5V supply (5v as to eliminate the power usage of the voltage regulator). Measure the current during processes, and during "sleep".

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


text:
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.

You can use a pin change interrupt on an analog input, and you can read an analog input inside an ISR. But using the same pin both as an interrupt trigger and an analog input makes little sense, unless you are using the analog comparator (not pin change) interrupt. You should start by telling us what you actually want to achieve.

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.

What I want to do is to analogRead() a pot inside the ISR. I have an Arduino UNO.

Well, I'm thinking that maybe I should read those analog values inside a timer interrupt. Considering I'm using some delays inside the loop() function.


text:
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).
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:

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?

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 software. There is some information on the specific usage of the arduino makefile on its github page here

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.


text:
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.

In desperate attempts to solve this i even tried addr_t childAddr[NUM_CHILDS] = { 0x10, 0x02}; and also tried assigning the valuess inside my Task, still the array reads as Zero.

I found a workaround for this, I declared the array locally and am using it. As per my understanding i think, C++ initializes all global variables to Zero, What eludes me is the fact that, i tried initializing them inside a function and they still read as zero.

what type is addr_t?

Its is an unsigned char

Your code on Github does not have that array at global scope, so it is almost impossible to debug code which we can't see.

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:

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

Sorry, It does not work either, I have defined the array locally within the function now, and it seems to work fine with/without the static_cast<unsigned int>(childAddr[0]) I am getting the correct values with my version and your version of Serial Print. Pretty strange though. Is there any kind of compiler setting for this?

No, there should be no setting which affects it. It might help if you add all your code to the question though (if possible). There could be other issues like masking or initialisation order.

well the code is really long to be posted here... I will give a link to my repo at github. https://github.com/ArunMKumar/IIEC/blob/Active/Project.cpp   In this file if you search for addr_t childAddr you can get to the part i am talking about, currently it is declared in function scope, it was dclared at line45. also i appreciate your efforts in helping me solve this.

@ArunKumar It looks like initialisation order could be the problem, although I can't tell just from that code. Basically, the code that's trying to use the global array might be executing before the global array has actually been setup. It can happen if you run code in the constructor of an object that is instantiated globally or statically. A possible solution is to create your objects on the heap during setup() (i.e. using the new keyword), but I don't know if that would break something else in your code/libraries.

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.


text:
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?

http://forum.arduino.cc/index.php?topic=170470.0 this can be helpful

well that's an unanswered question i guess

Thats why its in comments i guess

Claiming only 2 analog pins must mean that you're using attiny instead of arduino-tiny; I recommend that you use arduino-tiny instead.

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).

well, I mean if I had to declare them as OUTPUT using pinMode(). Should I use digitalWrite() and digitalRead() on them?

That's how you use digital I/O with the Arduino libraries, so yes.

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 library written by Jack Christensen. Please note that I haven't used this library personally!

Thanks. I'll read about SPI. I know attinyX5 uses USI, but communication is possible with that library and SoftwareSerial I guess.


text:
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.

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.


text:
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.

The only place some code to fix the problem could go is where code is still running during the hang: inside the twi library.

i tried changing the buffer size as pointed in some forums, but still it does not work.

Look into the watchdog timer. You can set it up to reset the chip if the timer hasn't been reset for e.g. 2 seconds. Just call wdt_reset() in every loop.

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.

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.

Arduino I2C Master Library link is dead.  It's now on GitHub: https://github.com/rambo/I2C

@Casey (sigh) Let's hope that link doesn't go down. Amended answer. Thanks.

@Casey With a bit more reputation (like, 1000) you will be able to edit answers and fix things like that up, which is perfectly acceptable to do, providing you don't change the intention of the answer.

I think you can suggest edits with fairly low rep, I'm not sure exactly what that threshold is.

Thanks for that.  I'll have to learn how to do edits if SE ever gives me some big boy pants.  It's worth noting that the original DSS Circuits I2C library is on github (https://github.com/DSSCircuits/I2C-Master-Library), but it died 8 years ago and was forked and carried forward by rambo (https://github.com/rambo/I2C) which has some activity this year.


text:
Ultrassonic sensor
Hi I have this ultrasonic sensor:
http://www.micropik.com/PDF/HCSR04.pdf
I use this code to read distances:
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?

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

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.


text:
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?

Welcome to Arduino SE! Do you mean sending traffic through the USB port to the computer to use the computer's internet connection?

Considering that the Galileo is basically a small embedded linux system, you could also evaluate the option of using it as such, meaning using your programming language of choice directly inside linux.

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.

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.

Yup - the Galileo Ethernet port works the same way as any other Arduino. For some sketch examples have a look at

File > Examples > Ethernet

Wrong, the Ethernet library is for use with W5100 Ethernet controller, as used on the Arduino Ethernet shield, not the Galileo's onboard Ethernet.


text:
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.

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)


text:
Incorrectly Reading Serial Using RXTX in Ubuntu
I am reading Accelerometer signals connected to Arduino board through a serial interface. I am using the RxTx library and following is the code.
private void initializeSerial() {
    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    while (portEnum.hasMoreElements()) {
        CommPortIdentifier currentPortIdentifier = (CommPortIdentifier) portEnum.nextElement();
        for (String portName : PORT_NAMES) {
            if (currentPortIdentifier.getName().equals(portName)) {
                portId = currentPortIdentifier;
                break;
            }
        }
    }

    if (portId == null) {
        System.out.println("Port not found");
        return;
    }

    try {

        serialPort = (SerialPort) portId.open(this.getClass().getName(), 2000);
        serialPort
                .setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
        output = serialPort.getOutputStream();

        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);

    } catch (Exception e) {
        System.err.println("Initialization failed : " + e.toString());
    }
}

@Override
public void serialEvent(SerialPortEvent event) {
    if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            String inputLine = input.readLine();
            String[] inputValues = inputLine.split(",");
            System.out.println(inputLine);

            if (inputValues.length == 10 && inputValues[0].equals("STX")
                    && inputValues[inputValues.length - 1].equals("ETX")) {

                double classid = 0;
                double accx = 0;
                double accy = 0;
                double accz = 0;
                boolean num_error = false;

                try {

                    classid = Integer.parseInt(txtClassID.getText());
                    accx = Double.parseDouble(inputValues[2]);
                    accy = Double.parseDouble(inputValues[4]);
                    accz = Double.parseDouble(inputValues[6]);
                    num_error = false;

                } catch (NumberFormatException numex) {
                    num_error = true;
                }

                if (recording) {

                    if (!num_error) {
                        gestureList.add(new double[] { classid, accx, accy, accz });
                        System.out.println("ClassID : " + classid + " \tAdding : "+ accx +","+ accy+","+ accz);
                    }

                    System.out.println("ClassID : " + classid + " \tAdding : " + accx + accy + accz);
                } else {
                    if (gestureList.size() > 0) {
                        gestureCollection.add(gestureList);
                        System.out.println("Segment :" + (gestureCollection.size()) + "   Items : "
                                + gestureList.size());
                        txtSegments.append("Segment " + (gestureCollection.size()) + "\tItems : "
                                + gestureList.size() + "\n");

                        // comboSegments.addItem(gestureCollection.size());

                        gestureList = new ArrayList<>();
                    }
                }

                txtRawData.append(inputLine + "\n");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

The problem I have is that, I'm reading the values in Windows environment perfectly, without any issues. But in Ubuntu I get data that is damaged and partially read. Here is the Java console output when I did this in ubuntu.
These are correct readings.
STX,16564.00,16565.65,-352.00,-431.09,-17840.00,-17941.79,-178.64,-42.72,ETX
STX,16524.00,16562.53,-440.00,-431.76,-17848.00,-17934.75,-178.63,-42.73,ETX
STX,16572.00,16563.24,-420.00,-430.88,-17992.00,-17939.05,-178.64,-42.72,ETX
But I get readings like this too. (In a considerable amount)
STX,16580.00,16551.27,-432.00,-438.85,-17936.00,-17922.1724.00,16548.94,-380.00,-439.41,-17880.00,-17921.05,-178.61,-42.71,ETX
9-178.56,-42.75,ETX
.,-454.82,-17944.00,-17916.45,-178.54,-42.72,ETX
STX,16584.00,16558.19,-464.00,-465.68,-18007416.00,-446.99,-18008.00,-17935.43,-178.56,-42.71,ETX
Why does this happen, where I can read perfectly in Windows and Not in Ubuntu.
Any help please? Thank You.

Have you looked into what the default flow control modes are on each OS? try changing the code to enforce a particular mode and see if it has any effect.

Could you explain more on that Brett? Do you see any issue in my code?

No issues per say, but you never explicitly set the flow control mode and your errors look similar to what happens when the receive buffer becomes full and starts dropping characters. Flow control requests the sender stop for a bit while the buffer gets processed. Try using different flow control modes with this: http://show.docjava.com/book/cgij/code/data/j4pDoc/serialPort/rxtx/RXTXPort.html#setFlowControlMode(int)


text:
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 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.

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:

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

Great, easy to understand answer. Thanks @Omer!


text:
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.
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.

"... the delay function does not disable interrupts."

How have you set up I²C? Which is slave and which master? Why bother with any signalling other than I²C?

because, my earlier design had a scenario where both the device started communicating over I2C at the same time, now the second device shall only send when the first asks it to do so.

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.


text:
NRF24L01+ scanning and connecting to wifi hotspots or creating one
I've seen this video 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?

It does seem possible, check out this thread 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.

I'm using Arduino Mega which has ATmega2560 chip. Do you think wifi stack can be implemented on this? Can you also provide me some tutorial or other helpful links about wifi stack please? I am new to wifi stack thing.

You can read more about 802.11 in wikipedia: http://en.wikipedia.org/wiki/IEEE_802.11 . It seems that a microcontroller running around 16MHz won't do the job. Also, implementing the network stack by yourself is not recommend for beginners. Nevertheless, there is also a nice gateway solution, check out this thread: http://forum.arduino.cc/index.php?topic=187274.0

if I use this ESP8266 module, do you think I can work without implementing any wifi stack?

Looks like this module should work, check out this instructable: http://www.instructables.com/id/ESP8266-Wifi-Temperature-Logger/

Anybody, please check this question of mine. (link) I edited this question now, since no one is answering it, I thought I would post it here.

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.

It's all right if i can only send and receive data, all i need is i can search, discover and connect with the nrf module using any wifi enabled device.

The issue is more fundamental than implementing a wifi stack - the nRF24L01 radio does not have the bandwidth and modulation types needed to support wifi.


text:
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:
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?

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.

So why it does work with software serial without any problems?

It is very marginal. The additional loading from the USB communication chip destroys this margin.

I see. Thank you for help. I'll use a level shifter as you suggested.

One would think that an idle USB serial chip would actually be pulling the line up thought its series resistor, rather than loading it down.

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);
          }
   }
}


text:
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

There are no bitwise operations in that code.

@IgnacioVazquez-Abrams I edited the OP

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);

Thanks, I got a similar answer on stackoverflow. I think this will work :)


text:
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).

Are you using serial port programming or ISP?

Not entirely clear what you are asking. Are you familiar with: http://arduino.cc/en/Tutorial/ArduinoISP

yeah i am using arduno isp.

It is not clear what do you mean by 'other AVR microcontrollers'. Can you please specify one specific AVR you plan to program using Arduino Uno?

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.

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


text:
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 ..

Localization note for this question: decimal points are shown as comma.  thousands separator is shown as dot.  yes?

oh, yes, that is correct

Why not use SPI to communicate between Due and rPi? You would support higher rates, and that would not be much more difficult to implement.

@jfpoilpret thanks, but the rPi is more like a verification device, the true challange is the arduino serial port, I am aware of SPI and USB, but I need to do this via serial or at least find out if this is possible or not

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.

wires are like 10cm max; the arduino is powered by the rPi as there is no extra GND line; need 8 bit; used init_uart_clock=14745600 on the rPi; am aware of the +/-1%; the situation is clear, but how to solve it?! how to practically align the clocks and baudrates of the rPi and due to 921600 or anything else in the neighbourhood

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

May be a little formatting and some punctuation might help understand your answer...

I had to put this project aside for quite a while but will check the answers when it will restart


text:
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.

Before asking about an IDE you should ask if it's even possible in the first place.

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.
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, or the Python Arduino Proto API v2.
See this SO question 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 :)


text:
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 it says that pin 11 runs at 980Hz. Is this why the value changes? If so, why?

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.


text:
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.

Arduinos have two major drawbacks:

Not enough memory.
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/

Some more info from electronics.stackexchange: http://electronics.stackexchange.com/questions/50576/how-to-stream-arduino-based-camera-to-http-server


text:
MySQL Connector/Arduino issues - not connecting
So I was going to make a project with the MySQL Connector/Arduino; a temperature log. I started out by experimenting with the example code from the website linked above. Not once did I manage to actually connect to the server; the mysql_connect() function always returns false. After several hours of intense googling, innumerable irritated noises and more, I decided to ask here on Stack Exchange.
Here is my current code:
#include "SPI.h"
#include "Ethernet.h"
#include "sha1.h"
#include "mysql.h"

byte mac_addr[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x69, 0xAC };
byte ip_addr[] = { 192, 168, 10, 127 };
byte dns_addr[] = { 192, 168, 10, 1 };
byte gateway_addr[] = { 192, 168, 10, 1 };
byte netmask[] = { 255, 255, 255, 0 };
IPAddress server_addr(192, 168, 2, 100);

Connector my_conn; // The Connector/Arduino reference

char user[] = "";
char password[] = ""; //the credentials are correct in my code
char INSERT_SQL[] = "INSERT INTO test_arduino.hello VALUES ('Hello, MySQL!');";

void setup() {
  Serial.begin(115200);
  Ethernet.begin(mac_addr, ip_addr, dns_addr, gateway_addr, netmask);     //Yes, I know this is way more than necessary, but just to play it safe
  delay(1000);
  Serial.print("IP: ");
  Serial.println(Ethernet.localIP()); // debugging
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password)) //connect to database
  {
     delay(500);
     my_conn.cmd_query(INSERT_SQL);
     Serial.println("Query Success!");
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
}

Any help is greatly appreciated.
Rasmus
EDIT: Looks like I'm not even getting through to reaching the server and attempting to log in. I enabled the general query logs, yet I get nothing when trying to connect. Also, I can ping both the Arduino and the MySQL server from this computer. I guess that rules out a faulty shield and network setup.

Can the gateway machine communicate with the server?

Yes, it can. I can also ping it from this computer which is also in the 192.168.10.x net.

Can you ping from the Uno to the server? aka from 192.168.10.127 to 192.168.2.100? Are you sure that port 3306 is not being blocked by the gateway (aka not ping, but login using 'this' computer or similar at 192.168.10.x)?

Sorry for the delay. Port 3306 is not being blocked. I'll start looking into pinging from the Arduino, but it should be the same because the Arduino and my laptop ('this' computer) are in the 192.168.10.x net.

Update: I most certainly can ping the server from the Arduino. I'll start looking at Windows MySQL clients to try it out.

Can you telnet from the Arduino?
telnet  3306
Anything come of that?


text:
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?

The ampere rating should be printed on the relays. Watts = Amps x Voltage

@Gerben. Thanks for the heads up! It says 5A 240V AC and the coil is 12V DC.

Than that's 1000Watt if you're on 220V AC, 500Watt if your on 110V AC (e.g. US). Good luck finding a 1000Watt CFL :-P

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.

Huh? If the OP builds a circuit to switch 12v (with a flyback diode) why would the relay board in question start a fire?

@DuncanC: There aren't many CFL bulbs that run on 12V, and the asker hadn't given the contact specifications yet.


text:
Arduino sketch works on ATmega1280, but doesn't work on ATmega328 (Arduino Nano)
I'm working on arduino based RGB LED strip controller.
This simple schematic was used to control 12V channels via 5V PWM signal from arduino:

I have also connected an HC-05 bluetooth module to be able to control it using android phone.
Android application, created for this project, is sending 4 bytes to set mode, red, green and blue colors. It looks like {0,255,0,0} to set static red color, {1,0,0,0} to start fade mode and {2,0,0,0} to start blink mode.
Here is my first demo video of this project:
click here.
The problem is that my code works perfectly on Arduino Mega 1280, but when I use Arduino Nano it works only with manual mode and blink mode. If I send {1,0,0,0} to turn on fade mode, LED strip starts to increase random color brightness and stops, before it gets to max value. In a moment LED strip turns off and doesn't react to bluetooth commands. Reset button helps in this situation.
I'm not sure, but I think there is not enough SRAM (only 2KB) on Arduino Nano to process fade mode data.
Source code:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(12, 13);

#define REDPIN 6
#define GREENPIN 3
#define BLUEPIN 9

#define FADESPEED 10
#define PANICSPEED 425

//0 - red
//1 - green
//2 - blue
int fadeColor = 0;
int panicColor = 0;

//values (brightness) for red, green and blue colors [0; 255]
int colors[] = {0, 0, 0};

long previousTime = 0;

//0 - manual, 1 - fade, 2 - blink
int ledMode = 0;

int fadeAmount = 1;

//if color is selected, it'll change brightness;
//when we got 0 or 255 brightness we'll change
//this flag and select next color in loop()
boolean fadeColorSelected = false;

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
  mySerial.begin(9600);

  randomSeed(0);
}

void loop() {
  long currentTime = millis();

  //data format - 4 bytes {mode, red, green, blue}
  if (mySerial.available() > 3) {
    ledMode = mySerial.read();
    int red = mySerial.read();
    int green = mySerial.read();
    int blue = mySerial.read();
    colors[0] = constrain(red, 0, 255);
    colors[1] = constrain(green, 0, 255);
    colors[2] = constrain(blue, 0, 255);
  }

  switch (ledMode) {
    //manual mode - just set received color on the led strip
    case 0:
      setColor();
      break;
    //fade mode - if color is selected, we'll
    //increase/decrease it's brightness by fadeAmount
    case 1:
      if (currentTime - previousTime > FADESPEED) {
        //change color (we can't choose the same color as previous
        //and we can't choose the color, if it's the last one,
        //because at least 1 color should be always ON
        if (!fadeColorSelected) {
          int randomColor = fadeColor;
          while (randomColor == fadeColor || isColorAlone(randomColor)) {
            randomColor = random(3);
          }
          fadeColor = randomColor;
          fadeColorSelected = true;
        }
        //depending on current brightness of selected color
        //we'll either increase, or decrease it's brightness
        if (colors[fadeColor] == 0) {
          fadeAmount = abs(fadeAmount);
        } else if (colors[fadeColor] == 255) {
          fadeAmount = -abs(fadeAmount);
        }
        colors[fadeColor] += fadeAmount;
        setColor();
        //when we got to max/min brightness, we should change current fadeColor
        if (colors[fadeColor] == 0 || colors[fadeColor] == 255) {
          fadeColorSelected = false;
        }
        previousTime = currentTime;
      }
      break;
    case 2:
      if (currentTime - previousTime > PANICSPEED) {
        int randomColor = panicColor;
        while (randomColor == panicColor || isColorAlone(randomColor)) {
          randomColor = random(3);
        }
        panicColor = randomColor;
        if (colors[panicColor] == 0) {
          colors[panicColor] = 255;
        } else {
          colors[panicColor] = 0;
        }
        setColor();
        previousTime = currentTime;
      }
      break;
  }
}

void setColor(int r, int g, int b) {
  analogWrite(REDPIN, r);
  analogWrite(GREENPIN, g);
  analogWrite(BLUEPIN, b);
}

void setColor() {
  analogWrite(REDPIN, colors[0]);
  analogWrite(GREENPIN, colors[1]);
  analogWrite(BLUEPIN, colors[2]);
}

boolean isColorAlone(int colorNumber) {
  if (colors[colorNumber] == 0)
    return false;
  for (int i = 0; i < 3; i++) {
    if (i != colorNumber && colors[i] > 0) {
      return false;
    }
  }
  return true;
}

Do you have any ideas why it happens?
If there is not enough SRAM, how can I optimize this code to solve the problem?

avr-size on the ELF says?

text 4770, data 22, bss 122, dec 4914, hex 1332

(data + bss) is less than 2KB, but it does not include dynamic memory allocated from the heap at run time...

You don't have any heap allocation. And I certainly don't see more than about 40 bytes in locals from the stack at any time.

I agree with you, but I have no idea, what can be wrong with it

Pin 13 has the Led on it. SoftwareSerial often runs better when using pins with interrupts. On the Uno that is Pin 2 and 3. I also find softwareSerial can be unreliable especially as low and high speed. So try the Uno on pin 2 and 3 and if possible use 19k or 56k which are usually reliable


text:
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.

Can you receive the correct serial string, if you use a different baud-rate?

Did you use existing gerber files or did you lay it out yourself?

@Gerben I have tried all of the Baud rates and none work.

@IgnacioVazquez-Abrams I did the schematic and PCB myself.

Find an oscilloscope and connect it to the TX and RX lines, right at the MCU. Based on the bit patterns I suspect that there is a lot of ringing or noise on the lines.

What USB-to-Serial chip are you using? The ATMega8u2?

@Gerben No, the 16U2.

@IgnacioVazquez-Abrams Scope results edited into original post.

HOLY CRAP. You need to take this serial connection issue to EE.SE now.

@IgnacioVazquez-Abrams Is it really that bad?

Subsequent to finding the solution on EE.SE, I recommend that we remove this question from here since it's not actually Arduino-related.

Could be an issue with the 16u2 or the 328. Try connecting pin 0 and 1 (Tx and RX) (also add a empty sketch to the 328). Try typing in the console. If all is well with the 16u2 the typed text should be echoed right back.

Related: http://arduino.stackexchange.com/questions/17/some-dude-named-avr-wont-let-me-upload-my-program-aka-avrdude-stk500-getsync

See this post. There are suggestions there for checking various things. I suspect you might have the "divide clock by 8" fuse bit set. Please post your test code. What is the horizontal scale on that scope image?

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.

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.


text:
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

"The professor was referring to the arduino pins with hex..." I'm not sure that I understand what this means...

PORTD and PORTC are the input registers. There is no point in clearing (cbi) them. Do you have external pull-up/pull-down resistors? As for the joystick; your just reading the digital value (0/1), not the analog (0..1023). You also need to use PWM to output different brightnesses. For readability I'd probably use sbi ddrb, ddb0; set PB0 to output. That way you don't have to use unreadable hex values. It also makes changing pin assignments a lot easier. It also saves a register. Though I now see your using it as a mask to set all leds at once (nice trick).

The professor was referring to the arduino pins with hex, but I couldn't find a mapping of the pins and their hex values - Well let's say you need to affect pin 10, in hex that would be 0A.

mov     r20, r20 >> 2       ; shift left twice  - looks like shift right twice to me, but whatever.

.include "/usr/local/include/atmega32u4.def" - the Uno uses the Atmega328P processor, so this is not the right file to include.

Did you know that the Arduino Uno uses the Atmel ATmega328P processor?
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.
You may want to read application note "AVR126: ADC of megaAVR in Single Ended Mode" and browse through the corresponding AVR126 example software.
(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",
"AVR ASM Introduction: A moron's guide to ADC"
and
"ATmega8 ADC Example"
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!


text:
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.

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.

thanks. so input sensibility should say how much voltage I should give them. however, what does input impedance tells me in this particulary case?

Input impedance will give you the resistance you should use to determine how much current will flow for a given signal voltage.

I only had a 470 kOhm resistance and I tried with it because it would result in less volume I believed. It worked. However, should I see 4,7V in the resistor between the pin and the input? My multimeter tells 0,01V.

You'll only see full scale if you're actually outputting full scale. Any sort of waveform will result in a value that is lower than maximum. Also 470kohm || 470kohm = 235kohm.

Two 470 kohm in parallel, right. Thanks for replying.

Sorry, I mean, I should see 4,7V but I see 0,01V in that 470k resistor. It's strange. 5V / (20k + 470k) = 1x10-5 A ... 1x10-5 A x 470k = 4,7V

I'd probably create my own voltage divider, and not depend on the 20kOhm input impedance. I also think you should AC couple (capacitor is series) it, but I'm not very good at this audio stuff, so I could be wrong.


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

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 :)

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.


text:
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, 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:

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

could you post those code samples?

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

Thanks BrettM!  I originally had the gyroscope using  the rx, ry and rz values but changed it at some point while playing with the accelerometer numbers,  thanks for reminding me to change it back,  I'd forgotten.  I was also planning to update to using the midpoint,  but had shortened it being a bit lazy.  Thanks again for helping me sort out my original question!