text:
Mega pin stuck high after driving optocoupler
I have an Arduino Mega which is driving a board. On the board is a quad optocoupler (K847PH). Pins 42 - 45 of the Arduino are each attached to the Anode of a opto. The cathode goes to ground through a 50ohm resistor. I've used multiple boards and have had no issues with this part of the circuitry so far. I recently attached a new board (same circuit) and began testing. I noticed I had ~1.1V on pin 1 of the opto (Anode). After some debugging I checked the voltage coming out of the Arduino to that pin (42 on the Mega) and noticed it was 5V. I ran a new sketch to drive and hold the voltage low but the voltage remains at 5V.
void setup() {
  pinMode(42, OUTPUT);
  digitalWrite(42, LOW);
}

void loop() {
  digitalWrite(42, LOW);
}

Looking at the schematic of the Mega it appears pin 42 is directly connected to the ATMEGA1280-16AU. Is there anything I can do to fix the Mega? Should I just replace the ATMEGA1280-16AU? Is there something I can probe to check? It does appear there is > 1Mohm of isolation between pin 42 and the 5V rail.

Re “Is there anything I can do to fix the Mega?”, if the condition persists when trying it after removing power from the Mega and discharging it, probably not. (Aside from not using that pin.)
Note, the IR LEDs in the K847PH are rated at 60 mA max each, and typically drop 1.25 volts at 50 mA current.  If you drive them with 5 V through a 50Ω resistor, typical current will be 3.75/50 = 75 mA, which exceeds K847PH ratings and Mega2560 ratings (typically 40 mA max, 20 mA working).  Consider using a 125Ω or more resistor, to stress the Mega pins at 30 mA or less.
(From Fig. 8 - Collector Current vs. Forward Current, in the K847PH data sheet, you might be ok with 10 to 20 mA current through the IR LEDs.)

Thanks, I'll probably increase the resistor up to 500ohms even.


text:
Get an additional analog pin?
I have the following board:

As far as I can tell, there's only a single analog pin (A0). But I need at least 2 additional (for 3 total).
Is there some way to fake analog input on GPIO pins?

No. Get a SPI ADC.

What do you need to connect to the analog pins?  You can "bitbang" an ADC with some additional components, but it isn't trivial to do. Better go with an external ADC or use a different sensor that has a digital output instead of analog.

The ESP8266 only has one ADC pin. You can:

Use an analog MUX to switch that pin between different signals
Connect an external I2C ADC chip
Connect an external SPI ADC chip
Connect the ESP8266 to another MCU (such as an Arduino) and get that to do analog readings.

source: Stack Exchange

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

sort: votes


text:
Merging strings and constants causing scope errors
I'm getting a few errors when merging strings with constants.
Here's the pertinent code...
#define STATION_ID ABC123
#define STATION_PASS XYZ987

void loop(){
    String path = "/weatherstation/updateweatherstation.php?ID="+STATION_ID+"&PASSWORD="+STATION_PASS+"&dateutc=now&tempf="+celsiusToFahrenheit(temperature)+"&humidity="+String(humidity)+"&action=updateraw";
}

And then the errors...
weather.cpp:15:20: error: 'ABC123' was not declared in this scope
weather.cpp:64:66: note: in expansion of macro 'STATION_ID'

weather.cpp:16:22: error: 'XYZ987' was not declared in this scope
weather.cpp:64:90: note: in expansion of macro 'STATION_PASS'

Not sure where I'm going wrong on this.

Maybe? Not sure, but give this a try.
#define STATION_ID "ABC123"
#define STATION_PASS "XYZ987"

That is just so wrong on so many levels.
Firstly, you should really not use String, especially not for constants.
Secondly, you do not need to manually concatenate string constants at all.
Thirdly, there is very rarely ever any need to concatenate things together into a single string before using them. Instead you can in general send individual parts separately:
#define STATION_ID "ABC123"
#define STATION_PASS "XYZ987"

client.print(F("/weatherstation/updateweatherstation.php?ID="
               STATION_ID
               "&PASSWORD="
               STATION_PASS
               "&dateutc=now&tempf="));
client.print(celsiusToFahrenheit(temperature));
client.print(F("&humidity="));
client.print(humidity);
client.print(F("&action=updateraw\r\n"));

By having multiple string constants next to each other (such as "string one " "string two") the compiler will automatically join them together (into "string one string two") for you. No plus, no comma, no nothing - just place them next to each other. And always use F() for string constants.

Calm down @Majenko, did you see this? Here's the pertinent code... I think he just gave an example. I think this: That is just so wrong on so many levels. is a little rude

You may think it's rude, but that doesn't stop it being completely true. It is so very very very wrong. On soooo many levels.

Further optimization is:
#define STATION_ID "ABC123"
#define STATION_PASS "XYZ987"

void loop(){
    String path = "/weatherstation/updateweatherstation.php?ID=" STATION_ID "&PASSWORD=" STATION_PASS "&dateutc=now&tempf="+celsiusToFahrenheit(temperature)+"&humidity="+String(humidity)+"&action=updateraw";
}

This will remove some intermediate String variables in the expression, etc.

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


text:
Refactor to save bytes?
I'm a painful 128 bytes of my max for this Trinket. Any refactoring I could do to get down the size?
#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#include <RTClib.h>

#define LEDPIN 1
#define TONE 4
#define BTNPIN 3

RTC_DS1307 rtc;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, LEDPIN, NEO_RGB);

const long fadeTime = 10 * 60000L; // X minutes
const int colorStops = 255;
const int delaySpeed = fadeTime / colorStops;
const int notes[] = {262,294,330,349};
const uint32_t alarmLength = 5 * 60000L; // 5 minutes

void setup() {
  rtc.begin();
  rtc.adjust(DateTime(__DATE__, __TIME__));

  pinMode(TONE,OUTPUT);
  pinMode(BTNPIN, INPUT);
  digitalWrite(BTNPIN, HIGH);

  strip.begin();
  strip.show();
}

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

  // If it's 5:10 am on a week day, start the fade in
  if (now.hour() == 5 && now.minute() == 10 && now.second() == 0 && now.dayOfTheWeek() != 1 && now.dayOfTheWeek() != 7){
    // Fade in light
    for(int i = 1; i<colorStops; i++){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(i,i,i));
      }
      strip.show();
      delay(delaySpeed);
    }

    // Play tone after light fully bright
    for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
         strip.setPixelColor(np, strip.Color(random(50,255),random(50,255),random(50,255)));
      }
      strip.show();

      beep(notes[random(0,3)]);
      delay(100);
    }

    turnOffPixels();
  }
}

void beep(int delayAmount)
{
  for (uint16_t t = 0; t < 30*1000/2; t += delayAmount)
  {
    digitalWrite(TONE,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(TONE,LOW);
    delayMicroseconds(delayAmount);
  }
}

void turnOffPixels() {
  for(int np = 0;np<strip.numPixels(); np++){
    strip.setPixelColor(np, strip.Color(0,0,0));
  }
  strip.show();
}

bool kill() {
  if (! digitalRead(BTNPIN)) {
    turnOffPixels();
    return true;
  } else {
    return false;
  }
}

Error...
Sketch uses 5,438 bytes (102%) of program storage space. Maximum is 5,310 bytes.
Global variables use 97 bytes of dynamic memory.

Have you tried using a lighter NeoPixel library?

@IgnacioVazquez-Abrams I wasn't even aware of other NeoPixel libraries...are there any you recommend?

I use light_ws2812 myself. Mostly the C library, but I can see the non-Arduino C++ library being useful in your case.

Remove the rtc.adjust(DateTime(__DATE__, __TIME__));. You only need to set the RTC once, after e.g. you insert the backup battery.
Change
pinMode(BTNPIN, INPUT);
digitalWrite(BTNPIN, HIGH);

to
pinMode(BTNPIN, INPUT_PULLUP);

Inline the beep function using the inline hint:
inline void beep(int delayAmount)
...

Shorter beep function:
inline void beep(int delayAmount)
{
  for (uint16_t t = 0; t < 30*1000; t += delayAmount)
  {
    digitalWrite(TONE,t & 0x01);// HIGH is odd, LOW if even
    delayMicroseconds(delayAmount);
  }
}

To inline a function you use the static keyword, as the compiler essentially ignores inline.

@EdgarBonet The compiled code got smaller with just the inline.

On a quick test build for an ATmega328p type Arduino, the implementation of random() and its unique dependencies seems to be about 180 bytes, so you might see if there's a more compact way of achieving your need there, perhaps using the low byte of some mathematical expression of the time, and just retrying until you get an in-range value.
Of course if you get really stuck, you could remove the bootloader and program it with ISP from an ordinary Arduino or something like that.

I'm inclined to agree with Chris Stratton here. The Trinket has an Attiny85 on it, which has 8k of program memory. However the amount they need for the bootloader limits the memory available to you somewhat. If you program via ICSP you could use all of the 8k of program memory. But if you don't want that inconvenience, finding another Neopixel library, as Ignacio suggested, could help.

Very good suggestions so far. I have only one to add: instead of
strip.Color(0,0,0) use just the constant number 0. This saves a
function call.

For refactoring, consider using a for loop that executes twice, once for the  “// Fade in light” section of code, and once for the  “// Play tone after light fully bright” section.  For parts of the code that differ, test the loop index and do one action or the other.
Here are two ways to get rid of a few (eg 54) bytes of code:

Instead of

 Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, LEDPIN, NEO_RGB);
 ...
 for(int np = 0;np<strip.numPixels(); np++){
 ...

(with three instances of the latter), say something like
enum {numPixels = 5 };
Adafruit_NeoPixel strip = Adafruit_NeoPixel(numPixels, LEDPIN, NEO_RGB);
...
for (byte np=0; np<numPixels; ++np){
...

This will save about 40 bytes (10 bytes per for, and another 10 probably due to strip.numPixels() code not linking).  (Note, the savings is due to getting rid of function calls; the change from int to byte apparently makes no difference in program size, probably because the compiler optimizes int to byte where its analysis shows it can do so.)

Instead of

if (... && now.dayOfTheWeek() != 1 && now.dayOfTheWeek() != 7){

say
if (... && now.dayOfTheWeek()+250>250){

which will save 14 bytes.  This works as explained in my answer to your previous question.  However, I've written +250>250 here instead of the +249>250 there because according to RTClib documentation and RTClib.cpp code, .dayOfTheWeek() returns 0 for Saturday, rather than 1 as you seem to expect.

Possibly inline beep(), since you call it only once.

You mean if (... && (uint8_t)(now.dayOfTheWeek()+250)>250){. C.f. my comment to this answer of yours.


text:
Not being able to use pushbutton
I've been trying to detect a push button based on this tutorial, but due to my lack of skills/knowledge I haven't been able to make it work, could you guys point out what I'm doing wrong?
Any help is appreciated
My project on 123d circuits
My code:
void setup() {
  pinMode(2, INPUT);
  pinMode(3, OUTPUT);
  digitalWrite(3, HIGH);
  Serial.begin(9600);
}

void loop() {
  trigger();
}

void trigger(){
  if (digitalRead(2) == HIGH) {
    Serial.println("Hey");
    //turn();
  }
}

You seem to be suffering from three problems here:

A lack of understanding how the button's pins are configured
A lack of understanding of how breadboard works
A strange notion (that I have seen around a lot recently for some reason) that a button needs to be driven from an output.

For the button's pins you should know that the pins are paired on the long sides. That is, if you hold the button so it is in "landscape" orientation (wider than it is high) the two upper pins are joined together, and the two lower pins are joined together.

Breadboard consists of strips of connections which, in your diagram, would be running horizontal. Pins plugged into holes horizontally in line with each other on the same side of the board (the gap in the middle is a gap in the connections too) will be connected together.

Finally for the wiring of the button. Nowhere in the tutorial you link to does it ever mention connecting the button to two IO pins. The button should only be connected to one IO pin. It also connects to +5V and, through the resistor, to ground.  Wire it up exactly as it shows you in the tutorial and make it work like that before you try fiddling with it.

Thank you so much for helping me out and for having patience to explain to me what I was doing wrong

so electrons from the black jumper go to red one and if I push the button they will get to pin 2? a weird question, will the electrons go through pin 2 and get out of the 5V pin? if not, where will they go?

At your stage of development you shouldn't be concerning yourself with electrons. For input pins you are only concerned about the voltage at the pin. With the button released the voltage is 0V. With the button pressed it is 5V.


text:
Why cannot I input arrays as digitalWrite arguments?
I am making my own "7 segment LED driver". I know there is a lot of examples on the internet, I just want to try my own. But I have a piece of code that does not work and I don't know why. Can somebody explain to me why it is not working?
When I put in this, it works:
digitalWrite(pins[0], one[0]);
digitalWrite(pins[1], one[1]);
digitalWrite(pins[2], one[2]);
digitalWrite(pins[3], one[3]);
digitalWrite(pins[4], one[4]);
digitalWrite(pins[5], one[5]);
digitalWrite(pins[6], one[6]);

So of course I tried using for():
for (byte i = 0; i >= 6; i++)
  {
    digitalWrite(pins[i], one[i]);
  }

And this does not work. But why? I think it should. Btw. pins is const byte array and one is const bool array.
Thanks in advance for any suggestions!

I don't see why it shouldn't work; what happens instead?

The seven segment display stays off, nothing lights up; but i am sure i have it connected right, because the first code works. But the compiler doesn't give any errors....

You've written the for loop incorrectly.
for (byte i = 0; i >= 6; i++)   <-- ERROR HERE
  {
    digitalWrite(pins[i], one[i]);
  }

That first line should be for (byte i = 0; i <= 6; i++). i begins at zero, which is less than six, and the loop only runs while i is greater than 6.


text:
Not enough pins on Uno?
I'm making touch-sensitive, light up tic-tac-toe board.
That means 9 LEDs + 9 capacitive sensors.
Each LED needs 1 pin and each sensor needs 2...meaning I'd need 27 pins to properly control each touch-and-illuminate sequence.
There aren't enough inputs on the Uno for this, so what sort of workarounds should I explore to pull this off?

You might use "NeoPixels" instead of LED's (or other LED strip IC's). You could then "R/G/B animate" the tic-tac-toe board, using only 1 pin :)

There are a number of common solutions to "not enough pins".

Reduce the number of pins you need. This option is often discarded out of hand, but may be the best. For example, you may be able to reduce the 18 individual pins for the on/off capacitive sensor, with a different part, which may be able to give you an X,Y co-ordinate of where it is touched, with fewer pins.
Multiplex the pins. This seems to be the most likely to work in this case - you will use (for example) 9 Uno pins to power the LED and capacitive sensor on each cell, one at a time. So, for example, you might attach D1 to the top left cell, D2 to the top-center, and so forth. Then you use another pin (e.g. D10) to connect to ALL the cathodes of the LEDs (via a single transistor, to protect the Uno from too much current), D11 and D12 to connect to one of the data pins of ALL of the capacitive sensors. So, you "select" cell one, by switching D1 from LOW to HIGH. Then, you put D10 to LOW, so current will from across the LEDs. Read the capacitive sensor, which is now also powered on. Although all of the censors are connected to D11 & D12, only one will be powered on, so you will only be reading that one. Once read, you probably want to delay a few milliseconds, to make sure the light shows up. Then move on to the next cell. Go round and round all cells. The LEDs will be off 8/9ths of the time, but it will still be visible. NOTE: reading more about capacitive sensors, I see that one is input, the other output. You would need a transistor for each of the "select" pins, used as a switch to connect D11 to the correct sensor.
Do the same thing, but using a decade counter. Connect 2 pins from the Arduino to the decade counter - one to "count", and one to reset. First, strobe the reset - this will set the first output of the decade counter high - connected to cell 1. Then, when you want to move to the next cell, drop the "count" low, then high again. You are now on the next cell. Repeat until you get to cell 9, then send the "reset" (which guarantees you know where you are up to) to get back to cell 1.
Charlieplexing (mostly suitable for output only). This is a somewhat complicated, but very efficient (pin-count wise) way of running lots of LEDs off only a few Arduino pins, by using them in combination. For example, 3 pins could run 6 LEDs - if you have pins A, B and C, run one LED from A to B, one from B to C, and one from C to A; then, run 3 more LEDs in the OPPOSITE direction (don't forget your resistors!). Depending on which LED you want lit, you might want pin A high, B low, and C high impedance (INPUT). 4 pins will get you 12 LEDs, 10 will get you 90 LEDs. If you think this might be useful, check out the Wikipedia
Use chips that are designed specifically for the application you need. For example, TLC5940 chips will run up to 16 LEDs each, controlling the brightness of each LED independently. You set the brightness of each LED, then let the TLC5940 take care of the work. SIPO chips such as the 74HC595 (8 outputs) are similar, but only allow "on" or "off" for each pin. Both of these can be "daisy chained" - with the same number of Arduino pins, you can connect the output of one to the input of the next, to control more outputs.
Use multiple Arduinos. Yes, this might sound expensive, but you can use an AtMega (e.g. AtMega328, which is the same chip used in the Arduino) for a fraction of the cost. You might even use an AtTiny - even cheaper (but less memory). All of these can run the same code. This is the most flexible, but is also the most work - you would need to think about which chip does what, how they interact, and how they talk to each other. This also has the advantage that, rather than a chip that runs at 16mhz, you can now have multiple chips that each run at that speed, and have more memory each. Some applications work well with one "master" chip controlling one (or more) "slaves", whereas other applications work really well as peer-to-peer, either with each node running the same code, or each doing their own thing, and passing information to other nodes. For this example, you might use one AtTiny85 for each of the 9 cells, with an Arduino to be the master. Or, use an AtTiny84, for each row of 3 cells, with one Arduino to rule them all. The AtTiny84 has 14 pins: power, ground, reset, and 11 data pins - 2 is enough for a shared data bus, such as i2c, leaving 3 pins for each of 3 cells.
(not relevant for this example) For multiple on/off sensors (e.g. pushbuttons, switches), you can attach them through different values of resistors, and connect them to an ADC pin as a voltage divider. For example, connect ground via R0 to an analog pin; then connect to the same pin: pin -> resistor 1 -> pushbutton 1 -> +5v; pin -> resistor 2 -> pushbutton 2 -> +5v, and so forth. Build the circuit, and test each combination of switches/pushbuttons on/off, what the output will be. Then, in your code, figure out which combination it is closest to. Each resistor will need to be different resistance. If you only expect one switch to be on at once, it's a lot easier.

Could you, use a pin (or complete port) as output for 90% of the time. And use 10% of the time to sense the pin? If sensing takes a little time (and you're normally powering an LED) you might not notice the LED going off for a real small time :)

For a definitive answer, I suggest you experiment. Since the basis of capacitive touch sensors is to see how much of a capacitor is in the circuit, any component that can act like a capacitor may cause increased or decreased sensitivity

Shift registers. A single shift register is typically 8 bits, so for nine cells you will need two parallel-in/serial-out (for the sensors) and two serial-in/parallel-out (for the leds). You can chain shift registers together to manage any number of bits, at the price of speed. Each chain of registers needs two pins - data and clock, and the parallel input needs a third pin to latch the data. 5 pins all up, for any number of inputs and outputs. You could even combine the clocks by combining 'read the sensors' and 'refresh the display' as a single operation.

same as #5 - I specifically mention SIPO (shift registers) as an example.

@PailMurrayCbr You can use Shift registers via SPI at full clock speed, if they can do it. So speed is not really a problem.

As noted in Paul's comment, you could use NeoPixels instead of ordinary LEDs for the display.  Each NeoPixel contains RGB LEDs and a microcontroller that accepts a serial stream of bits in, cleans up the waveform, and passes what it doesn't need on through, to the next NeoPixel.  This would reduce the necessary number of pins by 8, since a string of NeoPixels uses one signal pin, independent of the number of NeoPixels in the string.
For the touch-sensitive (capacitive) buttons, rather than two wires per button, you can use one sense wire per button, and one drive wire per set of buttons, thus 10 pins to sense nine buttons, rather than the 18 pins mentioned in the question.  A sketch is shown below that samples nine capacitive buttons about 1300 times per second.  Here is some sample output from the sketch:
At t=2354 button 0 on at level 274  xoooooooo  nr= 3121
At t=2975 button 1 on at level 283  xxooooooo  nr= 3943
At t=3056 button 2 on at level 271  oxxoooooo  nr= 4048
At t=3235 button 3 on at level 280  oooxooooo  nr= 4283
At t=3272 button 4 on at level 278  oooxxoooo  nr= 4331
At t=3418 button 5 on at level 284  ooooxxooo  nr= 4521
At t=3460 button 6 on at level 275  ooooooxoo  nr= 4575
At t=3507 button 7 on at level 278  oooooooxo  nr= 4636
At t=3632 button 8 on at level 290  oooooooxx  nr= 4799

Each entry like “level 278” shows the value of a running average of counts for a button; since the program is using 270 as a threshhold value for a button being on, it's reasonable for the numbers to be slightly above 270.  (Note, if the call to secondlyReport() were uncommented, one would see that the running averages go on up into the 300 to 500 count range when a button is pressed.)  The strings of o's and x's show which buttons are on and which are off.  The numbers after nr= are the number of button readings taken so far.
The program implements smoothing (via a running average with exponential decay), debounce (via “holdoff” counts, as explained in detail in a previous answer), and hysteresis (going from off to on at a high count (270) and from on to off at a lower count (170)).
The program may need tuning to work with a given set of capacitive buttons.  The tuning variables used here (such as ButtonIsOn = 270, ButtonIsOff = 170, usSettle=60, usPreWait=5, and nsamp = 40) work ok with my nine-button setup where each capacitive button is attached to an input pin (like 4,5,...12) and to a 619K resistor (a size I have a number of).  The other end of each of those resistors attaches to Uno pin 13.  By changing ButtonIsOn and ButtonIsOff, one should be able to accomodate resistor sizes from a megohm on up to perhaps 4 or 5 megohms.
Note, to install Streaming.h (which doesn't increase code size) unzip Streaming5.zip from arduiniana.org in your sketchbook/libraries directory.
/* Via serial port, tell the current time when capacitive readings on
  various digital pins show a button has been "pressed" or "released".
  This version reads buttons using 13 as a drive pin, and two groups
  of pins as capacitive switches: group D = pins 4,5,6,7, group B =
  8,9,10,11,12.  Each of those pins should be connected to the drive
  pin via (eg) a 1M ohm resistor.   JW - April 2016

 See eg refs at http://playground.arduino.cc/Code/CapacitiveSensor and
 http://www.arduino.cc/en/Reference/PortManipulation and
 http://garretlab.web.fc2.com/en/arduino/inside/arduino/Arduino.h/digitalPinToPort.html
 */
#include <Streaming.h>       // provides nicer syntax for printing
enum { pinsMax = 9 };        // upper size on pins count per sample;
enum { nPortReads = 40 };    // # bit samples saved per reading;
enum { bundleSize = 16 };    // 2^j samples carried in running average
enum { drivePin = 13 };      // # of pin to drive capacitors
enum { ButtonIsOn = 270 };   // button-on level, with hysteresis
enum { ButtonIsOff= 170 };   // button-off level "    "
enum { usSettle = 60 };      // Hold sense pins low this long.
enum { usPreWait = 5 };      // Ignore probably crosstalk this long.
enum { nKeys=9 };        // # of keys in PinSet. Cannot be > pinsMax
#define PinSet "4,5,6,7,8,9,10,11,12"
unsigned int AvCount[nKeys]={0};
unsigned long int nSamples; // # of samples taken
//-----------------------------------------------------------
// Use delta=0 for startup, vs delta=1 for exponential averaging
void makeSample(int delta) {  // Take a sample, add it to AvCount
  byte counts[nKeys], j, nc;
  unsigned int bundle;
  nc = countPins7(drivePin, PinSet, counts);
  for (j=0; j<nc; ++j) {
    bundle = AvCount[j] * (bundleSize-delta);
    AvCount[j] = bundle/bundleSize + counts[j];
  }
  ++nSamples;
}
//-----------------------------------------------------------
void setup() {
  Serial.begin(115200);     // initialize serial port
  nSamples = 0;
  // Initialize AvCount[] with a bundle of samplecounts
  for (byte j=0; j<bundleSize; ++j)
    makeSample(0);      // Add sample directly to total
}
//-----------------------------------------------------------
// portSampler7(): countPins7() calls this routine, which holds
// drivePin and involved pins on current port low for usSettle
// us, then makes them inputs and turns on drivePin.  It waits
// usPreWait us (to weed out crosstalk), then reads the port
// nPortReads times as the pins recharge.
// The set of nPortReads port readings is returned in portReadings.
//
// Inputs:  drivePin, portCode, pinsMask.  Constant nPortReads.
// Output:  array of nPortReads portReadings.
//
// This version takes 8 cycles per reading.  Inputs switch
// on after about one RC time constant.  On a 16MHz Arduino an
// m-count result (that is, a zero bit in m of the nPortReads reads)
// suggests RC is about m/2 us + usPreWait us.

void portSampler7(byte drivePin, byte portCode,
          byte pinsMask, byte *portReadings) {
  volatile byte *pin, *port, *ddr;
  // pin, port, and ddr are pointers to registers with volatile
  // contents: input port, output port, direction register.
  pinMode(drivePin, OUTPUT);
  digitalWrite(drivePin,LOW);
  pin =  portInputRegister (portCode); // eg points to PIND
  port = portOutputRegister(portCode); // eg points to PORTD
  ddr =  portModeRegister  (portCode); // eg points to DDRD
  *port &= ~pinsMask;        // Turn off our pins
  *ddr  |= pinsMask;         // Make our pins be outputs, briefly
  delayMicroseconds(usSettle); // Delay to let pins settle low
  *ddr &= ~pinsMask;         // Make our pins be high-impedance inputs
  digitalWrite(drivePin,HIGH); // Turn on driver pin
  delayMicroseconds(usPreWait);
  for (byte i=0; i<nPortReads; ++i) // Take and store nPortReads readings
    portReadings[i] = *pin;
}
//-----------------------------------------------------------
/* Decode a pins-list into one list per involved port.
   Use portSampler7() to get rise-time counts for each port.

   If pins are spread across k ports, countPins7()  will make
   k calls to portSampler7().  Results are in counts array.
   Note, make pinsMax larger if pinsMax < #(pins in list).

   pinsList can look like "2,3,4,5,6" or "2,4,5,12,9,23,17,7"
   etc.  A list may contain digits and commas only.  Pins may be
   listed in any desired order.  Elements of counts[] will be in
   list-order.  Eg, in the "2,3,4,5,6" example, counts[0] is the
   count for pin 2, counts[1] is the count for pin 3, etc.  A
   larger count implies longer rise time and larger capacitance.
 */
byte countPins7(byte drivePin, char *pinsList, byte *counts) {
  byte pnum, pomask, pocode, potem, i, j, mul;
  byte sampl[nPortReads], pim[pinsMax], pat[pinsMax], bout=0, nat=0, pcon;
  char *c, cc;
  int usedPorts=0;  // To track which ports are done
  for (c=pinsList, counts[0]=pcon=0; *c; ++c) // Zero the counts array
    if (*c < '0' || *c > '9') counts[++pcon] = 0;
  // In each pass, group bit numbers by port and sample the port
  while (nat<pcon) { // Each loop pass sets one bit in usedPorts
    pnum = pocode = pomask = bout = pcon = 0;
    c = pinsList;
    while ((cc=*c++)) {  // Loop until c is at end of string
      if ('0' <= cc && '9' >= cc) {
        pnum = 10*pnum + cc - '0';
        if ( *c < '0' || *c > '9') { // See if pin # is complete
          potem = digitalPinToPort(pnum);  // Get port #, in range 1 to 12
          if (!(usedPorts & (1<<potem))) { // Is potem's port already done?
            if (!pocode)           // If pocode not set, set it
              pocode = digitalPinToPort(pnum);
            if (pocode == potem) {  // Process pin if it's in current port
              pomask |= (pim[bout] = digitalPinToBitMask(pnum));
              pat[bout++] = pcon; // Save location of pin's bit in results
            }
          }
          pnum = 0; // Clear # accumulator
          ++pcon;   // Count pin numbers
        }
      }
    }
    // Now pomask is a mask for all bits to be read from port pocode
    // and we are ready to sample current port.

    // Get nPortReads port readings into sampl array.
    portSampler7(drivePin, pocode, pomask, sampl);
    usedPorts |= 1<<pocode;       // Mark the port finished
    // Count up # of zeroes (ie rise times) in sampled bits
    for (j=0; j<bout; ++j) {
      int count;
      byte m=pim[j];
      for (count=i=0; i<nPortReads; ++i)
        count += sampl[i] & m;
      counts[pat[j]] += nPortReads - count/m; // Return the number of Zeroes
    }
    nat += bout;        // Count number of pins done so far
  }
  return pcon;          // Return # of pins processed
}
//-----------------------------------------------------------
// Measure rise times at designated pins and report
// current running averages of rise times, once per second
void secondlyReport() {
  unsigned int seconds=0, now;
  while (1) {
    now = millis()/1000;
    makeSample(1);      // Add a sample to running average
    if (now > seconds) {    // See if next second started
      Serial << "Counts: ";
      for (byte j=0; j<nKeys; ++j) // Show output
        //for (byte j=1; j<nKeys; j+=2) // Show output
        Serial << AvCount[j] << " ";
      Serial << " t=" << now << " sec." << endl;
    }
    seconds = now;
  }
}
//-----------------------------------------------------------
// Frequently sample rise times on designated pins, to
// find and report capacitive key press times & levels.
void keypressReport() {
  // Old-state and holdoff-count vars
  byte ostate[nKeys] = {0}, holdo[nKeys] = {0}, j, k;
  while (1) {
    makeSample(1);      // Add a sample to running average
    for (k=0; k<nKeys; ++k) {
      if (holdo[k]) {       // Ignore an on button during holdoff
      --holdo[k];
      } else {
    if (AvCount[k] > ButtonIsOn ||
       (AvCount[k] > ButtonIsOff && ostate[k])) {
      if (!ostate[k]) { // Were we off?
            ostate[k] = 1;  // New button press
            holdo[k] = 40; // Start a holdoff period
            Serial << "At t=" << millis() << " button " << k;
            Serial << " on at level " << AvCount[k] << "  ";
            for (j=0; j<nKeys; ++j)
              Serial << (ostate[j]? 'x' : 'o');
            Serial << "  nr= " << nSamples << endl;
          }
          ostate[k] = 1;     // We detected button is on
        } else {
          ostate[k] = 0;     // We detected button is off
        }
      }
    }
  }
}
//-----------------------------------------------------------
void loop() {
  if (0) secondlyReport();
  keypressReport();
}

Oh - capacitative sensors. I was fooling about with transistors (BD149s, I think) hooked up into darlington pairs, and I found that just touching the resistor on the base was enough to make them switch. No extra capacitor timing whatsamajig required.

authors: ชีวิตไม่สิ้น. ก้อดิ้นกันไป


text:
How would I refactor this code, given how similar most of the lines are?
I have a set of buttons and a set of NeoPixel LEDs. There's lots of very similar constants (button1pin, button2pin, etc) so there's almost certainly a more efficient way of coding this.
Any ideas?
#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);

// Buttons
const int button1pin = 3;
const int button2pin = 4;
const int button3pin = 5;
const int button4pin = 6;
const int button5pin = 7;
const int button6pin = 8;
const int button7pin = 9;
const int button8pin = 10;
const int button9pin = 11;

const int led1 = 0;
const int led2 = 1;
const int led3 = 2;
const int led4 = 3;
const int led5 = 4;
const int led6 = 5;
const int led7 = 6;
const int led8 = 7;
const int led9 = 8;

void setup() {
  strip.begin();
  strip.show();

  pinMode(button1pin, INPUT_PULLUP);
  pinMode(button2pin, INPUT_PULLUP);
  pinMode(button3pin, INPUT_PULLUP);
  pinMode(button4pin, INPUT_PULLUP);
  pinMode(button5pin, INPUT_PULLUP);
  pinMode(button6pin, INPUT_PULLUP);
  pinMode(button7pin, INPUT_PULLUP);
  pinMode(button8pin, INPUT_PULLUP);
  pinMode(button9pin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(button1pin) == LOW){
    strip.setPixelColor(led1, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button2pin) == LOW){
    strip.setPixelColor(led2, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button3pin) == LOW){
    strip.setPixelColor(led3, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button4pin) == LOW){
    strip.setPixelColor(led4, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button5pin) == LOW){
    strip.setPixelColor(led5, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button6pin) == LOW){
    strip.setPixelColor(led6, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button7pin) == LOW){
    strip.setPixelColor(led7, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button8pin) == LOW){
    strip.setPixelColor(led8, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button9pin) == LOW){
    strip.setPixelColor(led9, strip.Color(20, 55, 0, 0));
  }

  strip.show();
}

int buttons[9]={3,4,5,6,7,8,9,10,11}; int leds[9]={0,1,2,3,4,5,6,7,8,9};...

#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);
// The maximum pin number for the buttons
const int MaxButton = 11;
// The value if the pin is not connected to an LED
const int NotConnected = -1;
// The connections from buttons to leds.
const int Connections[MaxButton+1] = {NotConnected, NotConnected, NotConnected, 0, 1, 2, 3, 4, 5, 6, 7, 8};

void setup()
{
  strip.begin();
  strip.show();
  for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
  {
    if (Connections[pinNumber] != NotConnected)
    {
        pinMode(pinNumber, INPUT_PULLUP);
    }
  }
}

void loop()
{
  for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
  {
    if (Connections[pinNumber] != NotConnected)
    {
        if (digitalRead(pinNumber) == LOW)
        {
            strip.setPixelColor(Connections[pinNumber], strip.Color(20, 55, 0, 0));
        }
    }
  }
  strip.show();
}

I can't test it, so I have no idea if it works, but it should do.

+1 for using const int instead of #define.


text:
Controlling a NC connection from two sources?
I'm trying to control a garage door opener. The button that lets you open the door from the inside is a NC connection (press the button and it goes to "open" and makes the motor run).
I want to keep that AND add another source (an Arduino w/ an RF module) that taps in to this.
Is there some sort of splitter I'd add to the garage door button wires to do this?

Just add the arduino switch in series with the button.

Are you certain that your existing circuit is NC?
The typical garage door opener button is a momentary switch. Many third party remote devices, including two that I have installed, tap directly into this circuit. Because the contacts short across the existing switch, activating one, two or three is insignificant. These switches are connected in parallel.
It would be a good idea to use an external isolation circuit to the Arduino, either a relay or SSR in order to ensure that there is no "injected" power from your circuit to the garage door circuit.
If your circuit is indeed an NC type, you would connect your new relay or SSR in series, using the device's NC connections. The locations for tapping into the circuit would be where your existing button resides or where those two wires engage your garage door mechanism.
I suppose my older garage door opener is NO, while newer models would use a different architecture, aka NC.


text:
Do I need capacitors for these LEDs?
I have 5 of these NeoPixel LED's.
For these particular LED's, they recommend "use of a 0.1 μF capacitor between + and ground".
Here's what I've got:

The blue's are 100 μF and the little brown ones are...I have no idea. Both were just in this starter kit. Maybe 100 pF?
So, a few questions around this...

Are these actually necessary and why?
Is there any harm in using much higher capacitors than recommended?

Dont know if needed....they arent there on a ledstrip are they? Try and find out...probably you wont kill it. What says the brown capacitor....100N is enough

The little brown ones also have their values printed on them. Do you need a magnifier?

The capacitors are called decoupling capacitors and are used to provide current at very short notice.
The LEDs, when not fully on or fully off, switch rapidly on and off.  This switching needs current to be provided very rapidly at short notice, and batteries and power supplies aren't good at that - so you have the capacitors to act as a little reservoir of power that the LEDs can dip into.
The size of the capacitor (capacitance) can have an effect on how effective they are.  Bigger capacitors respond slower than smaller ones, but store more energy. So you need the capacitor to be small enough for it to respond fast enough. But if you have it too small it won't store enough energy to give to the LEDs and they will be unable to do their job.
0.1µF (or 100nF), aka "104" capacitors are usually reckoned to be a good rule-of-thumb value to use since they are small enough to respond rapidly and yet large enough to store enough power for most small high speed fluctuations.  The exact value though doesn't matter that much, however I would be wary about going below that, and going too high can be troublesome for other reasons as well as their slow response (google: "Inrush Current"). So you don't want to go too high. Around the 0.1µF to 1µF area is where you want to be, with maybe a 10µF for every group of 5 or so LEDs.
I would say 100µF is way too high to have on every LED, but maybe one of those on the breadboard where the power is fed in would be useful to provide a reservoir for larger low frequency demands from the rest of the board.

Are these actually necessary and why?

The datasheet for the WS2812 says a "typical application circuit" should have them:

If the manufacturer recommends it, I would say it is necessary. I'm sure they would be happy to not have to recommend extra parts, but testing would have shown they are necessary. As Majenko replied, putting in 100 µF when you only need 0.1 µF seems way overkill (to say nothing of more expensive).
And don't forget the 150R resistors, eh?


text:
How to store a function in a constant?
I'm trying to do something to this affect:
const string first_color = strip.Color(0, 60, 0, 0);
With the intended outcome being that I could use first_color wherever I'd have used strip.Color(0, 60, 0, 0) before.

Are you asking how to save the return value of the function so that you can reuse it, or are you asking how to create a reference to the function so that you can call it by invoking first_color? There doesn't seem to be much point to calling it repeatedly with the same parameters, unless it has some side-effects that you're interested in.

It sounds like you might want a preprocessor macro.

You pretty much need a helper function to do that; a small local function that calls strip.Color() with the intended arguments and returns strip.Color()'s return value if there is any.
int first_color(void)
{
   return(strip.Color(0, 60, 0, 0));
}

(assuming strip.Color() returns an int) which you would call with:
value = first_color();

If strip.Color() is a void function, then delete the 'return(' and one ')', fix the definition of first color to be void instead of int, and of course, don't try to use any return value from first_color().

It sounds like you might want a preprocessor macro:
#define FIRST_COLOR strip.Color(0, 60, 0, 0)

And then later
FIRST_COLOR;

This is basically just text substitution at the initial stage of the compilation process.  It is somewhat conventional to make macros all caps, but not required.  You can also define function-like macros which take arguments.

authors: Иван Маркович


text:
How do I hook up a 3V device to a 74AHCT125 (Quad Level-Shifter)?
I have this level shifter that I'm trying to feed a 5V power source and then hook up a 3V device.

I've got the 5V source hooked up fine (on the top pinouts), but having trouble figuring what the "power out" would be that's 3V.
Here's the data sheet.

That's because it can be used to shift 3V to 5V, not 5V to 3V.

It's not a level shifter. It's a buffer chip that can be used to level shift in one direction only.
It is good for shifting from a low voltage logic signal (3.3v, say) up to a 5V logic signal. It can't shift down from 5V to 3.3V.
Basically it works by having a fixed voltage that it considers to be a logic HIGH, and any voltage above that will be output as 5V. Any voltage below will be output as 0V.  This is the "TTL Logic Level" specification in the datasheet.
So if you have a sensor that emits a 3V logic signal the HIGH logic value will be above its fixed threshold and will trigger a 5V HIGH on the output.
In contrast "CMOS" logic uses a percentage of the supply voltage to set the thresholds (usually > 0.6 x Vcc), and a 3V signal is less than that (3.3V is about bang on it, so is "iffy"), so won't work (or not reliably).

The datasheet would let you think it cannot shift in that direction, but it's the chip recommended by Adafruit to do so : https://www.adafruit.com/product/1787
The "trick" is to feed it 3V power. It seems it will then happily accept 5V input and produce 3v outputs.


text:
Reduce 5v Trinket Pro to 3.3v?
Apparently these nRF24L01+ modules need 3.3v, but I've only got 5v Trinket Pros that I'm using.
How can I reduce the voltage to the RF transmitter?
Would a voltage regulator work? Specifically looking at this: http://addicore.com/product-p/165.htm

The NRF24L01+ has inputs that are 5V tolerant! So you only need to provide 3.3V on the Vcc pin of the module, which you can do by putting a voltage regulator between it, and the 5V of the Trinket. So there isn't really any need to convert the Trinket to 3.3V.
PS Remember to add some capacitors to the output of the voltage regulator, as the NRF needs a pretty stable 3.3V. Noise in the power lines can cause instability in the operation of the device.

I also had a 5V Pro Trinket on hand and needed to connect one of its 5V output pins to the 3V pairing pin on an Adafruit's EZ-Key HID. I solved it easily for the price of a couple 1/8 watt resistors by including a simple voltage divider in the circuit as a "level shifter" and it works like a charm. In my case it's not serial data but give it a try.
Classic voltage divider equation: V out = V in * R1 / (R1 + R2)

In setup(), set the 5V Pro Trinket digital out pin to be normally LOW when it's not doing anything in the sketch, e.g. if it were pin 8: pinMode(8,OUTPUT); digitalWrite(8, LOW);
Connect this 5V output pin to one end of a 1.8K resistor (the "R1").
Connect the other end of that resistor to both: your 3V module's input pin AND to a 3.3K resistor (the "R2") to ground.
If you have a meter, perhaps before connecting to your module input first double check your circuit at the juncture of the resistors. Actual serial data probably won't produce a reliable reading so temporarily alter your sketch to just take the 5V Pro Trinket pin HIGH. I measured 3.1 V output on mine when the output goes HIGH and it works great with the EZ-Key module.

As said by JayEye: there are 3,3V Trinkets and that is probably the cheapest option.
If you want to pay the extra money, there are special boards for it by addicore: https://www.amazon.com/gp/product/B00VFNZN8K/ref=s9_dcacsd_bhz_bw_c_x_3
third option is to build yourself a small voltage regulating circuit. The regulator that you linked to will do.

There are 3.3V Trinkets. Anything you try to do will cost more than buying one.

LM78**, resistors... simple IC and discreet wouldn't cost more.


text:
My RTC is returning a sporadic date/time
RTC seems to be sporadically returning bogus date/times. Here are the logs from my serial monitor:
2016/3/23 8:19:46
2017/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2165/165/165 15:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46

That 2165/165/165 15:19:46 appears throughout the logs.
Here's the relevant code:
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;

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

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }
}

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

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

I have a Grove RTC module.

165 is a failure to communicate. Check your wiring for loose connections.

I think the single 2017 is also quite interesting (2017/3/23 8:19:46)

Are you using an I2C chip on the end of a 20 foot length of wire?

@Majenko Negative. The RTC module (which, to my understanding has the I2C built in) is attached to a ~10 inch piece of wire.

10" is still pretty long for I2C. Are you using the internal pullups of the Arduino or do you have real resistors attached to the wires?

I think the single 2017 is also quite interesting - a single-bit error like that tends to suggest that there is indeed something wrong with the communication, like lack of pull-up resistors, or too long a cable.

Previous reports of this RTC problem (1,2,3) attribute it to hardware issues, such as broken wires (to SCL or to battery) and overvoltage (>3.6 V supply vs 3 to 3.3 V).
If your setup uses breadboards or other temporary connections, you might try adding some redundant wires.  If your setup uses soldered connections, go over them carefully, looking for shorts and opens; or use a solder sucker / solder wick to remove old solder; then solder anew to make fresh, bright connections.
If you don't locate a hardware problem (and perhaps even if you do) you could add error-testing to your sketch.  That code would see if all relevant fields have valid, in-range values.  If any fields are invalid, it would delay a few milliseconds and then reread the RTC.

Loose wiring was the ultimate cause and making some adjustments in that area did the trick.

The RTC library does not check for communications success. In particular, here:
DateTime RTC_DS1307::now() {
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.send((byte) 0);
  Wire.endTransmission();

  Wire.requestFrom(DS1307_ADDRESS, 7);
  uint8_t ss = bcd2bin(Wire.read() & 0x7F);
  uint8_t mm = bcd2bin(Wire.read());
  uint8_t hh = bcd2bin(Wire.read());
  Wire.read();
  uint8_t d = bcd2bin(Wire.read());
  uint8_t m = bcd2bin(Wire.read());
  uint16_t y = bcd2bin(Wire.read()) + 2000;

  return DateTime (y, m, d, hh, mm, ss);
}

There should be a check for a zero returned from Wire.endTransmission(). It isn't otherwise possible to detect if the data is invalid (if we got the endTransmission OK) however generally speaking I2C will return 0xFF if the transmission has ceased.
The code in the library for bcd2bin is this:
static uint8_t bcd2bin (uint8_t val) { return val - 6 * (val >> 4); }

You can see that if passed 0xFF (255) it will return:
   255 - (6 * 15) = 165

Thus if any of the minutes, hours, day or month (which are not further affected in the code above) are 165 (or if the year is 2165) you can assume the whole date/time is bad.

Thanks for the explanation! You mentioned in a comment about there being something potentially wrong w/ communications...specifically "lack of pull-up resistors". In my set up, I don't have any resistors added. I've got wires from the RTC that go to +/- and then A4 & A5 on the Uno. Should I add resistors somewhere in that set up?

Judging by the schematic I just downloaded, that board already has them.


text:
How do I adjust the scale/calibration of a photoresistor?
This photoresistor has a min/max of 0-1023.
I'm trying to scale the brightness of a cathode RGB LED based on the sensor's value, but based on my current lighting, the min/max readings I generally am getting are 100-700.
So how can I scale the sensor reading so that 100 = no light on the LED and 700 = max brightness?

What circuit?  What code?   output=constrain(map(sensor,100,700,0,255),0,255)); per http://arduino.stackexchange.com/q/9219/6628 ?

You can easily scale in Arduino code with the map() function.
e.g.:
const int MIN_LIGHT 100;
const int MAX_LIGHT 700;

int light_reading = analogRead(A0);

// Convert MIN reading (100) -> MAX reading (700) to a range 0->100.
int percentage_bright = map(light_reading, MIN_LIGHT, MAX_LIGHT, 0, 100);

But you may need some calibration of your system to handle different ambient light situations. What reading do you get in direct sunlight for example?
So then I assume you're using PWM (Pulse Width Modulation) to drive the LED.  This requires a value between 0 & 255.  Once again we can use the map() function.
// Convert light-value % (0-100) to PWM speed (0-255)
int led_brightness = map(percentage_bright, 0, 100, 0, 255);
analogWrite(LED_PIN_RED, led_brightness);

Obviously these bits of code can be reduced down to a single line - mapping directly from the reading to the desired result.

A light_reading of 90 would give a negative percentage_bright, which could in turn produce negative led_brightness, which would behave badly.  You need a light_reading = constrain(light_reading,MIN_LIGHT,MAX_LIGHT) or percentage_bright=constrain(percentage_bright,0,100)

@Dave X - Yep, that's why I had the note about calibration.  But I didn't want to confuse the explanation of the map() function.


text:
Arduino reads bogus from serial
Recently I've started playing around with an Arduino Uno (rev 3), and I've set up a communication bridge between the Arduino and my computer using Python. So I send a command in Python ("ping" for instance), which is then read and interpreted. I've had it working before, using the Python commands to control a motor, but today it became non-responsive. However, only if I boot the serial monitor from the Arduino IDE, it suddenly accepts my commands again. Further inspection reveals that the Arduino is probably reading empty or corrupted data, interpreting it as ð, à and ÿ and such.
Here is an excerpt of the Python code I'm using:
import sys, glob, serial, time, re

class interface:

     timeout = 2    # 10 second time-out

    def __init__(self):
        port = "/dev/ttyACM0"
        self.connect(port)
        pass

    def connect(self, port="/dev/ttyACM0"):
        global arduino
        arduino = serial.Serial(port, baudrate=115200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0.1)  # Establishing connection
        time.sleep(3) # Allowing the connection to settle
        arduino.flush()
        print "Connection established..."

    def ping(self):
        arduino.flush()
        arduino.write("ping")
        msg = self.listen_arduino()
        print msg
        if msg == "ping_ok":
            print "pinged"
            return True
        return False

    def listen_arduino(self):
        timeout = self.timeout
        matcher = re.compile("\n")
        buff = ""
        t0 = time.time()
        buff += arduino.read(128)

        while (time.time() - t0) < timeout and (not matcher.search(buff)):
            buff += arduino.read(128)
        return buff.strip()

And here is the Arduino C code:
String readString;

void setup() {
    Serial.begin(115200); // use the same baud-rate as the python side
}

void loop() {
    readString = listen(); // listen for any commands
    if (readString.length() > 0) {

        Serial.println(readString); // print the command

        if(readString == "ping") {
          Serial.write("ping_ok");
        }
    }
}

String listen() {
    String readString;
    while (!Serial.available());
    while (Serial.available()) {
        delay(1); // Allow the buffer to fill
        if (Serial.available() > 0) {
            char c = Serial.read();
            readString += c;
        }
    }
    return readString;
}

I suspect there is something fishy with the connection I'm making on the Python side, as the Arduino IDE serial monitor works just fine. I hope anyone can spot the problem in this code, I'm willing to provide more details on request.
Thanks

Try with one letter. See if that helps.

change the code to Serial.available()>0 because by default the output is -1, this could be the reason you are receiving junk values.

I've discovered that there was another program trying to access the Arduino, interfering with the code above and causing corruption of the signal. After terminating the intrusive program, the code worked just fine.


text:
How to make an Arduino USB programming circuit?
I am designing a PCB in which I am using the MCU used in Arduino UNO which is Atmega328P and some other components as per my project requirements. I have almost designed the circuit but I am confused with the USB programming part. I want my MCU to be programmed using USB B Type just like we do it in Arduino UNO. My friend suggests me to purchase an Arduino UNO device and program that MCU and then put it in my circuit. But I don't want to do it like this. I have found the schematic design but its very confusing. Can anyone help me out with this.?

Eh. Save yourself the pain and just use ISP.

Can you explain more.?

The "core" part of the arduino uno board is the Atmega328P, with the 16MHz oscillator (can be removed if you want to use the internal 8MHz clock - search for optiboot) bypass capacitor(s) (C6, but I suggest you to put another one close to the other pair of power pins), reset circuit (RN1D and, I suggest you, also the button), ICSP connector and, suggested, capacitor C4. You will need an ISP programmer to put at least the bootloader on board. If you want to program through serial, just add a usb-serial converter (suggested: FTDI). If it has also the DTR pin, you can enable auto-reset

To enable it, just add the capacitor C5 between the reset node and the DTR pin. And that's all. If you want everything on-board, you can use a FT232RL (and its VCP drivers), which does not require you to flash the firmware (like the Atmega16U2 used by the real arduino boards). Otherwise you can use any USB-UART module (and if it has the DTR pin, well, better). I suggest you the FT232RL because I recently got a prolific 2303 cable and.. There are no more drivers for Win8+, while FTDI goes on supporting their products

It is quite a lot simpler to obtain an FTDI USB - TTL Serial cable. (The link goes to the American supplier, Sparkfun, but such cables are available from many online suppliers.) They are typically made with a 6-pin female header instead of a USB B connector; you may have to make up that part yourself, if it is important to you. If you only need USB functionality for programming, one cable can serve any number of boards (one at a time, of course), no need to build it into each board.

Not 100% exact. In fact this requires you to have a Atmega328P with bootloader; commonly sold atmega, however, do not have it, so you will also need the ICSP port to program the bootloader the first time

It takes only one chip with a bootloader to make an arduino work-alike which can then flash the bootloader into bare chips. A borrowed work-alike can flash that first chip. The OP seems familiar with Arduino and there was no constraint that no Arduino should ever be used

Totally agree, but... If there is no ICSP connector on the PCB then you will not be able to program it once soldered. Hence, the "not 100% exact", since you can fix it by pre-programming the bootloader, but 1) it's more useful to put an ICSP connector on the PCB (if the bootloader gets corrupted you can flash it again later), and 2) better saying it before the OP solders the IC on the board (and then finds out he can't upload with just a USB-TTL cable)

Looking at the schematic design, you need atmega8 to make a usb programming connection. Design your circuit exactly like in the schematic.You will also need bootloader for it, so use any programmer like usbasp, connect its pins to mosi, miso sck, rst,vcc,gnd and click on burn boot loader in arduino ide

If you wanted a more permanent option on the board, you could also add a USB to FTDI chip like this: http://www.mouser.com/Search/m_ProductDetail.aspx?FTDI%2fFT232RL-REEL%2f&qs=D1%2fPMqvA103RC6OU6bKtoA%3d%3d&gclid=CNmDjr7dvssCFYZefgod9jgPeQ

Again, this requires you to already have a Atmega328P with bootloader


text:
Usefulness of measuring 0v using ADC
I'm looking at the datasheet of the ATMega328, and I see the different channels you can select for AD conversion. ADC0..7, ADC8 (temperature), 1.1V (VBG), and lastly 0V (GND).

What would be the use of measuring 0V?
Would it ever result in a reading other than 0? I find it very intriguing.

The datasheet doesn't seem to give any additional information about it.
AVR126 seems to give a hint:

configure 0V (GND) in ADC by setting Mux bitfield (MUX3:0) equal to 1111. This is done to discharge the capacitor of ADC.

Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz).
Is it to protect the ADC from to high a voltage in the ADC capacitor, when changing to a different (lower) reference voltage? Rather odd you need software to protect the IC, and it's not even mentioned in the datasheet. Also I've never seen anyone do this (e.g. when measuring the internal temperature of the ATMega).

That quote you mention says it all really.  It's purpose is to discharge the Sample And Hold capacitor.
That capacitor is used (as I'm sure you are aware) to store the incoming voltage while it's being sampled by the ADC.  The ADC operated in two main phases:

Acquisition
Sampling

During acquisition the capacitor is connected to the incoming voltage.  During sampling it is disconnected from the incoming voltage and the voltage it stores is read into the internal registers.
It takes a certain amount of time for the voltage in the capacitor to equal that of the incoming voltage.    If you try reading at higher speeds then what voltage was in the capacitor from the previous sample can affect the new reading.  However, if you do each sample always from a known voltage in the capacitor (0V) then you get much more stable results.
Another good use for it is when using the ADC as a Charge Time Measurement Unit.  This is the proper way of performing capacitative sensing.  You apply a constant (tiny) current to an external capacitor (the sensing plates) for a specific period of time.  When that time is up you disconnect the constant current source and measure the voltage that has developed across that capacitance.  The capacitances and currents are small, and if there is a charge in your S&H capacitor at the time you do the sampling that will be back-fed into the touch sensor capacitative plates changing the voltage.  By ensuring that the S&H capacitor is at 0V before you sample the plates you won't be adversely affecting the voltage on the plates with successive readings (well, you will, but it will be consistently in the same way every time so it won't affect your overall results).

About S&H: unless one is really desperate, shouldn't the acquisition phase be such that it allows the capacitor to charge to whatever is considered precise enough for the maximum variation? Iow, taking for example Ta=5RC, where R is the parasitic resistance and C the capacitance, don't they pretty much set the max frequency? I'd think that if one is really desperate to the point of forcing such constraint, it would be faster to not discharge the capacitor at all, assuming that there is somewhat a correlation between successive readings. Especially if performed at high frequency.

Forcing the initial voltage on the capacitor to be 0V means that one has to always allow enough time to reach Vmax. By limiting the maximum Voltage variation, it is possible to measure at increased speed, accepting that there might be a possibly large error, depending on how much the assumption on the max DeltaV is violated.

So consistency. That makes sense. Though with the speed example, you would lose half the rate, cause you do a 0v read between every regular read. Also, if the speed speeds are high, is the sample period long enough to fully discharge the cap?

Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz).

The document actually says:

The ADC can prescale the system clock to  provide an ADC clock that is between 50kHz and 200kHz to get maximum resolution.

(My emphasis)
It goes on to say:

If ADC resolution of less than 10 bits required, then the ADC clock frequency can be higher than 200kHz. At 1MHz it is possible to achieve eight bits of resolution maximum.

I did some testing on this page with different prescalers. The results showed that reasonable results could be obtained even with a 1 MHz ADC clock:
Prescaler 2

Analog port = 0, average result = 1023
Analog port = 1, average result = 1023
Analog port = 2, average result = 1023
Analog port = 3, average result = 1022
Time taken = 26220

Prescaler 4

Analog port = 0, average result = 673
Analog port = 1, average result = 718
Analog port = 2, average result = 512
Analog port = 3, average result = 193
Time taken = 32780

Prescaler 8

Analog port = 0, average result = 842
Analog port = 1, average result = 677
Analog port = 2, average result = 509
Analog port = 3, average result = 34
Time taken = 46040

Prescaler 16

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 509
Analog port = 3, average result = 0
Time taken = 73164

Prescaler 32

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 508
Analog port = 3, average result = 0
Time taken = 128040

Prescaler 64

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 508
Analog port = 3, average result = 0
Time taken = 240972

Prescaler 128

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 508
Analog port = 3, average result = 0
Time taken = 448108

The four test voltages were, and their results should have been:

5V (should return 1023)
3.3V (should return 674)
2.5V (should return 511)
0V (should return 0)

The tests were done in rapid succession, no allowing for the ADC to recharge or anything:
 unsigned long startTime = micros ();
  for (int i = 0; i < ITERATIONS; i++)
    {
    for (int whichPort = lowPort; whichPort <= highPort; whichPort++)
       {
       int result = analogRead (whichPort);
       totals [whichPort - lowPort] += result;
       }
    }
  unsigned long endTime = micros ();

Thank you. I guess I skipped that page when browsing your site. In the sample code belonging to the document, they use all the 10-bits. I just find it weird to give an example that's not as precise, and not even warn about this. Though your test seem to indicate there isn't any difference in the results. I guess I will 'overclock' my ADC to get a bit more battery life on my current project.


text:
How do I connect an 8x8 LED RGB matrix to an Uno?
I have this 8x8 LED RGB matrix. How do I get it connected to an Arduino Uno?
It came with no other wires/modules/connectors and has a veritable crap-ton of pins to connect.

You can find the data sheet at the link that was provided in one of the answers at the Amazon page you provided above:
http://www.nooelec.com/files/GTM2088ARGB-28.pdf
a quick look at the data sheet tells me that you will very much need a few shift register chips and reasonably strong matrix programming skills.

Shift registers via SPI are your friend. Also, you could use multiplexing to get away with 8 pins.

Because you have, unfortunately, decided to buy a product without a datasheet (and the product description can't even decide if it's common anode or common cathode!), you'll have to find a product which is similar that has a datasheet, and determine by experimentation if the pinout matches.
For instance, this Sparkfun LED matrix looks similar. Take a look at the datasheet for an internal schematic and manually verify the pinout.
Once you know the pinout, you can begin to figure out how to drive it. There are many ways to drive large numbers of LEDs, one of the simplest of which is a bunch of shift registers.
Getting yourself a couple of 595 SRs and playing with the matrix (hint: try and get a single colour working first, then add the others) would be a good place to start.
Alternatively, the display description says that it is compatible with "Arduino RGB LED Matrix Driver Shield". That may or may not be true, but looking at a schematic of that board would give you insight into how to drive the matrix. I believe that board uses a DM163 8x3 CC LED driver chip, which seems to be perfectly suited to drive the matrix, but buying and wiring that chip up may be non-trivial.

It is common anode matrix. Look at the headline.

@IOBToolkitTeam And from the description: "...into one common cathode housing."

Busted for not being careful. :D

The idea is to use a shift register PMIC (power management ic), such as the MAX6971; you'll need a pair of them; each has 16 bits of output; if you want to really shave off a dollar, get four TPIC6C596.

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


text:
Detect if multiple variables are the same?
I'm setting a series of variables with: uint32_t currentLedColor[9]
What I'd like to check is if certain ones of those are the same.
Basically want to say if currentLedColor[0] and currentLedColor[1] and currentLedColor[2] are equal
How would I write that?

You run multiple checks. For example:
if (currentLedColor[0] == currentLedColor[1] && currentLedColor[0] == currentLedColor[2]) {
    // do something
}


text:
What would the total current requirements be for these items?
I'm using 5 of those 8mm NeoPixels + a 5V Trinket.
I'm trying to get a rough estimate of the current requirements that would have, assuming all 5 NeoPixels were running at full brightness "white" (255 RGB).
I'm voltage-regulated to about 150 mA from the Trinket and my current hunch is that those NeoPixels need more than that, but trying to confirm it.

According to the data sheet each LED takes a maximum of 3*20mA, so you are pulling 300mA.  You  are going to need a bigger power supply :(


text:
Trinket works with USB but not with wall adapter
My Adafruit 5V Trinket works fine when powered via USB connected to my computer (and the power going in to the Trinket is 5V), but if I use a 9V wall adapter with a microUSB adapter, it just powers on but doesn't seem to actually run the program on the Trinket.
Am I over powering the Trinket and sending too much voltage to everything? If that's the case, is there some way to decrease the voltage?

Normally you should never connect more than 5v to a USB connector.  This particular board seems to run the USB VBUS through a diode into its regulator, in the same way it routs its VBAT input.  So conceivably you would get away with it.  But it's still a risky idea to have such non-standard cable assemblies around as they might be accidentally connected to something else that would not tolerate this!  A possibility is that your 9v adapter is faulty, or perhaps it outputs AC, or insufficiently filtered DC.

Yes, you are probably over-powering the trinket. The trinket expects 5V on the USB connector. However, it has an voltage regulator on board that can take up to 16V.
The BAT pin is connected to the voltage regulator and can take anywhere from 5.5V to 16V.

It's not entirely clear what you are proposing here, but the schematic shows the VBUS and VBAT inputs to be distinct, but have identical circuitry, so an input voltage that is in tolerance for one should be for the other... if only for this particular oddball board.


text:
Mega 2560 powered with 7V don't work correctly
I have an Arduino Mega 2560  with a GPRS seeedstudio shield and an USB Host CircuitsAtHome shield which work fine when powered with USB or with an adjustable voltage regulator set at 8V.
When I set this voltage regulator at 7V (minimum voltage from the spec to get the better efficiency) I am still reading 5V and 3.3V on the pins of the Arduino and all the leds of the Arduino and the GPRS shield seems fine but the USB Host CircuitsAtHome shield seems to not work properly.
I cannot debug it using the console because if I plug the USB cable, everything works fine...
Why 7V fail while 8V is ok?
The adjustable voltage regulator can provide up to 5A which is plenty.

7v is the minimum voltage from which spec? Can you provide links to all the components of the circuit?

From this page : http://arduino.cc/en/Main/arduinoBoardMega2560 "input voltage (recommended)"

The Voltage-Regulator has a dropout-voltage of 1,2V, but in line to the regulator is a diode, which adds another minimum 0,7V (dont know the exact part number, so i guessed the voltage of a Si-diode at ~1A). So you have to supply at least 5 + 1,2 + 0,7 = 6,9V. I presume the circuit doesnt draw a constant current all the time, so from time to time the regulator cant supply the 5V because you sink under the necessary dropout-voltage of the rehulator/diode-combination.
-> Use 8V  or bypass the Diode D1 (with a solder-bridge) and use 7V if its a must and you are sure the input-polarity is always correct.
Arduino-Mega-2560-schematic: http://arduino.cc/en/uploads/Main/arduino-mega2560_R3-sch.pdf

You need to be clear about how you are hooking this up. Are you feeding 7V into the Vin on the Arduino? If so, then the voltage regulator on the Arduino is attempting to regulate 7V down to 5V. As Echo says, 7V isn't quite enough for the built-in voltage regulator.
If your voltage regulator outputs clean, noise and ripple free regulated voltage, you could set it to 5.0 volts and feed it directly into the Arduino's 5V line, bypassing the regulator on the Arduino completely. If you do this you need to make absolutely sure that you give it exactly +5V though, as you will likely destroy the board if you go much over 5V or wire it backwards.
If it's a switching regulator then you might need to add a choke to the output of the regulator to get rid of high frequency noise on its output.

I am currently feeding the board using the 2.1mm jack plug of the board. Will it be safe to power the board at 5V  (directly to the 5V pin of the board) with this converter : http://www.seeedstudio.com/depot/Adjustable-StepDown-DCDC-Converter-10V-17V18A-p-1717.html?cPath=1 . Is it outputs clean, noise and ripple free regulated voltage? Thanks!


text:
How to connect a 2 cell LiPo batter to Arduino Motor Shield?
I am trying to connect a 2 cell 7.4 volt LiPo battery into my motor shield. I am a beginner at robotics so I am not sure if I just connect the battery, via a connector of some sort, into the motor shield itself or do I use some 22 AWG wire and connect it via that way. Sorry if that sounds confusing.

22 AWG might be a little thin for some wire IMO; for power lines it's usually best to get something thicker, of course something really big would have too much resistance: that's why some power lines have more than 2 cables. (In the US, anyway)

You might want to check this about arduino overheating.

From the Motor Shield page,

External (non-USB) power can come either from an AC-to-DC adapter
  (wall-wart) or battery. The adapter can be connected by plugging a
  2.1mm center-positive plug into the Arduino's board power jack on which the motor shield is mounted or by connecting the wires that lead
  the power supply to the Vin and GND screw terminals, taking care to
  respect the polarities.

So they provide the screw terminals for a battery, you should be able to insert two wires from your battery/pack into the terminals. If your battery has a connector on it, you'll need to either cut it off or find an adapter.
Be extra careful: if you have exposed leads from your battery and they touch, it'll get extremely hot and possibly catch fire.

Do I need a separate 5V battery to power arduino board, and my 7.4V battery for motor shield? Can I use one for both?

it is up to you.
Welded cable is better, but you will probably need a connector, so you should take care to use low-ipendance one that can hadle your current need, like bullet connector used by RC toys.
Also the battery should have a discarge current higher that the maximum current used by the engine: normaly this can be calculated by the discarge factor (labeled as 'C' on the hobbyst battery) multiplied by the capacity in Ah o the battery. Pay attention to this as this can damage the battery and alco cause lipo-fire, witch cannot pulled off with just water, you need an extinguer. (this is what happen when you short-circuit the + and -)


text:
atmega16 in Arduino Board
I had a very common question. Why a additional MEGA used in most of the Arduino Boards. Arduino board Mega2560 also have a MEGA16U2 controller on board which i think is used for programming via USB. Is there any other specific usage of atmega16 on arduino board.
Thanks


text:
Serial communication using Arduino and TeraTerm
I wrote a simple serial program using Arduino Mega 2560, it is connected to COMPORT 10. Here is the program I Wrote,
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  Serial.println("HELLO");
  delay(1000); //Send every one second
}

Now, I tried to send this message "Hello" to TeraTerm (COMPORT 1, for this I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0. Doing this I do receive message in my TeraTerm screen but the received message doesn't make sense, its receiving garbage. Its not the case of mismatch of baud rate I am using 9600 on both the side.
However I do receive message "HELLO" in the serial monitor. Is there something I am doing wrong that I am not receiving message on TeraTerm.

Are you just plugging straight into a 9 pin D connector on the back of your computer, or are you using a USB to serial adapter of some form - if so, what is it (link)?

What is TeraTerm? Can you post a link please? it is connected to COMPORT 10 ... COMPORT 1, for this I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0. You've lost me here. You connected what to what?

@NickGammon Tera Term is like a serial monitor just like hyper terminal,putty,docklight. Well this question needs a more explanation because author dont need to connect anything, arduino itself is connected to Com port so you can easily see what you are sending. Or if he is connecting it to some device, then what device?

My guess, from the scant information we have so far, is that the signals are inverted polarity, and quite possibly the wrong voltage as well.

... I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0.

But neither device knows what voltage they are. You need to connect ground as well so that they have a common reference.

Whatever ground is to whatever ground is.

Hello everyone thanks for your reply,
I found the problem :D and was also able to solve it.
I was directly connecting the Tx and Rx pin of Arduino to the Rx and Tx pin of DB9 connector on PC. Since, DB9 on the PC operates on higher voltage than the operating voltage of the Arduino which is 5V. This mis-match of the voltage was causing the problem, So in order to solve this i added a level shifter in between (MAX232) and now it works perfect.
Thanks everyone for replying.


text:
Newbie Question with 4 pin button
I suspect this is a very Naive question.
But the answer will teach me a lot.
Why does this circuit work when I connect the Digital Input (Digial Pin 2) to Pin 4 of the push button. But does not when I connect the push button to Pin 3. I missing something about how power flows when the button is pushed.
Ray K

Are you using the pin assignment convention of having pin 1 on the bottom left and counting up going counterclockwise?

Please clarify what pins you are talking about. In this case top-right, top-left, bottom-right and bottom-left would be a lot clearer.

Internally those little tactile switches look like this:

That means that the two pins on the same long side are connected together.  So you can use, when you hold the switch vertically as in the image on the page you link to the two left-hand pins are linked together, and the two right-hand pins are linked together.
So you can use either both the top pins, both the bottom pins, or the top left and bottom right or the top right and bottom left.
Using either both left hand pins or both right hand pins will be as if you were sat on the button and it was permanently pressed.

ok - so let say I do the silly thing, and I connect the 5V VCC and the Digital Input (Pin 2) on the same long side. Is there then constantly power flowing to the Digital Input - making it impossible to differentiate between keypresses?

Yep. That's it exactly.


text:
MCU to switch single coil latching relay not working (attempting array with common gnd)
I have several single coil latching relays, (EC2-5SNU).
I am trying to control them by an MCU; connected directly they work fine, but I am iffy about keeping it this way so I'm trying to power them through a darlington pair array, (ULN2003).
Using the non-latching type, these work fine through the ULN2003, but attempting to interface the code below with the latching type isn't going so well and i can't figure out why:
int right = 12;
int left = 10;

void setup() {
  pinMode(right, OUTPUT);
  pinMode(left, OUTPUT);
}

void loop() {
  digitalWrite(right, HIGH);  //reset
  digitalWrite(left, LOW);
  delay(2000);
  digitalWrite(right, LOW); //set
  digitalWrite(left, HIGH);
  delay(2000);
}

I have four connected with a common pin, but to simplify i've tried and failed to have the code above work on a single relay, as shown below:

Measuring the voltages out of the MCU show the correct levels, keeping in mind the ULN2003 acts an inverter, so i've set the boolean logic accordingly.
The voltages at the output of the ULN seem to stick at 0.6V, I've tried a bunch of permutations, including having one pin (on the common pin setup) connected directly to the MCU.
Does anyone have any ideas?

You need to use an h-bridge as if you were driving a motor. For this kind of relay you need to be able to both sink and source current, which a Darlington pair cannot do, it can only sink.
I guess you may be being thrown by the symbol of an inverting buffer used in the schematic symbol for the ULN2803 in your schematic capture package. It's incorrect, since it's not an inverting buffer, it's a Darlington pair:

simulate this circuit – Schematic created using CircuitLab
As you can see, setting the input HIGH will allow the transistor pair to conduct, but setting it to LOW will stop it conducting - so the output is either connected to ground, or is floating.

Thanks, that's the lesson i learnt the hard way. FYI to anyone reading, as calculated on page 8, the relays draw 25mA so can be attached directly to the MCU.

No, they can't be directly attached to the MCU, or not safely anyway. The back EMF from the switching is liable to damage the MCU. You should separate it with a proper H-bridge.

You're right, not the safest option, but connecting them through a bridge rectifier makes it so. https://i.sstatic.net/Q0uOL.png

I'm sure that you've solved this, given that the post is old, but it would work if you use pull-ups on the ULN2003 outputs. However, you should wire at least two open-drain buffers of the ULN2003 to both endings of the relay coil to ensure enough current when the microcontroller pulls down.
See this 2009 EDN post:
https://www.edn.com/drive-a-single-coil-latching-relay-without-an-h-bridge-circuit/


text:
Smallest digital 3-axis gyroscope pcb for arduino?
What is the smallest size digital 3-axis gyroscope pcb compatible with an arduino that I can buy or maybe make if its simple enough. I need one really really tiny probably around 0.8x0.1x0.5 (doesn't have to be that small but the smaller the better).
Thanks,

How small you can make depends on your skills - what are they? You may find trouble finding a fab house that is willing to make such small boards - commonly 10mm² is a minimum size.

The recent invensense parts come in 3x3 mm QFN packages, you could probably put them on a 6mm x 6mm PCB - really the challenge would be getting the wires for the offboard connections to them.  If you want really small, put a QFN ATmega on the reverse side as your "Arduino" and make the board no bigger than that requires.  OSHPark should be able to make the board for you for around $1 each, and you can build it with solder paste and a $60 hot air station.

smallest board is no board.  pick a small BGA or LGA shaped accelerometer and superglue it face down to the arduino board then solder fine wires beween the chip terminals and arduino terminals.
search digikey for 'spi accelerometer'

That technique is known as Dead Bug.

@Jasen I meant gyro but I get what you mean. I found an example of a LGA shaped gyro here: http://www.amazon.co.uk/GYROSCOPE-3AXIS-2000DPS-L3GD20-STMICROELECTRONICS/dp/B018COVMAM/ref=sr_1_14?ie=UTF8&qid=1457819243&sr=8-14&keywords=LGA+gyroscope How big would that chip be?

Of course that ends up as big as the arduino - which by extension means you could do the same thing with substantially easier soldering by using a typical SMT part as sold on a breakout board (which is incidentally often cheaper than buying a single bare chip anyway)

@ChrisStratton  Yh of course but couldn't I solder some 0.35mm^2 wires to the IC chip so that I can mount it wherever I want and have an Arduino somewhere else?

Arduino accesories are generally large because they are meant to be easy to use. mpu-6050 is a good example and you can find many decent breakout boards for it. But if you really want it to be very small, you should consider a custom solution for your problem like designing a PCB that holds both the microcontroller and the accelerometer.

Bosch CNO055 chip is an IMU-Cortex combo capable of outputting 3-D coordinates directly in several formats via several data interfaces. Adafruit has a product based on this chip, along with Arduino library (the CNO055 is in the middle to get you an idea about minimum size) -> https://www.adafruit.com/products/2472.


text:
Arduino Uno not working as usb HID interface
I have an arduino uno rev 3 and it works perfectly fine. I the OS I am using is Kali Linux 2.0 and you can upload everything as normal to the arduino.
I am following this tutorial:Arduino Uno as usb HID interface device
to use my arduino uno r3 as a hid device. After I upload the
Arduino-keyboard-0.3.hex

file, I plug cycle the board and I try uploading the example blink program. It always says:
Serial Port /dev/ttyACM0 not found.
Retry the upload with another serial port?
/dev/ttyS0

the /dev/ttyACM0 is my default arduino port and /dev/ttyS0 is one of my usb devices that is plugged in. Neverless, I tried uploading but it says board isnt responding. Can someone help me with this please?

You have reprogrammed the ATMega16U2 chip to be a HID device. Thus it no longer functions as a serial interface between the Atmega328P and your computer. You need to reflash the firmware on the ATMega16U2 to return to normal operation.
I have instructions for how you might to this on my bootloader uploader page. In brief, you need to put the original hex file back:
sudo dfu-programmer atmega16u2 flash Arduino-atmega16u2-Uno-firmware-Rev3.hex

There are other ways of turning your Uno into a HID device. Search for "Virtual USB Arduino".
More easily, get a Arduino Leonardo or Arduino Micro which are designed for this sort of thing.

Yes but how can I use it as a HID? ...  it cannot detect it so how would I be able to upload code to it  ...

What is "it" here? Look at this photo:

There are two processors on the Uno. It sounds like you have reflashed the ATMega16U2. Do you want to use the ATMega16U2 as a HID or the Atmega328P as a HID? They need totally different techniques.
Once you reflash the ATMega16U2 you can't "get to" the Atmega328P via the USB interface.
On the page you linked there is a workflow for programming the ATMega16U2. Are you following it? If so, which part is not working for you? If not, why not?

Yes but how can i use it as a HID? I cant seem to be able to use the Arduino IDE as it cannot detect it so how would I be able to upload code to it as they did in the tutorial?

See amended reply.

authors: Παναγιώτης Βλαχάκης


text:
How is IF( object ) evaluated? Follows from SD card example sketch
The "DumpFile.ino" example sketch from the SD library tries to open a file off an SD card, read its contents, and write them to the Serial Monitor. I am confused in how the following if() statement is evaluated:
File dataFile = SD.open("datalog.txt");

if (dataFile) {
// read and print, then close
}
else {
// print error message
}

There must be some implicit conversion on dataFile which depends on whether or not SD.open("myFile.txt") was successful. I would like to understand how this implicit conversion occurs. Which property of the File object determines if the if() statement evaulates true or false?

It calls the bool() operator.

There is an operator bool which does the test:
File::operator bool() {
  if (_file)
    return  _file->isOpen();
  return false;
}

When used inside an if the compiler invokes the operator bool() which does the test you see above.

Thanks, it is obvious now that I see it. I've indeed found that this defined in the File implementation.


text:
Zeroing a Vernier force probe
For a class assignment I have been tasked with zeroing a Vernier force probe by typing a command into the serial monitor. I am having trouble writing the code for this algorithim. I was hoping to give the monitor the command and have it save the analogread as a variable which I can later subtract from future reads. Does anyone know if I can save the analogread value without it being updated in a loop? If, so how?

Not sure if this is what you mean, but:
const int FP = 0;  // force probe analog pin
const int OFFSET = 10; // your deadband depending on your sensors consistency too
int init_read = 0;  // initial read
int curr_read = 0;  // this will be constantly updated till zeroing is done

void setup(){
  Serial.begin(9600);
  //the rest of your setup()
}

void loop(){
  if (Serial.available() && (Serial.read() == 'z')){  // if you sent anything with the monitor and if 'z' is present
    init_read = analogRead(FP); // initial read from sensor before 'zeroing' begins
    while (abs(curr_read - init_read) < OFFSET){ // here you indicate the condition that would mean the probe has been zeroed
      // make your adjustments or whatever
      curr_read = analogRead(FP);  // take a new reading and check in the next iteration
    }
    Serial.print("Zeroing is done.");
  }
}

z is the command you send from the serial monitor to begin zeroing.

There is usually some jitter in analogRead, so you might want to compare for "almost the same".

Right...will edit...

The main issue i am having is saving an analog read value. This seems to be an issue because the analogread value keeps refreshing. Essentially what i want to do is save an inital analogread value as "x" and then have the proceeding values be realreading-x=reading

@JaimeTorres If you place your variable 'x' in setup() like I did, it wont be updated. Do you understand the code above?


text:
Arduino SoftwareSerial not receiving data from Neo-6M GPS module
I am trying to hook up my Neo-6M GPS module to my Arduino Uno but am having some trouble getting GPS data out of it.
The code being used was taken from the TinyGPS library. I have set the SoftwareSerial ports in the constructor to 2 and 3 (check images at bottom for reference). I set to the boad rate of the software serial so that it matches that of the Neo-6M. The datasheet for the module can be found here.
The output that comes out of the Arduino serial monitor looks like this:

A new line is added to this every second, and when the line is added the TX light on the Arduino blinks. The 'Chars RX' 0 would indicate that the SoftwareSerial isn't reading any data at all from the module. I can't for the life of me figure out why this is happening! Any help would be much appreciated.
#include <SoftwareSerial.h>
#include <TinyGPS.h>

/* This sample code demonstrates the normal use of a TinyGPS object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/

TinyGPS gps;
SoftwareSerial ss(2, 3);

static void smartdelay(unsigned long ms);
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);

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

  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
  Serial.println("by Mikal Hart");
  Serial.println();
  Serial.println("Sats HDOP Latitude  Longitude  Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
  Serial.println("          (deg)     (deg)      Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
  Serial.println("-------------------------------------------------------------------------------------------------------------------------------------");

  ss.begin(9600);
}

void loop()
{
  float flat, flon;
  unsigned long age, date, time, chars = 0;
  unsigned short sentences = 0, failed = 0;
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
  gps.f_get_position(&flat, &flon, &age);
  print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);
  print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  print_date(gps);
  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);

  gps.stats(&chars, &sentences, &failed);
  print_int(chars, 0xFFFFFFFF, 6);
  print_int(sentences, 0xFFFFFFFF, 10);
  print_int(failed, 0xFFFFFFFF, 9);
  Serial.println();

  smartdelay(1000);
}

static void smartdelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void print_float(float val, float invalid, int len, int prec)
{
  if (val == invalid)
  {
    while (len-- > 1)
      Serial.print('*');
    Serial.print(' ');
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(' ');
  }
  smartdelay(0);
}

static void print_int(unsigned long val, unsigned long invalid, int len)
{
  char sz[32];
  if (val == invalid)
    strcpy(sz, "*******");
  else
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartdelay(0);
}

static void print_date(TinyGPS &gps)
{
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned long age;
  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  if (age == TinyGPS::GPS_INVALID_AGE)
    Serial.print("********** ******** ");
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
        month, day, year, hour, minute, second);
    Serial.print(sz);
  }
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  smartdelay(0);
}

static void print_str(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
  smartdelay(0);
}

Gray wire should be plug on pin2. SoftwareSerial ss(2, 3);  means pin2 for Receive(RX) and pin3 for Transmit(TX). The Transmit(TX) on Neo-6M should be connected to Receive(RX) on Arduino.


text:
FHT doesn't work with the example code
I'm trying to use the FHT librairy from (http://wiki.openmusiclabs.com/wiki/ArduinoFHT). I used the example code provided on the link, which is the following :
#include <FHT.h> // include the library

#define LIN_OUT8  1
#define FFT_N     64

void setup()
{
  /*Turn off timer0 for lower jitter -
    delay() and millis() killed*/
  TIMSK0 = 0;
  /*set the adc to free running mode*/
  ADCSRA = 0xe5;
  /*use adc0*/
  ADMUX = 0x40;
  /*turn off the digital input for adc0*/
  DIDR0 = 0x01;

  Serial.begin(115200);

}

void loop()
{
  while(1)
  { // reduces jitter
    cli();  // UDRE interrupt slows this way down on arduino1.0
    for (int i = 0 ; i < FHT_N ; i++)
    { // save 256 samples
      while(!(ADCSRA & 0x10)); // wait for adc to be ready
      ADCSRA = 0xf5; // restart adc
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int k = (j << 8) | m; // form into an int
      k -= 0x0200; // form into a signed int
      k <<= 6; // form into a 16b signed int
      fht_input[i] = k; // put real data into even bins
    }
    fht_window(); // window the data for better frequency response
    fht_reorder(); // reorder the data before doing the fft
    fht_run(); // process the data in the fft
    fht_mag_lin8(); // take the output of the fft
    sei();
    Serial.write(255);
    fht_lin_ou8[0];
    Serial.write(fht_lin_out8, FHT_N/2);
  }
}

But I get the following error:
fht_lin_ou8' was not declared in this scope
I canot resolve this probleme, ans help would be appreciate

There's three versions of the library on that site. I can't find that code you post in any of them.

Even the "program example" link is something different.

May be you should try to replace :

fht_lin_ou8[0];

with :
fht_lin_out8[0];


text:
Can I connect and control 12 Arduino's over USB/serial to my laptop?
I have 12 arduinos, each of them controlling some simple hardware peripherals. I want to interact with all of them over 1 USB connection to my laptop, where I have a python program communicating over serial.
The following seems like it could work: https://www.amazon.ca/Satechi-Power-Adapter-Control-Switches/dp/B0051PGX2I
Are there any electrical/other considerations to take into account for why this would/wouldn't work?

You want one program to handle 12 serial connections at the same time, as if it was one?

From a technical standpoint, USB can host up to 127 devices, so 12 Arduino boards is certainly not pushing the limit. Having 12 serial ports shouldn't be an issue in either Linux or Windows.
From a practical standpoint, you will have to find a powered USB hub which can support that many devices, or plug multiple hubs together. I'll leave that up to you as shopping recommendations are off topic.
In terms of the hub you use, you need to make sure you don't exceed its maximum current rating. The Arduino boards draw typically around 60-100mA alone. 12 of those and you will need at least 1.2A rating. The hub you mentioned says that it cannot exceed 2A. Depending on what other circuitry you attach to your Arduino boards you may need an external power supply for the boards.