text:
HIGH and LOW reversed
i've got a seven-segment-display on my arduino-nano and want to write some numbers on it. The problem is that HIGH and LOW seems to be reversed.
If the output should be
0

it displays
-

I could solve this, replacing all HIGH and LOW through HIGHX and LOWX, and defining them reversed:
 #define HIGHX 0x0
 #define LOWX 0x1

but this is reversed and not a good solution...
The wiring is correct like this (just GND not connected):

But if i connect the GND, the hole display isn't showing something anymore.

Possibly related: http://arduino.stackexchange.com/questions/9925/a-led-should-be-lit-when-high-why-does-mine-only-burn-with-low

With the given schematic both your logic for segments and digits should be active high, so it looks like you made a mistake. Especially because you say it doesn't work anymore when you connect ground. Check that you have the right transistor and that it's connected correctly: Emitter should go to ground, collector to the display's common cathode. (Check that your displays are common cathode!)
It's not a good idea to define some version of high as low, that's only confusing. Instead name the signals:
#define DISPLAY_SEGMENT_ON HIGH
#define DISPLAY_DIGIT_ON HIGH

The image can be found at several places on the Internet, so I guess you didn't draw it. This is a common cathode display, and the transistors are NPN types. If your displays are common anode then the whole thing flips upside-down: The Ground rail becomes Vcc, and the NPN transistors should be PNP types. Then you will indeed have inverted logic, and you should define:
#define DISPLAY_SEGMENT_ON LOW
#define DISPLAY_DIGIT_ON LOW

reversing a boolean can be done using the ! operator.
So doing something like print(!true); will print false (or 0, I'm not sure.)
And you make a wrapper or class to abstract this specific/odd behaviour.
Like:
"setLedPin(pinnr,state){digitalWrite(pinnr,!state)} //The pins are inverted, LOW is ON, HIGH is off, this piece inverts it."
You may even make a class for these segment displays and pass to your constructor if it's an inverted or "normal" one.
Or even make two classes that implement the same interface, but for such a small difference, that shouldn't be necessary.

While it is technically correct, it's confusing for the human programmer. Best practice is using "positive" names/description like "DISPLAY_IS_ON" for all constant/variables. "Negative" names, like "DISPLAY_IS_NOT_ON" induce errors; you have to mentally compile what !DISPLAY_IS_NOT_ON means.

If your display is a common anode type, the following will happen.
Suppose you put a HIGH on D12, and LOW on D2 then current will flow from D12 through the base-collector diode of Q1, through the LED and out D2 to ground.
If you now connect Gnd to ground wihout changing anything else, the current from D12 will flow through the base-emitter diode of Q1 to ground and not through the LED.
So the display is probably of the wrong type for your design.


text:
Arduino OR operator
I have been trying OR conditional operator in a if condition statement in my arduino program and the result is not what I expected.
My program:
// three variables assigned to const int datatype as the
// pin numbers they are assigned to are  going to remain
// constant through out the program.
const int led1=10;
const int led2=11;
const int led3=12;

void setup(){
  // assigning the pins as input/output.
  pinMode(10,INPUT);
  pinMode(11,INPUT);
  pinMode(12,OUTPUT);
}

void loop(){
  control();
}

void control()
{
  int task1 = digitalRead(led1);
  int task2 = digitalRead(led2);
  if (task1==HIGH || task2==HIGH)
  {
    digitalWrite(led3,HIGH);
  }
  else
  {
    digitalWrite(led3,LOW);
  }
}

if the 'IF' conditional statement used without 'OR' operator is working fine that is not including both the tasks instead only one task either task1 or task2, else it is working without errors but the result is not as expected.
hardware part is all fine. i reckon that there is a problem with the OR || operator.

The 'or' operator is fine, your error lies elsewhere. But you do not give enough detail to help people diagnose your problem. How did you test the program? What behavior do you expect? What behavior does it show instead?

Could you try the ^ operator instead of (||), if this works for you, I'll explain it in greater detail.

I would also not advice using "led" as input. You might want to rename it to button or whatever other input device you're using.

@EdgarBonet - my objectice is to switch on the 3rd led pin high if any of the tasks i have assigned in my programme goes high. for example i have two push buttons thats assigned to task1 and task2 respectively.so when i press either of the push button the 3rd led pin must go high instead its low. i have tested it on PCB which has an atmega328 IC and the IDE is arduino IDE.

@FuaZe - i tried your input idea,but that didnt work as well. and i have no idea how i can use the bitwiseXOR operator for my application.

Could you please show the circuit schematic? How did you wire the LED on output 12? And the push-buttons? And why are those push-buttons called “led”?

Okay, could you specify when you want the led3 to go high. The code you have does it if any of these two is high and/or when both are high. What result do you think it should've had, or what do you want to achieve?

@EdgarBonet@FuaZe. thank you foremost for helping me out through this problem. i am a beginner to arduino platform thats why the variable name led occured to a push button  :-D. i wil make sure i work on the ethics of programming. your work is really appreciated.

Your code is correct for what you described you want it to do - raise led3 when either or both of led1 or led2 is high, and make it low otherwise. Some things to check:

Do the push-buttons pull their respective pins HIGH? (Pulling LOW is more common).
Are the pins pulled to ground with a 5K or 10K resistor, and not left floating, when the respective button is not active?
Real buttons need to be de-bounced. They behave as if their contacts bounce several times before making contact (even though that isn't really what happens). If this is an experiment and you hold the button down, even briefly, you should get proper results without de-bouncing, but it's something to be aware of as you move on.

If you aren't getting the expected result, as JRobert suggested you should look at your hardware. Ensure pull-ups/downs are being used correctly, your interpretation of your hardware's logic is correct (positive/negative logic), and maybe even use a simple sketch to check that everything is working correctly. Firstly I would simplify the control function. You could try replacing the OR with a bitwise OR, or changing your variables to booleans. Realistically, more code and a diagram illustrating your implementation would help us reproduce and troubleshoot this with you. I'm a little confused as to whether pins 10 & 11 are LEDs or Buttons. I would be happy to help you get a test program together if you can provide more detail. :)
void control()
{
    boolean task1 = digitalRead(led1);
    boolean task2 = digitalRead(led2);

    // Note that the if isn't needed
    digitalWrite(led3, (task1 || task2));

    // If your buttons use negative logic
    // digitalWrite(led3, (!task1 || !task2));
}

For humour-sake when I hit a problem that doesn't make sense, I rework my logic to break down the problem and output in stages, or use the Serial library to output what is going on periodically.

Arduino Serial Reference
Arduino Serial Tutorial

Typically for inputs and outputs I define a structure which buffers everything per IO, and write my code with a loop-based mentality, much like how a game loop is implemented in video games. It is easy to print and trace when troubleshooting, and the positive/negative/default-state logic is abstracted. This will help you get started if you are curious.

Game Loop Example

source: Stack Exchange

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

sort: votes


text:
Using Arduino BLE Nano to switch an electric circuit on and off
I'd like to use an Arduino Nano BLE to activate or deactivate an electric circuit.
I intend to use a relay to do so, but activating a relay seems to require a current with more intensity than what we can get out of a digital output (about 20 mA).
Is there a way to get more intensity out of a BLE nano ?
Are there others components that could behave the same way as a relay but could react from a digital output ?

You can use an NPN transistor such as a 2n2222 with a 1K or so resistor on the base to actuate a small relay.  Put a diode backwards across the coil.  You will see this circuit published everywhere.  Or you can use the optoisolated version common on those cheap relay boards.  Make sure your relay is rated to handle your ultimate load.

Thanks a lot for the comment. This could be an answer isn't it ? May I ask you for a reference link about how to use an NPN transistor with an Arduino ?

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


text:
Troubleshooting DC motor
I worked on the starterkit project #9 motorized pinwheel, and the motor worked just fine.
I then tried to add a potentiometer, and now the motor won't rotate at all any more (neither in the current nor in the project's baseline configuration). I also tried connecting the motor to the 9V battery directly, to no avail.
I did check the battery by briefly connecting a LED right away. The motor apparently also still generates current if I turn it manually (checked with a directly connected LED either).
What else can I do to check what's wrong with the motor? Is it possible that I somehow accidently killed it with my attempts with the potentiometer?

Have you tried a fresh battery? A good 9 V battery should blow a LED pretty fast if you tried to connect it directly.

If your motor doesn't work when connected to the 9V battery, either the battery is flat (which is likely since you were able to connect the LED without destroying it!! - they are a 2.5-3v part, not a 9v part) or the wiring to the motor is damaged. When you connect the motor directly to a 9v battery, it should turn pretty fast - may also work if you connect it to between 2 & 4 AA batteries.
9v batteries don't have that much energy in them... you would be better off with a battery pack with 6 AA batteries in it.


text:
How to draw a bitmap on a tft display?
I'd like to print a bitmap on my TFT.
I setup my screen with this library: http://forum.arduino.cc/index.php?topic=292777.0
It is like the Adafruit_GFX library (only a little bit changed). Everything works.
With the tool Img2Code I converted my image into a bitmap.
void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
                               const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

How to include this code and print the bitmap on the tft?

What is your question?

how to draw a xbm (bitmap) on my tft. I don't know how to include the big bitmap array.

As the function prototype you have show suggests, the data needs to be in a uint8_t array format.
void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
            const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

So your array data would look like:
const uint8_t myBitmap[] = { 0xff, 0xff, 0xc0, 0x00, 0xc0, 0xff,
    0xc0, 0xc0, 0xff, 0xff, 0xde, 0xad, 0xbe, 0xef,
    .... etc ....
    0xff, 0xff, 0xff, 0xff, 0xff
};

You then call the function with the needed parameters:
tft.drawXBitmap(10, 20, myBitmap, 100, 80, 0xFFFF);

That is assuming you want to place it at (top left corner) 10,20 and the bitmap is 100x80 pixels in size.  It will draw it in white (0xFFFF).


text:
How to read data from a rotary encoder with ATmega328
I'm using a home made "bare bones" Arduino, made with the ATmega328, and I need to read angle data from a geared DC drill motor, turning at speeds between 0 and 450 RPM. This is so I can use it as feedback for an angle control system implemented on the Arduino.
I've not yet bought the encoder. I'm waiting until I find a suitable one which works easily with Arduino.
I have already written the control algorithm. I'm using state variable feedback, and the algorithm depends on a getAngle() function that I have not written yet. This function is inside an if statement that executes every 0.2 seconds. It needs to return the angle of the DC motor in degrees.
My questions:

How can I implement this getAngle() function using a rotary encoder?
What is an example of a rotary encoder that is suitable for this application?
Will it be better to use the interrupt pins of the Atmega328, or use some other method?

I have seen a few library's on Arduino Playground that claim to make reading angle data easier, but how do I use them? I need something that is fast (it, and the control algorithm operations, both needs to finish before the 0.2 seconds sample time), and more importantly it needs to be easy to implement. I'm coming up to the project deadline so I don't want to have to spend a whole day figuring out how to implement this getAngle() function.
Thank you!

This question is cross-posted to Electrical Engineering SEx. Please don't do that.

You will have to use interrupts or otherwise the encoder might be rotating but your Arduino is doing something else than reading the encoder. By using interrupts, the encoder counter is always updated when the encoder moves. This also means that the interrupt function has to be very short so that it only takes a few cycles to complete and thus leaves the majority of the Arduinos computing time for your sketch.
Here is a code that I've used in many applications from CNC handwheels to servos and for reading extremely accurate angle sensors. It is dead simple, uses two interrupts to read the quadrature signal (A & B channel) and also makes use of Arduinos built in pull-up resistors to keep the channels held high for reliable readings.
Assuming that your encoder is an open-collector output and works with 5V, you only need to connect 5V and GND to it and then the A channel to the first interrupt pin #2 and channel B to #3. That's it for the hardware.
This code goes at the start of your sketch, right before setup() function:
const signed byte encoderDirections[] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
volatile long encCount = 0;

It defines a constant array that is used for finding the direction that the encoder has turned based on the previous value and the current value. It is defined as constant as it is never changed. Also a global variable calle encCount is defined as a long type variable so that the encoder can count in both directions. It is absolutelu imperative to declare it as volatile so that the compiler and the microprocessor never try to do any "shortcuts" when you use this variable, but instead always loads it from its respective memory address. This is done so because the interrupt can fire at any time and change the variables value without any other function knowing it.
Next, in your setup() function you will want to include these lines to make the Arduino pins as inputs with the internal pull-up resistors connected. The latter two lines attach the interrupts 0 & 1 (hardware pins pins 2 & 3) so that whenever the pin state changes (low to high or vice versa), it halts the microprocessors operation and jumps to the encoder_interrupt function immediately.
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
attachInterrupt(0, encoder_interrupt, CHANGE);
attachInterrupt(1, encoder_interrupt, CHANGE);

Last you will need the actual interrupt function that reads the encoder and updates the counter value.
void encoder_interrupt() {
  static unsigned int oldEncoderState = 0;
  oldEncoderState <<= 2;
  oldEncoderState |= ((PIND >> 2) & 0x03);
  encCount += encoderDirections[(oldEncoderState & 0x0F)];
}

First this defines a variable that holds the previous encoder value that was read from the pins 2 & 3. This is declared as static, so the value is stored in memory even when this function exits so that it can be used the next time the interrupt routine is run.
The second line moves the previous interrupt channel values two bits to the left (multiply by 4) to make room for the new values.
The third line is an interesting one. It reads the PIND, meaning all the pins at D register, which holds many Arduino pin states, including the pins 2 & 3 that we are interested in. Next it shifts this value 2 bits to the right (divide by 4) to "drop" the pin 2 & 3 states to the lowest bits of this byte. Then it AND's this byte with 0x03 to zero everything else but the lowest two bits that now contain the interrupt channel states. Lastly these two bytes are OR'd with the previous encoder state values to obtain a 4 bit number.
On the forth line this 4 bit number is AND'd with a 0x0F to make sure the highest 4 bits are zero to make sure this number is truly a 4 bit number that stays between 0..15, as it is used as an index for the constant array we defined at the start of the program to get the encoders direction of rotation and this is then added to the counter variable.
And now you have an accurate and extremely fast way of reading a two channel encoder to keep track of its position.
If you want to calculate an angle from the encoders current position, you could do a function like this, but you have to know the line count of your encoder and multiply it by 4 so you know the encoder pulse count per revolution. For example, a 100 line rotary encoder gives out 400 pulses per revolution. I assume that there is a constant defined as follows at the start of program:
const int LINE_COUNT = 400;

Also, this function assumes that the encoder could have turned more than one revolution and you just want the angle from some reference spot in degrees. Do take in to account that the long type variable will overflow after +-2 147 483 648 pulses as it is a 32 bit signed variable.
float getAngle() {
  long curCount = encCount;  // Store the current count.
  while(curCount < 0) {
    curCount += LINE_COUNT;
  }
  while(curCount >= LINE_COUNT) {
    curCount -= LINE_COUNT;
  }
  return (curCount / LINE_COUNT * 360.0);
}

First the encoder count is copied to a one use variable. then two while statements make sure the values is positive from 0 to LINE_COUNT-1, so it basically reduces the count to what it would be with just under one revolution. Then it returns the number of degrees by calculating the current position as a fraction of a one revolution count and multiplies this with 360 to get the degrees.

This is exactly what I was looking for. Thank you.

Your encoder choice will probably be driven by the mechanical requirements and the precision you need:

Runs occasionally, and briefly to 450 RPM or runs continuously, and often at the higher speeds?
Do you need position to e.g., within 3 degrees (7 bits)? Or 1/3 degrees (10 bits)? Or are you willing to count pulses from an index mark (this gets more complicated if the direction of rotation can change).

An n-bit encoder can probably be read whenever you need a position sample, so interrupts would probably not be necessary. With an index wheel (a pulse every x degrees, plus a separate pulse at 0 degrees, e.g.)
you would probably benefit from tracking the position at interrupt level and letting the main loop simply access the last known position.
Your getAngle() implementation depends totally on the choices you make above. If you use a Gray-coded encoder wheel, you'd need to convert the code to a binary fraction and multiply by 360 to get degrees. If you use an index wheel, getAngle() just reads the current pulse-count maintained by your interrupt routine and converts it to degrees. But you need an interrupt routine to count angle-pulses and reset the count on the index pulse (not especially hard to do).
Fixed-point arithmetic is pretty fast. Floating point takes longer. Depending on what else, besides position-keeping, your code needs to do, and how math-heavy it is, whether you can afford floating point. The floating point library will take more code space, too, but my guess is you'll be constrained by time more than by code-space.

There is no such thing as an encoder that "works well with Arduino" - encoders are encoders, and there are several basic types. As @JRobert said, you need to make an appropriate choice, and an encoder that will mechanically couple well with your drill motor is probably your primary criteria, and of course an encoder that can spin unrestricted (some are only for an angular range like 180 or 270 degrees); my guess is you'll want to put the encoder on the ungeared motor, rather than the geared output of whatever it is you're driving, to get good feedback from a cheap (i.e. relatively small number of 'pulses per rev') encoder.  Search on DigiKey, Mouser, online hobby stores, etc.  Then just deal with whatever type of encoder it is, hack its electrical interface into the Arduino:
http://www.digikey.com.au/product-search/en?pv69=848&FV=fff4001e%2Cfff80033&k=encoder&mnonly=0&newproducts=0&ColumnSort=0&page=1&stock=1&quantity=0&ptm=0&fid=0&pageSize=25
This (2-signal quadrature) encoder library for Arduino is superb, by Paul Stoffregen @ pjrc.com:
https://www.pjrc.com/teensy/td_libs_Encoder.html
For best results you'll want the 2 'quadrature encoder' outputs to go into 2 interrupt inputs on the Arduino, and there are only 2 available.  There is an option to run this library on only 1 IRQ-capable input (the other can go into any input), or even no IRQ-capable pins, but performance will suffer.
Sampling at only 5/second isn't much - don't be afraid to increase that substantially - 10 to 50 / second.
You also might want a PID control algorithm, depending on what your actual aims are.  the "PIDLibrary" by Breatt Beauregard on the Arduino Playground website is excellent.
Coding your 'getAngle()' function shouldn't be hard - for a rotary quadrature encoder, X pulses from the encoder corresponds to 1 revolution.  The 'encoder library' you end up using may provider more than 1 pulse output per actual pulse output from the encoder.  Do that math. Simple.

You are mixing two related ideas together.  Keeping track of encoders is best done with at least one interrupt in my experience. Whether or not you should use 2 or can get away with none depends on the speed of the shaft.  In my experience, RPMs generally encountered at the hobby level can be handled by 1.  So your interrupt code is interrupted by phase A rising or falling (Pin Change Interrupt).  At that point it read phase B, depending on the combination of A and B you are either going forwards (interrupt count+) or backwards (interrupt count-).  You know by specifications how many pulses you will have in a 360 degree rotation, and by modulo math, (e.g. x % 360) you will know how many degrees you are currently at.
The concept of sampling rate has to do with how often you read the current interrupt values, but they themselves will always be accurate and realtime.
Keywords to google volatile.  Also use signed long integers, not unsigned (don't ask how I know :| )
Not sure why the other answer suggested a PID, I didn't see anything in your question that would need it. For holding an angle you are more likely to use acceleration and deceleration, not PID.
Search google, you might find a way to build your own encoders.


text:
Mouser/DigiKey part number for female "stacking" headers?
Adafruit has this wonderful product: http://www.adafruit.com/products/85

What are these actually called? I've looked all over the place in Mouser and DigiKey and can't find them (now, granted, it's impossible to find anything in DigiKey since they discontinued their printed catalog, but I'm digressing...)
They are great for putting other things that are on breakout boards on a tightly-packed breadboard and still be able to attach probes.
Also, sometimes, the board you are trying to attach is this:
As you can see, there is a dip switch blocking the 8-pin header. This is fine for its final resting place (on a board with a socket), but putting it on a breadboard is a bit of a pain. I have quite a few of those, so even though the aforementioned adafruit part is pretty cheap and I could get a bunch, I'd rather know what the real part is called so I can get the sizes I need.
PS: In case you are wondering, and you like old-style nixie tubes, that's http://www.tayloredge.com/storefront/SmartNixie/DataSheets/Datasheet_SmartNixie.pdf.)

A Digikey.com search for samtec SSQ includes numerous longtail stackable headers (as well as some shorttail, or non-stackable).  However, looking at Digikey's prices suggests to me that adafruit.com's price is a bargain unless you are purchasing thousands of pieces.
Also see an arduino.cc thread on this topic.

This one has la posta, search for samtec SSQ and you'll get the stackable pins in all sizes.

They're actually called "Wire-Wrap Headers" and they pre-date the Arduino probably by at least 50 years or so.
They used to be used to create circuits between chips and components by wrapping wire around the pins and routing it to other connectors:

They have since been adopted as stackable headers on boards like the Arduino shields.
Being such old technology not many people make them any more, though thanks to their popularity on things like the Arduino they are starting to appear more and more from normal electronics supply companies.

Thanks. I'm old enough to know about WW headers, but the pins on these are not thick enough to be usable for WW, and the receptacle part is also too high. I've looked for WW  headers on mouser and digikey, and none match these. What I can find are the nice, machined (round, that is) receptacles that are meant for plugging in ICs. I have lots of those from days past, but they are too narrow to accept other headers.

If you are already ordering from Digi-Key, they do carry the same set of stackable headers from Adafruit.  It's just a bit hidden in an accessories family.  Otherwise it looks like Samtec is the only company Digikey carries that makes this style of connector.  Some dual-row long tail headers can be found using the term stackthrough, but this is mostly used in conjunction with PC104 connectors.

You can find stackable headers on eBay (ie. 141063314400 , 191576393028 , 271841707614). Futurlec also sell them pretty cheap - about half-way down the page.

That DIP switch is also connected to the 4 address pins so you could cut the switch off, plug it into a proto board and then set the address by selectively grounding those pins.


text:
How to protect my arduino, while hotplugging its power supply and other related electronics
The unsolved: when I connect power and signal lines to my Arduino - while power is on - I potentially kill it. I have fried 2 so far.
Situation:

I have build an DMX-controlled lighting fixture, which consists of the fixture and a Controller Box.
The fixture houses 2 Arduino's (5V), 2 steppers, 2 drives (36V), 2 fans (24V) and some temperature sensors.
The controller box houses 1 Arduino, amongst other electronics.

The controller box receives DMX and does calculations an send controls via I2C to the fixture.
There is a 8 pole connector between fixture and controller box.
1 - GND
2 - 5v
3 - 24v
4 - 36v
5 - CLK (i2c)
6 - SDA (i2c)
7 - signal line (used as charge pump)
8 - reset

All wires are shielded(but the shield is only connected AFTER the initial pins make contact)
When the power on the controller box is ON and i connect the light Fixture with the 8-pole connector my arduino goes to heaven.
My own idea's so far:

Voltage spike, because the connection wires is grounded after it connects the pins.
Some strange flyback? via the Arduinos in the light fixture? I connected everything straight to the 5v pins, not using the regulator.
no idea

Any help on a way to search for the most likely cause of the problem would be greatly appreciated.

This apparatus may well have dangerous design defects to begin with which would desperately need correcting, but even if not you should not try to hotplug it.  Think about what would happen if the 5v and 36v lines were connected but the ground was not yet - while the grounds of the 36v and 5v systems are presumably connected together on the remote side.  It seems like you could easily end up with 31v across the series combination of the 36v load and the Arduino... backwards.

Hmm, i dont understand fully. But would it mean that the 36V uses the 5v as a gnd? somehow and thus it puts 31V on the 5v side? That would really hurt the feelings of the arduino.

Yes - current will flow through whatever path exists.  Consider if that 36v gizmo has a big capacitor across the supply input.  Discharged, it will initially look almost like a dead short.  So pretty much the entire difference between the 36v and 5v rails briefly shows up across the Arduino components - and backwards at that.

Thanks Chris, Yes that gizmo has a big capacitor so this makes sense and is indeed a major design flaw. Hmm so 2 things to do. 1 find a connector that grounds first. 2. use SSR or relay to switch on the 36v powerdrive, only after i have a proper I2C connection made.

Also consider a Ruggedino as a 2nd tier kind of protection. While it's possible it would survive, I'd suggest making the design improvements first. http://www.ruggedcircuits.com/microcontroller-boards/ruggeduino-se-special-edition

If you ever drive an I/O more than a diode drop above or below its power supply rails, the internal ESD protection structure will begin to conduct.  The internal structure is only there to keep the part alive during normal handling, i.e. in a factory but not for the situation described above.  If the current in this structure is allowed to go high enough, it looks like an SCR and "Latches" up.  When latch up occurs the device, like an SCR, will keep conducting as much current as the power supply rails are capable of until the current is removed and usually results in device destruction.  The way around this is to limit the current that may flow into a pin, and prevent current from forward biasing the ESD structure:  http://www.tayloredge.com/reference/Electronics/EMIESD/InputProtection.pdf

There's usually a number of scenarios that can cause hardware to go poof when you plug it in to a live system.  Most of them you have managed to identify, so I won't go into detail here.
Suffice it to say that creating hot-pluggable devices isn't as straight forward as you would at first guess.
There are two main critical things to consider when designing your system:

Suppression

Invest in TVS diodes to suppress ESD.  All the IO pins that connect to the outside world that will be liable to be disconnected or connected at any time should be protected by adequate suppression.  Any inputs should also ideally be tied to a default state with pullup or pulldown resistors so they aren't left floating.

Connector

The connector itself is pretty critical.  Hot-plug connectors typically have different pins of different lengths so that they connect in a specific pre-determined order.  Normally you want your ground and shield to connect first.  Then your power supplies, and finally your IO pins.  Doing it in any other order is asking for trouble - such things as back-powering through the IO pins if the supply hasn't been connected.
If you can't use a proper hot-plug connector then there are ways you can simulate it internally.  You can add hardware (buffers, reed relays, FETs, whatever, depending on your signals) which normally isolate the signals from the MCU, and only when the MCU is powered up and ready does it then activate the buffers to allow the signals through.  Of course, the buffers themselves have to be able to withstand any possible back-powering etc while the plug is being inserted.
One other small trick is to ensure that all your IO lines have a series resistor in them.  This limits the maximum current that can ever go in or out of a pin (at a specific voltage of course) to a level that is safe for the hardware.  470Ω - 1KΩ are good values.

that makes a lot of sense to have a connector with different pin lengts to connect to ground first. I'm going to try and source that. Would those TVS diodes influance the fast i2c signals? The idea was nto to make a Hotswapable device, its just that the poroject got out of hand and it needs to go on tour for 1 or 2 years and i'm sure this will happen....

TVS diodes shouldn't affect the signals, no.  They only come into effect when you get out-of-range voltages.  For more info on hot swap connectors you can read wikipedia: http://en.wikipedia.org/wiki/Hot_swapping

Thank you Majenko, you gave me new leads to research. thats great help, thank you.


text:
How to define function/macro so it is accesible throughout various cpp files
I recently came across this nice SerialPrint() implementation:
void StreamPrint_progmem(Print &out,PGM_P format,...)
{
  // program memory version of printf - copy of format string and result share a buffer
  // so as to avoid too much memory use
  char formatString[128], *ptr;
  strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
  // null terminate - leave last char since we might need it in worst case for result's \0
  formatString[ sizeof(formatString)-2 ]='\0';
  ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
  va_list args;
  va_start (args,format);
  vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
  va_end (args);
  formatString[ sizeof(formatString)-1 ]='\0';
  out.print(ptr);
}

#define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
#define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)

I want to use it in my more complex projects to save precious RAM space.
This works really well when I have just one *.ino file where I'm using the SerialPrint() function.
When I try to use it in my more complext projects, which consist of a central *.ino files and several .cpp/.h files (mostly one cpp/h pair per class).
The problem is if I put the code below into the *.ino file, it will not be known inside any of the *.cpp files. The compiler is not complanining, but I'm never seeing the serial output of my code.
Any ideas how to fix it?
I've tried putting this code in a central global.cpp/h file which I include everywhere, but it does not seem to work (no output on serial).
Thanks in advance!-

This looks to me like an inefficient emulation of vsnprintf_P(). Also, if you want to use printf-style formatting, why not just use printf()?

@EdgarBonet: Correct me if I'm wrong but I don't think the functions you mention are availabe in the arduino IDE. The code I linked to allows use of printf() like functionality with the added extra that it puts the formatting strings in progmem, saving precious RAM in the process.

They are available. On AVR-based boards, like the Uno, the Arduino library is built atop avr-libc, and all the functionality of this library is available. The only caveat is that you have to set up stdout before using it, c.f. the documentation on stdio.h. You can have the formatting string in progmem too by using printf_P() and the other _P variants.

Have you thought of turning it into a small library?
libraries/StreamPrint/StreamPrint.cpp:
#include <StreamPrint.h>

void StreamPrint_progmem(Print &out,PGM_P format,...)
{
  // program memory version of printf - copy of format string and result share a buffer
  // so as to avoid too much memory use
  char formatString[128], *ptr;
  strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
  // null terminate - leave last char since we might need it in worst case for result's \0
  formatString[ sizeof(formatString)-2 ]='\0';
  ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
  va_list args;
  va_start (args,format);
  vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
  va_end (args);
  formatString[ sizeof(formatString)-1 ]='\0';
  out.print(ptr);
}

libraries/StreamPrint/StreamPrint.h:
#include <Arduino.h>

extern void StreamPrint_progmem(Print &out,PGM_P format,...);

#define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
#define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)

Then in your code, wherever you want to use it:
#include <StreamPrint.h>

You can read more about writing libraries here: http://www.arduino.cc/en/Hacking/LibraryTutorial

Thanks for your answer. I tried this but got some compiler errors: StreamPrint.h:6:68: error: initializer fails to determine size of '__c' StreamPrint.h:6:68: error: array must be initialized with a brace-enclosed initializer StreamPrint.h:6:94: error: invalid initialization of non-const reference of type 'Print&' from an rvalue of type 'const char*' StreamPrint.h:3:13: error: in passing argument 1 of 'void StreamPrint_progmem(Print&, const char*, ...)'

Compiles fine for me. What are you using?

Normally visual studio 2013 with VisualMicro, but I tried in arduino IDE 1.6.1 and got the same error

It must be the code surrounding it then, since I can't get it to fail at all.  Try posting your test code.

Yep I had borked it... I started a new test sketch and suddenly everything works. Found out I had the code also still in my main *.ino file of my other big project.. Thanks for your help!


text:
How do I make a atmega 32u4 mp3 player?
Is there a way to use the atmega 32u4 breakout board to make a mp3 player without the mp3 shield?

I don't think it has enough CPU power to decompress mp3. I think wav-files playback is possible.

You don't.
A basic ATmega lacks the computational (and perhaps memory also) resources for mp3 decoding.  And even if you do decode to a linear PCM format, you do not have a good way to output it.
You can playback linear PCM data by pulse width modulating a pin, but the limited clock rate will result in limited resolution, and thus poor fidelity.  You will also end up with a low sample rate, making it hard to avoid audible artifacts.
The situation can actually be somewhat better with an ATtiny85 - still no MP3 decoding of course, but you can clock the counter/time block at a higher rate and so playback PWM audio with higher fidelity, provided you are willing to tolerate the inaccuracy of the onboard clock oscillator that may shift your audio frequencies by a small amount.
If you want to do MP3, you will need either a more powerful processor (often no more expensive than the one you have, and typically cheaper as a module than anything "-duino"), or else a dedicated function chip to act as a coprocessor for that purpose.

The quality of most MP3 is so bad to begin with. Do you have any empirical data as to how much worse it will be? Are the on board clock oscillations even detectable by a human ear?


text:
What are the basic steps to make a printed circuit board?
I created a shield for Arduino on a soldering board. The next step shall be to implement the circuit on a PCB. I'm new to this, so I'd like to know what the basic steps in designing a PCB are.
More specifically,

What software do I use for this? Is free software sufficient, or do I get substantially more value from a commercial package?
Can I have a single PCB printed by a commercial provider, or are there minimum quantities? What is the approximate cost for a shield-sized PCB in a small quantity - is it in the tens, or rather in the hundreds of bucks?

Of course, any pointers to good tutorials on the Web will be appreciated,  too!

Software packages are, amongst others

Fritzing (more target at beginners)
Eagle (free for board of size 100 x 80 mm (4 x 3.2 inches)).
KiCad (open source)

Companies that make you pcb in small quantities are e.g.

OSHPark
seeedstudio
Dirt Cheap Dirty Boards

I personally create my own double layer PCBs at home. I first started with the toner-transfer method, but now use photo lithography. I etch in Hydrochloric acid and hydrogen-peroxide. I can have a finished board in 1-2 hours, instead of having to wait a week or so. Great learning experience.

What software do I use for this? Is free software sufficient, or do I get substantially more value from a commercial package?

There are plenty of good free ones, or free versions of commercial ones. Use the one that best suits your way of working - they are all different, try some out and find out which you like best.  I use a free one for all my work (but then I am a FOSS junkie).

Can I have a single PCB printed by a commercial provider, or are there minimum quantities? What is the approximate cost for a shield-sized PCB in a small quantity - is it in the tens, or rather in the hundreds of bucks?

Generally, no.  It'd be just too costly.  There are small quantity houses around though, and I often use iTead for my prototyping, since they will do batches of just 10 boards at a reasonable cost.
The basic steps in designing a PCB though are:

Design it as a schematic
Lay it out as a PCB design
Get a prototype made
Build it
Correct the mistakes
Go back to 3

If you only want one circuit and it is a pretty simple one you might want to give making the PCB yourself a go - it's quite rewarding and if nothing else gives you good insights into PCB design requirements and how best to lay out a PCB and the tracks for a good reliable etch.  If you have a laser printer the Toner Transfer method of home PCB production is good.

it seems that your toner transfer link above is broken.


text:
Powering an Arduino Pro Mini directly from a LiPo
I've recently purchased an Arduino Pro Mini, 3.3V version. I've planned to use it in a diy remote: I've empty a ps2 remote, just left the buttons, and the board will be inside. The remote will be wireless: I use an xbee, which also fit inside the ps2 controller. To power it, I use a one cell Lipo, which will empower the Arduino and the XBee, here comes my issue: As you've seen, there will be many things an a single ps2 controller, so I try to minimize connections and external components. But, the XBee will take more than the maximum 150mA provided by internal regulator of the Arduino. So, either I use an external regulator, or I directly plug the lipo in the VCC pin if the Arduino. Can the board survive? If the voltage is greater than 3.3V, will it damage the board?

also, is that XBEE 3V3 or 5V? You should be ok just connecting the lipo directly to 3.3V+.

I removed the 3v3 regulator on my pro mini by accidentally connecting a lipo directly to the Vcc pin, which roasted the regulator enough to desolder itself! Luckily, no other damage.

The only thing about the 3.3V Pro Mini that is actually 3.3V is the 3.3V regulator.  The main chip (pretty much the only other component) is good for anything from 1.8V up to 5.5V.
Running direct from a 3.7V LiPo or Li-Ion will be perfectly fine.  You might want to disconnect or otherwise disable the regulator though to reduce current consumption - the latest Minis have a solder jumper SJ1 for doing just that, but older versions you may want to actually cut the 3.3V OUT pin of the regulator or de-solder it entirely.


text:
How to tell Arduino Uno that I pressed or released a key on PC keyboard over serial?
I want to implement a simple musical keyboard with Arduino using tone() and noTone() functions, etc.
The desired behavior is:

While PC and Arduino are connected via USB/Serial...
...when I press a key, a corresponding note starts playing...
...and if I release that key that note stops playing...
...or if I press another key, another note replaces the former one.

So, basically, instead of "while key is pressed" logic, I would like to just write a byte to serial when a key is pressed, write nothing while the key is held pressed, and write another byte when that key is released.
I will be using a Python script in the PC, but examples in other languages, or just using a plain serial monitor, are fine.

PCs' keyboards send key-down and key-up signals to the PC so that much is available already. But that gets translated into letters including generating key-repeats at a fairly low level - BIOS, I think. Getting that deep from a higher level language like Python may be a challenge. A search for "windows keydown" returned a few hits that looked promising.

UPDATE: When I posted this answer I had not yet any knowledge of the Processing Language. If you came to this answer with the same intention I had (the question title), I strongly suggest you to use Processing instead, which has much more straightforward keyboard event capturing and serial communication working out of the box with minimal code.
A question showing this in action is here: https://stackoverflow.com/questions/18366482/processing-to-arduino-with-keyboard

After realizing that what I actually wanted was to "capture keyboard events", I ended up using PyGame due to its minimalistic setup. Now I can send whatever I want to the Arduino using PySerial.
PS.: Don't be fooled by the lame aesthetics of PyGame website, it is a very mature gaming platform.
Full code here: https://github.com/heltonbiker/Experiments/tree/master/SerialMusicKeyboard
#/usr/bin/env python

import pygame
import serial
import glob
import time

def pygameSetup():
    pygame.init()
    screen = pygame.display.set_mode((468, 60))

    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((250, 250, 250))

    if pygame.font:
        font = pygame.font.Font(None, 36)
        text = font.render("Shut up 'n play yer keyboard!", 1, (10, 10, 10))
        textpos = text.get_rect(centerx=background.get_width()/2)
        background.blit(text, textpos)

    screen.blit(background, (0, 0))
    pygame.display.flip()

def main():

    pygameSetup()

    initialized = False

    while not initialized:
        try:
            serialpath = glob.glob('/dev/ttyACM*')[0]
            ser = serial.Serial(serialpath, 9600)
            initialized = True
            print "serial up"
        except:
            time.sleep(500)
            print "waiting for serial"

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.KEYDOWN:
                print event
                ser.write(chr(event.key))
            elif event.type == pygame.KEYUP:
                ser.write(chr(0))

if __name__ == '__main__':
    main()

@heltonbiker consider accepting any of the answers as "the answer" as currently, the question seems "unanswered". While you actually have found something usefull. By accepting an answer, no-one with the intention of giving an answer will waste time on this question.

As mentioned by Spiked3 there are a few ways to hit the ground running with C#.
Firstly, as detailed by Majenko, you will need an application running on your PC and some code on the Arduino to interact with this. For the desktop application, the two easiest ways to get started with C# are with WinForms, or XNA/MonoGame. WinForms is targeted at Desktop application development; think legacy desktop apps. Although it is not the current defacto standard (replaced largely by WPF) it is very simple and akin to Swing in Java to use. MonoGame and XNA are targeted at video game development. The latter would be my preference as it lends itself more towards real time applications, and has a game loop much like the Arduino so it is very easy to start using. The caveat is that there is more setup involved, but you will probably find this the friendliest and best supported.
Firstly, The Code! So for the Winforms Route, We have something like this:
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            Debug.WriteLine(" Key Up! ({0})", e.KeyCode);

            // TODO: Talk with Arduino
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            Debug.WriteLine(" Key Press! ({0})", e.KeyChar);

            // TODO: Talk With Arduino
        }
    }
}

To get to this point, fire up a new winforms project, and open up the 'Form1' code (the default window which is added to the project) add the methods as outlined above. You will need to go to the designer afterwards and add events for on KeyPressand on KeyUp to tie these functions to the Window. You can do this by clicking the Window, then opening the Properties Panel, and then clicking the lightening bolt. You will see a list of event names; find the corresponding events (Key Press and Key Up) and associate them with these methods.
From here, you can perform some logic when a button is either pressed or released.
The monogame or XNA approach is a bit simpler to follow as there is no hidden magic; but may be more intimidating if you're not familiar with C# and the project type.
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Diagnostics;

namespace GameName1
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;

        KeyboardState currentState;
        KeyboardState previousState;

        public Game1() : base()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            // Get state management started
            currentState = Keyboard.GetState();

            base.Initialize();
        }

        protected override void Update(GameTime gameTime)
        {
            // Listen for exit command
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // Update the state of your keyboard object
            previousState = currentState;
            currentState = Keyboard.GetState();

            // Detect Keypress of key 'F'
            if (currentState.IsKeyDown(Keys.F) && previousState.IsKeyUp(Keys.F))
            {
                // F Key has been pressed
                Debug.WriteLine(" Key Pressed! ({0})", 'F');
                //TODO Talk to Arduino
            }

            // Detect Keyrelease of key 'F'
            if (currentState.IsKeyUp(Keys.F) && previousState.IsKeyDown(Keys.F))
            {
                // F Key has been pressed
                Debug.WriteLine(" Key Released! ({0})", 'F');
                //TODO Talk to Arduino
            }

            base.Update(gameTime);
        }
    }
}

In either case, you will need to get yourself set up first. Get a compy of Visual Studio Community from the link below, and install MonoGame if desired. Then do some C# tutorials to get comfortable in your new environment.

Visual Studio Community Edition
Mono Game
C# Tutorial
C# Mono Game Tutorial
C# WinForms Tutorial

Lastly, you will want to talk with your Arduino. This can be done by implementing a compatible Serial interface between your desktop application and your Arduino. See the tutorial below to get started!

Arduino C# Serial Tutorial

I hope this information is useful. There is a very broad range of topics mentioned here, and it may seem overwhelming at first - but C# is a very idiosyncratic language in that it permits rapid development in many different scenarios, and I think that you will find it rewarding to conquer the learning curve.

Incidentally, my current job is C#/WPF developer, so creating a GUI app is something I am quite familiar with. The greatest "paradigm change" here was to realize that everything I wanted to do regarding "capturing keyboard events" is already implemented in any GUI toolkit (I ended up using PyGame), while most examples use command-line tools and/or serial monitors on a terminal.

Yeah I do WPF too (spiked3.com). As far as I know SlimDX has more or less replaced XNA for current development. In any case keyboard events are native to all windows development environments, except raw python, that I know of. Why would you not just use WPF?

Don't get me wrong - I love WPF, and strongly dislike WinForms in contrast, however I generally find myself strictly following the MVVM design pattern with WPF and consequently I find it difficult to get in that 'single dirty file with a blocking UI thread' mindset. :)

I just took a quick look at SlimDX - it appears that it more or less just wraps DirectX, which isn't a bad thing. I think MonoGame and XNA will still be simpler for most use cases where you would use managed code, as there is a lot of automation that I am sceptical would be included with SlimDX, especially the content pipeline. I get the impression SlimDX is related to SharpDX, and that it's best equivalent to XNA would be MXA. https://mxa.codeplex.com/

Mxa says it is also based on sharpDX, and it just doesnt have the volume yet of slimDX. I'd love to continue the conversation, but not the right place. Email me spiked3 @ gmail com if you want to talk more.

You need to come up with a protocol.  Then you need to write the PC software.  The PC software will monitor the keyboard, and when you press a key it will send a certain signal through the serial port. When you release the key it will send a different signal.
How you arrange that is entirely up to you.
You might implement a protocol that sends something like:
b4
c4
d3
off
c3
f3
off
g4
off

Where the first letter is the note, the second letter is the octave to play that note in, and the word "off" is to stop playing.
I don't have a clue (and probably few people here do) how you'd program the PC end in Python.  It most likely depends on what platform you're working on as to what kind of interface you can build.

It sounds really simple, but as I think about it, the python twist makes it near impossible.
First the simple part.  What you are describing is very close to the MIDI spec. It define a sequence of character for note on/note off events over serial. I'm rusty but it something like this x'90' + chan1..16, note, velocity (3 bytes for note on) and x'80' + chan1..16, note, velocity (3 bytes for note off).  (spec)
Firmata took that idea, and turned it into a remote arduino protocol, where instead of a note, a pin number is used (eg pin on/pin off) and you could dig into the firmata that is included with Arduino for some ideas.
The hard part is the keyboard.  I use a function getch, that I define myself based on whether the script is running on a POSIX host or not (although that is technically inaccurate).  It is described at
https://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user
but unfortunately it only waits for a keystroke and provide no information about a key release. You are going to have to dig deep and probably write some platform specific code, maybe even a C .DLL, to get that kind of interaction in python. Handling key down/up is trivial in any language but python (for windows anyhow, dont know about *nix)

Simplest would be to use a GUI toolkit to make a GUI application.  GTK+ would do the job - anything that can give you keypress / keyrelease events.

yeah, that is why I said it is trivial in anything but python. Not sure how (or even why) it works with python GTK.

@Spiked3 when you say "anything" but python, could you suggest something to use instead? I am using python just because it's what I am most familiar with, but it's not fundamental at all to use strictly python.

C# would be (is) my primary choice. I'm looking for a piano keyboard gtk app that might run with python but have not found any yet.  I think even Processing probably could do it but I am not sure. It is probably worth looking at though, since it is so similar to Arduino (IDE)

https://processing.org/reference/keyPressed_.html

@Spiked3 Python is just a language - the toolkit is programmed (or can be) using Python (there are Python GTK+ bindings), so you are programming in Python to create a GTK+ GUI which can handle the key events.  Of course, you have to be some kind of psycho to even want to use Python in the first place, but that's another story...

lol - IKR? Yeah that is kind of what I meant by digging - I assume the GTK people had to dig and write DLL level stuff to get keypress, but to take advantage of that, you have to do it all GTK - so its not really a practical solution.  I'd say go with Processing for something simple.

I went with PyGame, actually it was trivial after I figured out where the problem was (not the Serial part, not the Arduino part, but the Keyboard-Event-Capturing part, which is trivial in PyGame and PyGtk). Frankly I am surprised by the negative comments on Python + Gtk, I assume you are not familiar with them, and by the way any GUI toolkit in any language should be able to capture keyboard events and handle them by sending bytes over serial.


text:
Where are the digital and analog pins for the adafruit atmega 32u4 breakout board?
Which pins are the analog and digital pins? I've been searching the internet for an hour and I could get an answer.

The information is right there on the product page for you. It took be a total of about 4 seconds to find it.
http://ladyada.net/products/atmega32u4breakout/


text:
Multiple nodes with the same receiving and transmitting address
I want to make a network with arduinos and nrf24l01 chips. The network will be like this:

1 master arduino
multiple (no specific number) slave nodes

I want all nodes to have the same receiving and the same transmitting address and the master arduino to understand which one send the message from the message itself.
For example:
Master:
Receiving: 0xABCDABCD71
Transmitting: 0xABCDABCD01
Slave 1
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71
Slave 2
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71
Slave 3
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71
Slave 4
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71
When master send a message, all nodes will receive it.
What I want to ask is :

Is that possible?
Will there be any problems?
Is there any other way so I can add more nodes in the future without changing the code?

That will work. The only possible problem would be collisions, if the nodes send a lot of data (having different re-transmit intervals might help here).

Generally, having same RX address on all slave nodes is a bad idea except when the slaves are receive only.  If you want to receive data from a specific node, then they should have different addresses, use ACK_PAYLOAD and you poll each one in turn.

Can we do it for only multiple slaves to single data receiver?
I want to get 13 IMUs( gy9250) data on single nrf24lo1 receiver is it possible?

as well as comment #1 the other thing will be the ack packets that the slaves will send back to the master to confirm message recieved. with all slaves sending back a ack at about the same time there will be no way for master to tell which ack is from which client, and thus who needs a retransmit. a way around this is to turn off ack for the clients and make the master transmit max times regardless. there is a rf24 fork that has broadcast mode, the makes it more easy to specify not to wait for ack before retransmitting

Using this as a base library and this as an simplifying overlay (there's actually RF24Mesh too) will make this possible very easily.


text:
What is wrong with my 32u4 breakout board from adafruit?
I recently bought the atmega 32u4 breakout board from adafruit. I uploaded a sketch, then it says that there isn't a timer 2 on it and it won't do as I programmed my sketch. how can I fix this?

Please include some more information - especially the code you're trying to run.

You will need to port any libraries and code that depend on timer 2 to the '32U4 architecture. There is no way to add timer 2 to the chip, and it is likely that trying to force it to use a different timer won't help since it may configure things the other timer doesn't have.


text:
Atmega328P-PU: Programmer is not responding
Few days ago, I built my own custom Arduino on the breadboard. It is built according to tutorial on http://www.crash-bang.com/resource/breadboard-arduino/. The Atmega328P-PU is already burned with the Arduino bootloader with simple blink sketch.
For the programmer, I decided to use the Arduino USB2Serial. Again, it is connected as shown on crash-bang site. Problem is I get this error when uploading a different sketch:
avrdude -Cavrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:build244630154737317489.tmp/sketch_may23a.cpp.hex:i

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : Arduino
     Description     : Arduino
     Hardware Version: 3
     Firmware Version: 4.4
     Vtarget         : 0.3 V
     Varef           : 0.3 V
     Oscillator      : 28.800 kHz
     SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "build244630154737317489.tmp/sketch_may23a.cpp.hex"
avrdude: writing flash (450 bytes):

Writing | avrdude: stk500_recv(): programmer is not responding

Most of the time I do not even get to this point and just end up with something like:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xf5

What I have done so far:

I already tried to reset Arduino just before uploading the sketch.
According to the avrdude, bootloader is fine.
Reinstalled drivers, Arduino IDE
Changed the USB cable and connected it to another USB slot
Burned new bootloader using ArduinoISP

Thank you for help.

Is there a reason why you don't want to stick with ISP?

This would require to buy another programer, would not it? I hope someone could know the solution to get current programmer to work...

Your time is more valuable than a (hardware) programmer.

"Step 3 says to connect +ve rail –> AVCC (pin 20) and +ve rail –> AREF (pin 21). You can leave those pins not connected. "
+ve rail should not be connected to Aref. The +ve rail will connect via the internal operation of the ADC mux.
AVCC and both Gnds should be connected per the datasheet:
5.2.7. AVCC
AVCC is the supply voltage pin for the A/D Converter, PC[3:0], and PE[3:2]. It should be externally connected to VCC, even if the ADC is not used.
28.2.
AVCC must not differ more than ±0.3V from VCC.... Optionally, AVCC or an internal 1.1V reference voltage may be connected to the AREF pin by writing
to the REFSn bits in the ADMUX Register. The internal voltage reference must be decoupled by an external capacitor at the AREF pin to improve noise immunity.
If you connect Aref to the +ve rail externally, and then select the internal reference, things can go bad.
FTDT thru 0.1uF cap to Reset, with 10K pullup, and reverse biased diode to VCC, works for me in plenty of designs.  Not sure why it does not work in all cases. The diode dissipates any spike on the Reset line to keep the chip from thinking high voltage programming mode is being started.


text:
Is it possible to use the DASH7 protocol in an arduino?
I've been reading about the protocol DASH7 but can't find much documentation about it. There seems to be a protocol stack called OpenTag writen in C and I want to know if there is something familiar written in arduino code and why can't I find a lot about this tecnology.

The google-fu is weak with this one. http://www.dash7-alliance.org/?page_id=34  http://www.wizzilab.com/solutions/wizzikit/ http://en.wikipedia.org/wiki/DASH7

@JRE a development kit and a Wikipedia article... meh, It's not "Taylor Swift" popular.

You ask if Dash7 can be used with an Arduino and mumble about OpenTag.  I point you at developer kits that mention OpenTag and OSS as libraries and you go Meh.  Did you already know about them?  If you did, what isn't clear about how it works?

@JRE The second part of the question was to know why the technology wasn't popular. It had passed years and I can't see any new developments about it. I though you where trying to contradict it by showing those links, my bad.

I hadn't heard of DASH7 before, but I checked the website and I'm not enthusiastic. To get the free(!) spec the site plays games with you, demanding to add it to a shopping cart, asking for a lot of personal information, etc. They're a nuisance. If that's the level of service for people whom you have to win over for your product, what level of service can you expect later on, after you've been won over already?


text:
Starting Off Low-Level Port Access
   I'm trying to teach myself some low[er] level code, but I just can't get it to work. I've tried OR-ing stuff in, AND-ing stuff in, and just straight up defining stuff, but it's not blinking! What am I doing wrong here?
I am using an Arduino UNO R3 DIP for this. I am just using the on-board LED, (on pin13/PORTB_5)
Current code:
#define STATE B00001000
#define ZERO B00000000
void setup() {
    DDRB = STATE;
    }

void loop(){
    PORTB |= STATE;
    delay(500);
    PORTB &= ZERO;
    delay(500);
    }

It would probably help if you were using the right pin.  In the pins_arduino.h file for the Uno is this diagram:
//                  +-\/-+
//            PC6  1|    |28  PC5 (AI 5)
//      (D 0) PD0  2|    |27  PC4 (AI 4)
//      (D 1) PD1  3|    |26  PC3 (AI 3)
//      (D 2) PD2  4|    |25  PC2 (AI 2)
// PWM+ (D 3) PD3  5|    |24  PC1 (AI 1)
//      (D 4) PD4  6|    |23  PC0 (AI 0)
//            VCC  7|    |22  GND
//            GND  8|    |21  AREF
//            PB6  9|    |20  AVCC
//            PB7 10|    |19  PB5 (D 13)
// PWM+ (D 5) PD5 11|    |18  PB4 (D 12)
// PWM+ (D 6) PD6 12|    |17  PB3 (D 11) PWM
//      (D 7) PD7 13|    |16  PB2 (D 10) PWM
//      (D 8) PB0 14|    |15  PB1 (D 9) PWM
//                  +----+

That shows that pin D 13 is PB5 which would be a binary value of 0b00100000 not 0b00001000 as you have, which would be PB3, or pin D11.
The only way I can come up with 0b00001000 is if I count from the left (wrong) and start at 1 (wrong) rather than count from the right (right) and start at 0 (right).

Yeah, that's exactly what I did... I'm used to the other bit order, so that's what screwed me up. And also counting from 1... Oops. But thanks!

The other bit order? There is only one bit order. All numbers count from the right. After all, 5 + 7 isn't 21, it's 12. The same applies to all bases - base 2 (binary), base 16 (hexadecimal), base 60 (sexagecimal)...

I was thinking of MSBF vs LSBF haha

That only makes any sense in the scope of serial communication.

Oh, by the way - your logical operators are pretty pointless.  The OR is OK since it just turns on one pin, but the AND is bad, since it turns off ALL pins.  You should be ANDing with 0b11011111 to maintain the state of all the other pins.  That would be equivalent to PORTB &= ~STATE.


text:
SoftwareSerial.h alternative with AVR (Two Serial/UART ports in atmega328p)
Arduino pins can be used as UART using the SoftwareSerial.h library. Is there any alternative for AVR?
I need more than one serial port on a ATmega328P, but i don't use Arduino.
SoftwareSerial.h is tied to Arduino.h and Arduino pins. I do not use Arduino, i use avr-gcc with atmega328p and atmega8.

Sorry my english

Software serial should only be used as an absolute last resort. If you are having to look at using it then you aren't using the right microcontroller.  Don't just use a certain microcontroller "because you always have", or "because the arduino uses it" - use the right one for that job, and if you need multiple serial connections then choose one that has multiple serial ports in it.  There's plenty to choose from, even within the same family of chips, that provide more than one serial port, so would require minimal changes to your project to use them.

AVR274 describes a single-wire, half-duplex software UART.
AVR304 describes a half-duplex, interrupt-driven software UART, and AVR305 describes a polled alternative.
AVR307 describes implementing a half-duplex UART using a USI.
All code associated with each app note can be downloaded from Atmel's website.

where can I download them?

Do a search on the app note handle.


text:
Issue with Embedded Coder Target for Arduino
I am using the embedded coder target for arduino following this: (http://www.mathworks.com/matlabcentral/fileexchange/30277-embedded-coder-target-for-arduino). I am having problem while running the myarduino_blink.slx demo.
My MATLAB version is R2015a, and I am using an Arduino Uno. I ran the file setup_custom_target_arduino.m after changing the relevant directory listing and the arduino version in the m file, and I got the output of Arduino on COM 3, which was correct.
After this, I checked the Simulink Library Browser and I had the Custom C/C++ Target Arduino Library will all its modules. Now when I simulate the model, I get the following error:
Error in S-function 'myarduino_blink/Digital Output':
S-Function 'sfunar_digitalOutput' does not exist
Kindly help me out, what could I have done wrong?

... I think you forgot the error...


text:
Basic makefile for avr-gcc
I would like to make a makefile for compiling c programs for the arduino. I am somewhat familiar with make but have never used it with avr-gcc. What is the simplest way I could put the commands below in a makefile?
$ avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o led.o led.c
$ avr-gcc -mmcu=atmega328p led.o -o led
$ avr-objcopy -O ihex -R .eeprom led led.hex
$ avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:led.hex

Since this is an Arduino forum, it would be more politically correct to compile with -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard and link with libcore.a. :-)

It's no different to working with Make and any other form of GCC.  Just set your CC variable and CFLAGS variable accordingly and work as per normal.
For instance, I just knocked this one up:
CC=avr-gcc
OBJCOPY=avr-objcopy

CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

led.hex: led.elf
    ${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

led.elf: led.o
    ${CC} -o led.elf led.o

install: led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:led.hex

That's saying that any automatic C compilation will be done with avr-gcc and the flags specified in CFLAGS.  It will by default make the hex file using OBJCOPY, which is set to the avr one, which relies on the file led.elf - so to get that file it runs the led.elf target, which links the object file led.o with the default libraries using whatever was set in CC. To do that it needs led.o, and it makes that automatically using the program specified in CC and the flags in CFLAGS.  You can then optionally to make install which will run avrdude to install the hex file into the chip.
You can make it even more generic so you can copy it in to other projects and make the minimum changes necessary:
BIN=led
OBJS=led.o test.o

CC=avr-gcc
OBJCOPY=avr-objcopy
CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

${BIN}.hex: ${BIN}.elf
    ${OBJCOPY} -O ihex -R .eeprom $< $@

${BIN}.elf: ${OBJS}
    ${CC} -o $@ $^

install: ${BIN}.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:$<

clean:
    rm -f ${BIN}.elf ${BIN}.hex ${OBJS}

That uses "automatic variables" and simple name replacement.  BIN contains the "base" of your binary files, OBJS contains the list of object files.  $@ is the name of the current target, $< is the name of the first prerequisite, and $^ is the list of all the prerequisites.  Just change BIN and OBJS to suit.  As a bonus I have thrown in make clean to remove the compiled files and just leave you with the source.

the posted makefile needs another line near the top; that says: '.PHONY : install clean'

@user3629249 Why? The makefile as posted works perfectly.  You only need .PHONY for targets called as prerequisites, not targets called manually which those are.

@Majenko It's good practice to create a phony target for anything that's not actually a filename. If you create a file called install or a file called clean (shell scripts, perhaps?), then make may think that they're Up to date and do nothing.

@WChargin If you do something as daft as that then you deserve it not to work.  Your shell scripts should be clean.sh and install.sh if you must have them.

The accepted answer is great as it has given me a valuable lesson in all kinds of debugging tools (avr-objdump -D has become a close friend). Namely, the line:
${OBJCOPY} -O ihex -R .eeprom $< $@
is missing the architecture flag and should read
${OBJCOPY} -mmcu=atmega328p -O ihex -R .eeprom $< $@
Without the -mmcu architecture flag, avr-gcc guesses we are compiling for 8515 architecture (definitely not) and it produces the .elf file without initial instructions for initializing, i.e. without instructions to call the "main" function etc.
This results in confusing behavior as any simple program (e.g. blink) with only the "main" function works perfectly, but if you define another function before or after the "main", it runs that function and never calls "main" or it restarts all the time etc.
I am also not a particular fan of avoiding the verification of correct MCU type and uploaded program, so I'd advocate not to use -F and -V and use -v instead.
So, the improved answer could be:
PKG=led
BIN=${PKG}
OBJS=${PKG}.o
MCU=atmega328p

CC=avr-gcc
OBJCOPY=avr-objcopy
CFLAGS=-Os -DF_CPU=16000000UL -mmcu=${MCU} -Wall
PORT=/dev/ttyACM0

${BIN}.hex: ${BIN}.elf
        ${OBJCOPY} -O ihex $< $@

${BIN}.elf: ${OBJS}
        ${CC} -mmcu=${MCU} -o $@ $^

install: ${BIN}.hex
        avrdude -v -c arduino -p ${MCU} -P ${PORT} -b 115200 -U flash:w:$<

clean:
        rm -f ${BIN}.elf ${BIN}.hex ${OBJS}

You wrote: “Without the -mmcu architecture flag, avr-gcc guesses we are compiling for 8515 architecture”. Actually it's avr2: “‘Classic’ devices with up to 8 KiB of program memory.”

I was referring the the Atmel reference http://www.atmel.com/webdoc/avrlibcreferencemanual/group__demo__project_1demo_project_compile.html Are they mistaken?

Maybe they mean the AT90S8515 MCU which, unlike its replacement (ATmega8515), has an avr2 architecture. The page you link to may have been written in a time when “8515” was not ambiguous. And they don't call it an ”architecture”, since it's only one of many MCUs sharing the avr2 architecture.


text:
How can I play audio from an SD card?
What is the best / simplest way to play audio files from an SD card?
I'm currently working on a sound board, where each button plays a different sound. But I have yet to find the right combination of shields / hardware to do this efficiently.
Is there a shield that supports this directly (SD card -> speaker)? Note that I also need additional pinheads for my buttons to connect to. I think I will be using the Arduino Mega for that purpose.

If all you need is button → sound then you don't need an Arduino at all. There are modules that do exactly that natively.

Are there? I haven't found any yet. Can you point me to one?

https://www.sparkfun.com/search/products?term=trigger

I don't think this will work, because I have 48 sounds and I don't have one button for each sound, but rather one row and one column of buttons that need to be pressed one & then the other...

There are several audio products/shields.  Because you mention "speakers", the first one listed can come with an on-board amplifier to drive speakers directly.  Most shields just give line-out to drive a pre-amp.

Adafruit Music maker shield plays MP3/WAV/OGG from microSD http://www.adafruit.com/products/1788
Adafruit Wave shield plays WAV files on SD card http://www.adafruit.com/products/94
SparkFun MP3 trigger board supports 256 tracks and a serial protocol for running individual tracks. https://www.sparkfun.com/products/11029
SparkFun MP3 shield board plays MP3/WAV/OGG https://www.sparkfun.com/products/10628

Can any of these be triggered with 48 different sounds on button click?

The shields and devices mentioned are for audio playback.  They don't in general handle buttons or inputs (although the SparkFun trigger above handles a smaller number).  Instead, you'd want to handle the inputs with some other method on the arduino (poll your row/column inputs) and then calculate what audio file to play.  Communicate that to the device and it plays.

If you can rig your device to print one of the numbers "1" through "48" based on inputs, getting it to instead play audio with one of the above would be pretty easy.

#include <SD.h>                      // need to include the SD library
//#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 10  //using digital pin 4 on arduino nano 328
#include <TMRpcm.h>           //  also need to include this library...

TMRpcm tmrpcm;   // create an object for use in this sketch
char mychar;

void setup(){

  tmrpcm.speakerPin = 9; //11 on Mega, 9 on Uno, Nano, etc

  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can      be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
     }
  tmrpcm.play("beware.wav"); //the sound file "music" will play each time the arduino powers up, or is reset
}

void loop(){

  if(Serial.available()){
    mychar = Serial.read();

    if(mychar == 'o'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("helpyou.wav");
} else if(mychar == 'r'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("chortle.wav");
} else if(mychar == 'q'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("helpyou.wav");
} else if(mychar == 'p'){
  tmrpcm.play("beware.wav");
}
else if(mychar == 'w'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("impresiv.wav");
}
else if(mychar == 't'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("seekyoda.wav");
}
else if(mychar == 'y'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("sensefear.wav");
}
else if(mychar == 'u'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("strongami.wav");
}
else if(mychar == 'i'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("whyhere.wav");
}
  }

}

This code should be helpful. Make sure you have a SD card reader. You must also hookup the card reader:
3.3v goes to 3.3v on the Arduino UNO (for power)
GND goes to Ground on Arduino UNO
D0 goes to pin 12 on Arduino UNO
D1 goes to pin 11 on Arduino UNO
CLK goes to pin 13 on Arduino UNO
D3 goes to pin 10 on Arduino UNO
Lastly, download an arduino library so it can play audio files.
https://github.com/TMRh20/TMRpcm

Finding code is easy, but the question is more focused on the right hardware.


text:
Arduino Yun doesn't link any library
I'm writing code for a project with Arduino Yun. My project is quite simple: it takes a picture with a webcam and saves it in a PNG or JPEG file format. I've already installed the uvc driver for Arduino Yun and tested it with my webcam and the fswebcam application. The application saved pictures both in PNG and JPEG format successfully, so I went on and installed the C compiler, make and binutils for Arduino Yun and started to write my own application that would do the same thing (just taking a picture and saving it in PNG format). After writing the code to capture the pixels of the image, I decided to write them down in a PNG file format by using the libpng library available for Arduino Yun through luci web control panel. After installing the package, I included the png.h (using #include png.h) in my source code and wrote the code to write those pixels down in a simple PNG file (thanks to this tutorial: http://www.labbookpages.co.uk/software/imgProc/libPNG.html).
What's the problem? It just won't compile! I tried everything and all I got were "undefined reference to 'function name here'" errors. I thought that, maybe, libpng was buggy so I moved to libjpeg. No luck! I get the same errors over and over again. I really don't know what else I can do, I tried everything, it just seems that the Arduino Yun C compiler can't handle "external" libraries. I thank you in advance for any help you'll give me...
Here are the errors I get when I try to compile it using the libjpeg library:
/tmp/ccdzMFgN.o: In function `salvaImmagineJPEG':
    ScattaFoto.c:(.text+0x1d9c): undefined reference to `jpeg_std_error'
    ScattaFoto.c:(.text+0x1da8): undefined reference to `jpeg_std_error'
    ScattaFoto.c:(.text+0x1dc8): undefined reference to `jpeg_CreateCompress'
    ScattaFoto.c:(.text+0x1dd4): undefined reference to `jpeg_CreateCompress'
    ScattaFoto.c:(.text+0x1dec): undefined reference to `jpeg_stdio_dest'
    ScattaFoto.c:(.text+0x1df8): undefined reference to `jpeg_stdio_dest'
    ScattaFoto.c:(.text+0x1e2c): undefined reference to `jpeg_set_defaults'
    ScattaFoto.c:(.text+0x1e38): undefined reference to `jpeg_set_defaults'
    ScattaFoto.c:(.text+0x1e54): undefined reference to `jpeg_set_quality'
    ScattaFoto.c:(.text+0x1e60): undefined reference to `jpeg_set_quality'
    ScattaFoto.c:(.text+0x1e78): undefined reference to `jpeg_start_compress'
    ScattaFoto.c:(.text+0x1e84): undefined reference to `jpeg_start_compress'
    ScattaFoto.c:(.text+0x1ed8): undefined reference to `jpeg_write_scanlines'
    ScattaFoto.c:(.text+0x1ee4): undefined reference to `jpeg_write_scanlines'
    ScattaFoto.c:(.text+0x1f10): undefined reference to `jpeg_finish_compress'
    ScattaFoto.c:(.text+0x1f1c): undefined reference to `jpeg_finish_compress'
    collect2: ld returned 1 exit status

Were you going to share the errors with us?

It's not the compiler, it's the libpng package (and other libraries too).  It only contains the runtime shared library (.so) files.  You can't use it for development.
I haven't yet found if it's possible to directly install a full development package or not - normally development for OpenWRT is done outside the low-powered chip using a cross-compiler environment on a PC.

Thanks for your reply. I actually considered the cross-compiling solution but I let it as last resort. Do you (or does anybody) know how to set up an Arduino Yun cross-compiling environment? Thanks in advance.

Just follow the OpenWRT instructions for that chip.


text:
changing analog pins data logging using sdFat library
Background:
My goal is to use sdFat library, more precisely AnalogBinLogger example.
I want to log data from changing analog pins for example, I want to log from pin 0 to pin 3 for 5 minutes and then from pin 4 to pin 6 for another 5 mins and then from pin 7 to pin 9 for another 5 mins. that is going to be continuously which means I am going to get rid of the part where you have to enter "r" to start logging.
Regarding the time, I managed to figure it out, I am just using the value of the variable count, if my sampling rate is 1000 samples/sec for example then 5 minutes will be 1000*60*5 and the change will be done in this line:
if (Serial.available()) {
  // Stop ISR calls.
  adcStop();

to
if (count >1000*60*5) {
  // Stop ISR calls.
  adcStop();

and this worked fine.
My problem is with the changing pins:
const uint8_t PIN_LIST[] = {1};

I changed this line to
uint8_t PIN_LIST[3] = {};

First I removed the word const, because it's not going to be constant anymore, and I just declared an empty array, and second I am changing the pins in the loop.
Here is the loop after I got rid of doing the serial input:
void loop(void) {
int i;
for (i=0;i<=12;i+3)
{
  PIN_LIST[] = {i,i+1,i+2};
  logData();
  Serial.println("done");
 }}

The problem is I get this error :

AnalogBinLogger.ino: In function 'void loop()':
AnalogBinLogger:808: error: expected primary-expression before ']'
token
AnalogBinLogger:808: error: expected primary-expression before '{'
token
AnalogBinLogger:808: error: expected `;' before '{' token

The line 808 is:
PIN_LIST[] = {i,i+1,i+2};

So this is the only error, any help please?
The code is so long (800+ lines) if this information is not enough and you need me to explain a part then just tell me.

in case someone has the same problem
it seems like after you initialize an array this way
uint8_t PIN_LIST[3] = {};
you won't be able to assign all the values at once:
PIN_LIST[] = {i,i+1,i+2};
instead you assign each individual value

PIN_LIST[0] = i;
PIN_LIST[1] = i+1;
PIN_LIST[2] = i+2;

and now it worked : )


text:
DC Motor speed control by using pwm
I am using Arduino Uno, and MPU6050(3 axis imu sensors), not gate,  and L298 dc motor drive.
My algorithm is very easy.
Receive an angle how the balancing robot is tilt.
Decision speed of motors by using the angle.
For example, when robot is tilt n degrees forth or back, robot will go forth or back with speed proportional n.
My code is similar to the following code.
Sorry, it is difficult to type on my phone. TT

Angle = getComplementaryAngle();

Speed = pidCompute(abs(Angle));
// Speed range: 0 to 255

if (Angle > 0.4) {

  DigitalWrite(dirA, HIGH);

  DigitalWrite(dirB, HIGH);

  analogWrite(enA, Speed);

  analogWrite(enB, Speed);

}

else if (Angle < -0.4) {

  DigitalWrite(dirA, LOW);

  DigitalWrite(dirB, LOW);

  analogWrite(enA, Speed);

  analogWrite(enB, Speed);

}

else {

  analogWrite(enA, 0);

  analogWrite(enB, 0);

}

I don't know why left motor's speed is different from right motor's one.
I checked the voltage of motor pin.
Both pins' voltage are same as 11V.
I think pwm is wrong.
When Arduino makes two pwm output, it causes some problems?

You haven't told us what is going wrong. Are enA and enB both pwm pins?

As Gerben notes - not all pins are able to provide analog output. Have you chosen pins that do? Try outputting PWM to a resistor load - say 10K Ohms, observing PWM outputs and tilting the robot by hand across its range. Do the PWM output vary as expected? You have not provided a circuit diagram , model of motors, voltages used, which pins are doing what and more. You do not say what dira, dirb  do or how or even why. We can guess but may guess wrong. There is MUCH room for things to be wrong in the areas you have not told us about.

ah... sorry. I will change my question and ask again.

Your code is "similar" to that or that is your code?  why don't you post the actual code?  What a waste of everyone's time it would be if your error is something that is different in your "real" code.

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


text:
Function generator with Arduino Nano
I'm trying to convert the project here to an Arduino Nano.
I scaled the waveforms from 12 bit to 8 bit values. I replaced the analogReadResolution and analogWriteResolution calls with pinMode(10, OUTPUT) and pinMode(11, OUTPUT) and changed the two analogWrite calls to write to pins 10 and 11. Otherwise the program is unchanged.
My thinking (and this is where my poor electronics skills come into play) is that I just need a simple low pass filter to convert the PWM into the appropriate waveform (which, at startup, ought to be a sine wave on both pins). According to the article, the frequency generator tops out at 170Hz. I figure the PWM signal is going to be significantly higher than that, so I use R=3.3K and C = .1uF for my RC filter which ought to give me a -3dB at about 480Hz, but what I'm seeing on my scope is a mess. Not a stable signal at all.
This is the waveform I'm seeing on my scope:

Can someone educate me?
Update: BTW, this is the initial waveform which ought to be a sine wave.

What you're proposing can work, but the PWM frequency needs to be much higher than the frequency you're trying to generate. If you look at the PCMAudio sample you'll see that it tunes the PCM frequency almost as high as it will go.

Can you elaborate on "much higher"? PWM on pins 5 and 6 is 980Hz. What sort of maximum frequency can I expect from the signal generator based on that? And how would I want to set up the low pass filter to clean up the signal?
I've read that DDS article, but I have no inductors in my collection of components, so I was trying to make an RC filter instead.

At a PWM frequency of 980Hz I wouldn't expect anything above 5Hz with any sort of fidelity.

Oh, that's far too low for my needs. I was aiming for simplicity, but a better approach may be to use the digital outputs and create a DAC with a resistor ladder.
Thanks for the education, I guess I'll have to start over.

You can tune the PWM as high as F_CPU/256, i.e. 62.5 kHz with a 16 MHz clock.

The PWMs on pins 10 and 11 of the Arduino Nano run at 488 Hz. That's what you are seeing on the scope. The code you are using was meant for an Arduino Due, which has real digital-to-analog converters.
Edit: You can tune the PWM to run as high as F_CPU/256 by
reconfiguring the timers 1 and 2 to “fast PWM” mode, instead of phase
correct PWM, and setting their prescalers to 1 instead of 64. This
should raise the PWM frequency to 62.5 kHz, given that the Nano has
a 16 MHz clock.
The following code should do exactly this. You can put it somewhere
inside your setup(). Warning: I have not tested this code. This
will change the PWM frequency on pins 10 and 11, but also on pins 3 and
9, which share the same timers. It will probably break the tone()
Arduino function.
// Set PWM frequency to 62.5 kHz on pins 3, 9, 10 and 11.
TCCR1A = 1<<WGM10;
TCCR1B = 1<<WGM12 | 1<<CS10;
TCCR2A = 1<<WGM21 | 1<<WGM20;
TCCR2B = 1<<CS20;