text:
Arduino Raspberry Pi USB Communication
I am trying to connect an Arduino and Raspberry Pi over USB.  I would like to send serial commands, just like the serial monitor in the Arduino IDE.  I know how to do this on the Arduino end but I'm not sure how to send/receive serial communication on the Pi end.  Ideally the solution would utilize Python.

Welcome to Arduino SE! Sorry, this is not on topic because it's about the Pi. If you Google your question with the word "python," you will get several articles to show you where to go.

You will need PySerial to accomplish this. A tutorial on interfacing Arduino and the RPi using a usb can be found here

linking to offsite resources as the meat of your answer is not useful in the longterm, please update your answer to include more information.

You would be better to ask this on http://raspberrypi.stackexchange.com
You can use program minicom on the Pi; this is a terminal program like the serial monitor in the Arduino IDE, and of course you can use Arduino IDE on the Pi.
If you look at the Pi site you will see lots of Python serial communication programs.

There's nothing particularly "pi" about this - it's rather a generic linux/unix question.

Why do you want to use the USB port on the Pi? Isn't it easier to connect the Arduino directly to the UART pins (Pins 8 and 10) on the PI and then read out the UART in your python programme?

this would be more appropriate as a comment. You are not answering the question. There could be lots of reasons to use a direct usb connection or the OP might not know that they can do what you propose, either way though the question they asked is about connecting via usb.

Do realize that it's the same serial software API either way?  While it's true that the USB serial imposes an additional latency, it's wise to design communication schemes that can tolerate that, because more often than not today one will be involved.  Regardless, you haven't answered how to implement either the original question or your own proposal - which is ironic as an answer to either would be an answer to both.

Why are you guys getting so upset with my comment? All I tried was to help. What I have written may technically, according to your orthodoxy, not be an "answer", i.e. providing a complete and final solution for the USB connection. However, I suggest an alternative solution to the original problem, i.e. sending serial commands.

The reason I want to use USB rather than the GPIO on the Raspberry Pi is that 1) The Arduino will be powered over USB, so less wires to run (the Arduino and Pi will not be immediately next to each other) 2) It is a neater solution 3) Latency is not an issue, and 4) The Pi is a 3.3V device while Arduino is 5V.  For now, signals only go Pi>Arduino, which should work, but I want the option to go Arduino>Pi without level shifting.


text:
Can I use micros() to analyze TX23 anemometer signal?
I'm very new to Arduino, and I'm trying to read data from a LaCrosse TX23 V02(X) anemometer. It's supposed to behave like this https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/, but it's not...
I don't have an oscilloscope, so I made this code, using micros() to try to trace the output from the TX23:
void loop() {
  collectData();
}

int collectData(void){
   if (bitLength < 0){
      bitLength = 1200;// length of bit is equal to approx 1230 micro seconds;
   }
  // init sequence
  pinMode(dataPin, OUTPUT);
  Serial.print("Send LOW\n");
  digitalWrite(dataPin, LOW );
  Serial.print("Send HIGH\n");
  digitalWrite(dataPin, HIGH);
  delay(100);
  Serial.print("Send LOW\n");
  digitalWrite(dataPin, LOW );
  delay(500);

  Serial.print("Begin input mode\n");
  pinMode(dataPin, INPUT);

  int state = 0;
  int oldstate = 0;
  unsigned long oldmicros = micros();
  for (int i = 1; i<5250 ; i++) {
    state = (digitalRead(dataPin) == LOW)? 0:1;
    if (i%10 != 0) {
      Serial.print("-");
    } else {
      Serial.print("+");
    }

    delayMicroseconds(10);
    if (state != oldstate) {
      oldstate = state;
      i = 1;
      Serial.print(oldstate);
      Serial.print(" @");
      Serial.print(micros() - oldmicros);
      oldmicros = micros();
      Serial.print("\n");
    }
  }
  Serial.print(state);
  Serial.println(micros()-oldmicros);
}

Does it have a chance to provide a quite accurate monitoring of the TX23 output? (eg is using micros() or delayMicroseconds(10) accurate ?)

You should really make use of pulseIn() to work out the bit rate of the signal.  The first HIGH pulse in the header is there for timing so you know how often to poll the input.
Step one, after sending your outgoing initiation pulse, should be to wait for that first pulse (you might need a slight delay first before it starts transmitting - wait for the line to be low first):
while (digitalRead(dataPin) == HIGH); // Wait for TX start
uint32_t pulseWidth = pulseIn(dataPin, HIGH); // Get first pulse

That gives you the width of the first pulse in microseconds.
Now you can read 45 times at that period.  If you first delay by half that amount before your first sample you will be roughly in the middle of the bit so you can cope with a slight amount of drift.
// Wait for the middle of the first bit
delayMicroseconds(pulseWidth / 2);

uint32_t highBlock = 0;
uint32_t lowBlock = 0;
for (int i = 0; i < 45; i++) {
    // Shift the high 32-bits left one bit
    highBlock <<= 1;
    // Place in the highest bit of the low block as the lowest
    // bit of the high block
    highBlock |= (lowBlock & 0x80000000UL ? 1 : 0);
    // Shift the low 32-bits left one bit
    lowBlock <<= 1;
    // Add in the value of the bit from the data pin
    lowBlock |= digitalRead(dataPin);
    // Wait for the next bit
    delayMicroseconds(pulseWidth);
}

You should now have two 32-bit words which, when put together, form the entire datagram.  You can now use bitwise operators to pull out the parts you are interested in.
A better, though more complex, method of doing it would be to employ a timer with an overflow period equal to the pulse width. That will afford you much more accurate timing than a simple loop with delays.

Thanks a lot for the input. It does not exactly answer my initial question, but it certainly helps me solve my problem reading the TX23 output ! It works, but I don't understand the first 'while (digitalRead(dataPin) == HIGH);' and the data I get with pulseIn() are the first two bits of the header, not an initial pulse...

Marking this as right answer as it helped me resolve my real problem, but other two contributions were really helpful as well. Thanks to
jwpat7 and Nick Grammon.

I'm going to present a third way of working on this. :)
First, since I don't have a TX23 I wrote a TX23-simulator:
const byte TESTPIN = 2;

const byte test [6] = {
    0b00000011,
    0b01111011,
    0b01010100,
    0b00010100,
    0b01001010,
    0b10111111 };

void setup ()
  {
  pinMode (TESTPIN, INPUT);
  delay (100);
  }  // end of setup

void loop ()
  {
  // wait for host to pull pin low
  while (digitalRead (TESTPIN) == HIGH)
    { }
  // wait for host to release it
  while (digitalRead (TESTPIN) == LOW)
    { }
  digitalWrite (TESTPIN, HIGH);
  pinMode (TESTPIN, OUTPUT);
  for (byte i = 0; i < 6; i++)
    for (byte j = 0; j < 8; j++)
      {
      delayMicroseconds (1100);
      digitalWrite (TESTPIN, test [i] & bit (7 - j));
      }
  pinMode (TESTPIN, INPUT);
  }  // end of loop

Based on your linked page about the TX23 it outputs a series of low/high pulses corresponding to the example on that page, like this:

Note that you need a 10 k pull-up resistor for this to work properly.

Now the reading code uses interrupts to detect state changes:
const byte READ_PIN = 2;
const byte NUMBER_OF_CHANGES = 48;

volatile unsigned long bitTime [NUMBER_OF_CHANGES];
volatile byte state [NUMBER_OF_CHANGES];
volatile byte count;

void stateChange ()
  {
  unsigned long now = micros ();
  if (count >= NUMBER_OF_CHANGES)
    return;  // array full
  state [count] = digitalRead (READ_PIN);
  bitTime [count++] = now;
  } // end of stateChange

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  }  // end of setup

void takeReading ()
  {
  count = 0;
  digitalWrite (READ_PIN, LOW);  // start reading
  pinMode (READ_PIN, OUTPUT);
  delay (20);  // pulse width
  pinMode (READ_PIN, INPUT);     // release line
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  attachInterrupt (0, stateChange, CHANGE);
  delay (55);  // let readings fill up array
  detachInterrupt (0);
  }  // end of takeReading

void loop ()
  {
  takeReading ();
  if (count == 0)
    return;  // nothing!

  delay (500);
  for (byte i = 0; i < count; i++)
    {
    Serial.print ("count: ");
    Serial.print ((int) i);
    Serial.print (" = ");
    Serial.print (bitTime [i]);
    Serial.print (", state = ");
    Serial.print (state [i]);
    if (i > 0)
      {
      Serial.print (", width = ");
      unsigned long width = bitTime [i] - bitTime [i - 1];
      Serial.print (width);
      Serial.print (" (");
      int bits = width / 1000;
      for (byte k = 0; k < bits; k++)
       Serial.print (state [i - 1]);
      Serial.print (")");
      }
    Serial.println ();
    }
    Serial.println ();
  }  // end of loop

Results were:
count: 0 = 10952804, state = 1
count: 1 = 10953928, state = 0, width = 1124 (1)
count: 2 = 10960616, state = 1, width = 6688 (000000)
count: 3 = 10962844, state = 0, width = 2228 (11)
count: 4 = 10963960, state = 1, width = 1116 (0)
count: 5 = 10968412, state = 0, width = 4452 (1111)
count: 6 = 10969524, state = 1, width = 1112 (0)
count: 7 = 10971752, state = 0, width = 2228 (11)
count: 8 = 10972876, state = 1, width = 1124 (0)
count: 9 = 10973988, state = 0, width = 1112 (1)
count: 10 = 10975104, state = 1, width = 1116 (0)
count: 11 = 10976216, state = 0, width = 1112 (1)
count: 12 = 10977328, state = 1, width = 1112 (0)
count: 13 = 10978440, state = 0, width = 1112 (1)
count: 14 = 10984012, state = 1, width = 5572 (00000)
count: 15 = 10985124, state = 0, width = 1112 (1)
count: 16 = 10986244, state = 1, width = 1120 (0)
count: 17 = 10987356, state = 0, width = 1112 (1)
count: 18 = 10990700, state = 1, width = 3344 (000)
count: 19 = 10991812, state = 0, width = 1112 (1)
count: 20 = 10994040, state = 1, width = 2228 (00)
count: 21 = 10995156, state = 0, width = 1116 (1)
count: 22 = 10996268, state = 1, width = 1112 (0)
count: 23 = 10997380, state = 0, width = 1112 (1)
count: 24 = 10998500, state = 1, width = 1120 (0)
count: 25 = 10999616, state = 0, width = 1116 (1)
count: 26 = 11000728, state = 1, width = 1112 (0)

This seems to agree with the test data.

Thanks for this, it really helps me progress and opens other possibilities to me.

Majenko showed a method for digitally recording the waveform, after measuring pulseWidth at the outset, and mentioned use of a timer for delays.   I'll address the part of your question about using micros() while tracing TX23 output:  “Does it have a chance to provide a quite accurate monitoring of the TX23 output?”
Some of the serial output that your method produces as it goes along will affect evenness of timing.  For example, the Serial.print() of + after every tenth reading introduces a small timing irregularity (the two branches of the if may differ a few cycles in execution time).
More seriously, your double-read of micros() (after you print oldstate, you print micros() - oldmicros and then read micros() again) introduces a few cycles of timing error.  It probably amounts to a few microseconds total over the course of recording the pulse train.  Instead of reading micros() twice, say something like newmicros = micros() directly after detecting a state change, before doing any serial printing, then use newmicros in place of other micros() calls.  Having serial prints before oldmicros = micros(); causes an offset error, which will be microseconds or milliseconds depending on the data rate you set in setup().  It mostly affects the reported length only of the first pulse.
What I would do for debug monitoring of the pulse train is along the following lines:
enum { timelen=44, maxpause=50000 };
unsigned long int times[timelen];

int collectData() {
  byte ntimes = 0, state=LOW;
  unsigned long int prevtime;
  pinMode(dataPin, OUTPUT);
  digitalWrite(dataPin, LOW ); // Pull DTR low to trigger conversion
  delay(500);
  pinMode(dataPin, INPUT_PULLUP); // Release DTR and set pullup
  delay(1);           // Let TX23U pull DTR low
  prevtime = micros();
  while (micros() - prevtime < maxpause && ntimes < timelen) {
    if (digitalRead(dataPin) != state) {
      times[ntimes++] = prevtime = micros();
      state = 1-state;
    }
  }
  return ntimes;
}

This code is intended to record times at which state changes occur.  After loop() calls collectData(), it can call a reportData() routine that will print out pulse lengths by subtracting adjacent entries of times[].  Even-indexed array entries are times of rising edges in the pulse train; odd-indexed entries are times of falling edges.  Because the if (digitalRead(dataPin) != state) {...} statement isn't executed atomically, the data pin can change after being tested but before being recorded a couple of lines later.  Using state = 1-state; instead of state = digitalRead(dataPin); guarantees that even indexes are for rising edges, but does not guarantee that adjacent entries correspond to the same pulse edge.  That is, a noisy signal can produce misleading results.

source: Stack Exchange

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

sort: votes


text:
Long range wireless communication between two arduinos?
I'm working on a project that will require two arduinos to be able to relay information to each other from long distances (up to about 10 miles or around 16 km).  WiFi won't be guaranteed to be available to either arduino as this is a wilderness application.
What are my options for long range wireless communication?  I haven't decided on an arduino model yet so if one particular model would be best for this application let me know.

Lower frequencies tend to have larger ranges. I'd also suggest looking into DIY directional antennas.

Your range of options depends strongly on what your budget is, what country you are in, whether you are a licensed radio operator, whether cell service is available, etc.
If you aren't licensed:
In the USA, unlicensed (or lightly licensed) radio options include GMRS (General Mobile Radio Service), FRS (Family Radio Service) and CB (Citizens band radio).  GMRS and FRS range typically is at most a few miles – ten miles is too much to hope for.  CB range would be ok but CB radios often are fairly large and antennas would be large, eg nine feet long.  I don't know whether it is legal to transmit digital data over GMRS/FRS/CB radio.
If you are licensed:
2-meter band radio might be a good choice.  Frequencies are 144 MHz to 148 MHz in the Americas and Asia, or 144 MHz to 146 MHz elsewhere.  Per wikipedia,

The license privileges of amateur radio operators include the use of frequencies within this band  for telecommunication, usually conducted locally within a range of about 100 miles (160 km).

If cell service is available:
Consider a GSM shield, eg the Arduino GSM Shield.
To access the cell network you would need to buy a SIM card for each GSM shield.
GPRS (General Packet Radio Service) on GSM provides data rates between 10 and 240 kbs.  Other GSM protocols may be faster or slower.  Data rates depend also on whether 3G service is available or only 2G.

Do you know any CB shields? Any approach you could recommend to me? I have two old President CB radios. I could manually connect to the input and output audio (i.e. mic and speaker) and build something. Are there any ready to use devices to convert digital sounds to useful binary data?

@Socrates, I don't have any info about interfacing to CB radios.  Re "digital sounds to useful binary data", that's the function of an audio modem; modem chips probably are available, but also see (eg) SoftModem on github

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

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


text:
LCD showing weird characters when using two 1-wire temperature sensors
I have a sketch to display a temperature obtained from 1-wire DS18B20 sensors. The sketch works fine, however when I connect two sensors to my board, the text on the LCD displays gets corrupted (### and other symbols shown instead of a temperature).
I have tried plugging each of the two DS18B20 sensors individually and it works with both of them, the problem shows only when I use both at the same time. I am connecting them both with black to ground, red to 5V and white to Dx and to 5V via a 4.7 kOhm pull-up resistor.
I have little idea how to check what is wrong - is it some kind of interference, insufficient voltage, or a SW problem?

After some more searching I have found Arduino forum topic LCD text corrupts after Arduino runs for length of time. I have followed this advice:

In particular, try running the LCD ground wire directly to a ground pin on the Arduino (not to the breadboard) and keep it short.

This seemed to solve the issue, therefore it was likely some kind of interference on the ground wiring. (Before this, the ground to the LCD went trought the breadboard power bus).


text:
USB device not recognised - windows 8.1
I'm a beginner with Arduino and i have acquired the Arduino UNO R3 board. i have followed the instructions on arduino website in order to install the board, however it fails and still remains as an unrecognised device.
consequently, arduino IDE reports that COM1 is not found, and the 'ports' menu is grayed out.
steps i have tried:
1) install the Arduino 1.0.5 IDE
- the installation failes near the end when installing the arduino board
2) install the Arduino 1.5.7 BETA IDE
- the installation is successful but arduino device is still unrecognized.
3) i have tried manually installing the drivers by letting windows search in the arduino IDE installation folder/drivers/
- it reports that the best driver is already installed - "usb unrecognized device"
4) i have tried installing the drivers by manulally loading the .inf files from the IDE installation folders, and installing all the serial converter A/B/C/D in the list - all failed to install.
i have done all the above for both IDE 1.0.5 and 1.5.7b with windows installer And zipped files, under administrative rights in windows 8.1
How do i get this to work?

Is your board connected to COM1?

well thing is, i connect to this board via USB and i honestly dont know what 'port1' is. the windows device manager does not recognize and is unable to install the arduino driver, thus unable to create any ports for it

Ah, well then. Does it show up as an unknown device in device manager?

yep, it does indeed

You said you loaded the .inf files, the guide mentions to just load up Arduino UNO.inf. I'm guessing you tried that?

yes, the arduino.inf file according to the device manager, does not contain any relevant information. i have oppened the file and it does indeed contain what i need, but device manager says it doesnt

After a quick google, would this help? link

Is this an official board? If so, you might have to contact Arduino and ask for a replacement. Other than that: another computer, another USB cable, make sure the right COM port/board is selected...

i am going to disable driver sign check as per doowy advice, and i will try it on a different pc too. how do i know if the board is official?

nothing worked, i guess my board is just faulty. thanks for the help guys

I have solved my issue. its funny, since i have got a new genuine kit, but the usb cable was faulty. i changed to some other usb cable i had laying around, and it worked perfectly...

Maybe you typed something in wrong somewhere; your Shift key appears to be having problems.

@TheGuywithTheHat if you are referring to the inconsistency in capitalization, dont mind it. i never care about correct capitalization. and no, i am pretty sure it was the cable. i never make case-sensitive mistakes where it matters.

The issue was resolved by changing my USB cable. the cable in the kit was new and seemed to supply power to the arduino board, but windows was unable to identify the board using that cable. maybe the data wires were damaged.
 in any case, i changed the cable and everything worked smoothly.

Right click on devices list from Manager
update driver and choose the folder with name "driver" in your arduino IDE app that you use
Ok
and the card ll be recognized
good luck

To solve this problem.
1. connect your Arduino board to the PC / Laptop.
2. open control panel. and go to view devices and printers
3. Here You can see a unknown device... i.e. your arduino board. double click on it.

4 Click on hardware..................................................

5. Now Choose Update Driver... Choose the location where the Arduino IDE is installed... And go to Next
6. Now your computer will recognise your arduino board


text:
Nested For Loop
I'm not sure if I'm being really really stupid, but why doesn't this work?
void setup() {
  Serial.begin(9600);
}

void loop() {
  for (int x; x < 8; x++) {
    for (int y; y < 8; y++) {
      Serial.print(x);
      Serial.println(y);
      delay(100);
    }
  }
}

When this does:
void setup() {
  Serial.begin(9600);
}

void loop() {
  for (int x; x < 8; x++) {
    Serial.println(x);
    delay(100);
  }
}

The first produces no output over Serial, whereas the second one prints out the numbers 0 to 7 as expected. I'm using a Teensy 3.1.

Very odd... doesn't work for me on Mega 2560. I must be missing something obvious :-)

yes, obvious: int x = 0; inside for() statements (same for y by the way)...

How we can solve question 18 ?

You are not initializing x and y.
When a local variable isn't initialized, it will "inherit" the value contained in the register assigned to the variable by the compiler. The fact that your single loop example worked is pure luck - the assigned register happened to contain 0 at that point in execution.
Change your nested loop like this:
for (int x = 0; x < 8; x++) {
  for (int y = 0; y < 8; y++) {
    Serial.print(x);
    Serial.println(y);
    delay(100);
  }
}

And it will work.
Note: Global variables, on the other hand, are guaranteed by the c++ standard to be initialized to zero. The compiler will make sure to write zeros to those memory addresses before the main program code executes.

I've spent too long writing Ruby...


text:
SD datalogger sometimes skips readings
I'm using the Adafruit SD shield with a Mega board and wrote a simple program to log data.  I am outputting a constant stream of data at 115200 baudrate from another Arduino to the Mega.  The data output is mostly good, but there are places where some data are skipped.  These skipped data usually occurs around a file flush.  I've tried playing around with the flush frequency and the soft buffer size, but to no avail.  I'm not sure what these hiccups are caused by and would like some help.
void loop(void)
{
  while (Serial1.available())
  {
    softBuffer[i] = Serial1.read();
    i++;
  }

  if (i >= SOFT_BUFFER_SIZE)
  {
    for (x = 0; x < SOFT_BUFFER_SIZE; x++)
    {
      logfile.print(softBuffer[x]);
    }

    logfile.flush();

    i = 0;
  }
}

The amount of time an SD card can take to actually commit data is relatively unbounded.  If your buffer cannot handle the data delivered for a fair fraction of a second, you may have problems with some cards.  How much data is delivered in a second?  115200 baud can potentially bring as much as 11520 bytes, while a Mega 2560 only has 8192 bytes of RAM in total.

But if you are not up against that limit, you could still be against another based on the architecture of your code.  A different scheme would use two buffers, one being filled directly by the serial interrupt (no Arduino Serial class), while the other is flushed to the card, then swap.  Or use a non-blocking SD library which can do other things while periodically polling the card to see if it is done.

@ChrisStratton I don't really understand the dual buffer suggestion.  With two buffers, aren't they still printing and flushing to the same file?  or do you mean doing something like alternating between logfile1.print and logfile2.print?

I mean continuing to fill one buffer while waiting for the SD card to flush the other, presumably to a single file.  Your current code does not appear to be able to continue accept new data while it is waiting for the card to finish flushing old data.  But depending on your data rate, you may not have enough memory on board to cover for the longest possible card delay anyway.

@ChrisStratton IIRC the Arduino internal serial buffer is only 16 bytes long, increasing that might be an elegant solution.

Correction, 64 bytes if RAMEND > 1000.. I don't know what RAMEND is though. https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp

Probably not as that would lead to double buffering  - it would be better to skip the serial class entirely and receive durectly to one of the ping-pong card buffers.  Or else write to the card directly from the serial buffer.  This is a case where if you want nice abstraction, you need a system with more buffer memory.

The SD card library works by filling up a 512 byte buffer. Once full, the data is written to disk.
The flush command updates the directory listing with the correct size for the file and also updates the file allocation table. It only needs to be done once, just before you pull the card out.
While flush is doing its thing, the internal serial buffer of the Arduino is filling up with new bytes. The internal buffer is 64 bytes long so if flush takes too long, the internal buffer fills up and you lose characters. You could edit HardwareSerial.cpp in the Arduino program directory to make it say 256 bytes.
Because of this softBuffer is not needed. Simply write straight to the card and let the internal buffer handle the buffering. See https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp for the Serial code.
unsigned long bytesWritten = 0;
void loop(void)
{
  while (Serial1.available())
  {
    logfile.write(Serial1.read());
    bytesWritten++;
    if(bytesWritten > BYTES_PER_FLUSH) logfile.flush();
  }
}

I tried that, but data is still being skipped.  I think I might have to try a different SD card library.  Is using a baud rate of 115200 testing the limits of the Mega?

@user2218339 What did you change the buffer in HardwareSerial.cpp to? It is not really the baud rate, but how much data is being transmitted

Sorry, I must have read too fast, I didn't see the part where you suggested to change the hardware buffer size. I will give it a try today.

I got a chance to try it out, and that was definitely the solution!  Thanks geometrikal!

@user2218339 glad it worked - i learnt something too!


text:
How do I specify a working directory when saving to SD card?
I'm trying to datalog to a EyeFi SD card by writing to a file with a jpg extension. Here's that portion of my code so far:
// see if the directory exists, create it if not.
if( !SD.exists("/DCIM/100NIKON") )
{
  if( SD.mkdir("/DCIM/100NIKON") )
  {
    Serial.print("File directory created: ");
  }
  else {
    error("File directory not created");
  }
}
else
{
  Serial.print("File directory exists: ");
}

// Test file
char filename[] = "DSCN0000.JPG";

if (! SD.exists(filename))
{
  logfile = SD.open(filename, FILE_WRITE); // only open a new file if it doesn't exist
}

if (! logfile)
{
  error("Couldnt create file");
}

The Arduino creates the directory, but the file is still saved to the root.  I would love some help or tips on this.

You're creating a directory, and then not writing the file into it.
You need to change the filename to /DCIM/100NIKON/DSCN0000.JPG";
Note that SD.open() takes the full filepath to the file, not just the file*name*.
From the Arduino Docs:

The file names passed to the SD library functions can include paths
  separated by forward-slashes, /, e.g. "directory/filename.txt".
  Because the working directory is always the root of the SD card, a
  name refers to the same file whether or not it includes a leading
  slash (e.g. "/file.txt" is equivalent to "file.txt"). As of version
  1.0, the library supports opening multiple files.

(emphasis mine)

Oooh, I was thinking that after creating a directory with mkdir, the directory will automatically become the working directory.  Thanks a lot!

@user2218339 - Nope, and as far as I can tell, there isn't even a way to change the working directory at all. It's basically hard-wired to /.


text:
SIM 900 + Arduino Mega attachGPRS problem, GPRS_READY
I have connected my GSM module to my Arduino. Using AT commands I am able to connect to internet.
  Using the following link of tutorials, I tried to connect to internet
http://arduino.cc/en/Tutorial/GSMExamplesXivelyClient
  In this the device is showing not connected. So I tried to debug it. In the attachGPRS
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY)
gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD = 2
and GPRS_READY = 4
Why is this happening? What is GPRS_READY ?

Your question doesn't make sense. I know english isn't you first language, but please try to rephrase it. The code you provide is also weird, with for example missing parentheses.

Welcome to Arduino SE! First of all, did you solve your other question yet? Also, it seems like you're relying on external code. Can you please add any relevant code? Thanks!


text:
What makes a board "Arduino Compatible"?
There are all sorts of Arduino and Arduino-compatible boards out there. They come in all form factors and they come with all sorts of different I/O. They even come with memory specs and different kinds of microcontrollers, from the ATmega328P to Intel-based.
So what is it that imbues a board to become "Arduino Compatible" ? Must it be pin-compatible? Must it be possible to compile Arduino source code for the board? Or must the board be binary-compatible? Must it emulate some specific processor instruction set?
Very curious. Please reference specifications if possible. Thank you.

Related: What does “Arduino compatible” mean?

The problem here is that "compatible" can mean so many things in different contexts and to different people.  For instance, it may mean any of the following:

Can be used with the Arduino IDE without any need for additional board installation of other modifications
Can be used with the Arduino IDE after modification (boards installed)
Uses the same (or very similar) API to the Arduino system
Has the same footprint as an existing official Arduino board
Is a device which will work with an Arduino board and has software available to operate it

All very different meanings.
Point 1 could be a board that is based on the design of an existing Arduino board (say the Uno) but built into a new form factor, maybe with additional hardware and peripherals added.  It is still treated as if it was the board the design was based on though.
Point 2 would be a board that is similar, though not the same, as an existing board.  A different board definition may be required to map the IO pins properly, for instance.  It could use a slightly different chip in the same supported family. You still use it as an Arduino, but it's not the same as an existing Arduino board.
Point 3 may mean it's based on a completely different chip.  The programming environment may be almost the same, but it's hard to get 100% API compatibility.  Arduino sketches and libraries may work out of the box, or may not.
Point 4 could be a board that, internally, is completely different to the Arduino, uses a different programming language, IDE, etc, yet the layout of the board is the same as, say, an Arduino Uno.  A good example is the Mecanique Firewing - an Uno footprint, but a PIC32 chip instead of an Atmel, and Basic instead of C++.  Most Arduino shields would just plug in and work though, software permitting.
Point 5 is from the completely opposite direction.  This is a device which "is compatible with" in that "it will work with" and Arduino.  That could be on an electrical level (it's a 5V device and will connect to the Arduino) or that it has full software support ("Download our Arduino library...").  It has nothing to do with how the device works or what it is though.
I prefer to use specific terms, respectively:

Based on the Ardino UNO
Programmable with the Arduino IDE
Compatible with the Arduino API
Footprint compatible with the Arduino UNO
Suitable for use with Arduino boards

That way it states exactly in what way this device relates to the official Arduino boards.

I think you could say it is Arduino-compatible if it contains a processor found on an Arduino board. For example:

The Atmega328P (found on the Uno, Duemilanove, Pro Mini, amongst others)
The Atmega32U4 (found on the Leonardo, Micro, amongst others)
The Atmega2560 (found on the Mega2560)
Other processors used by Arduinos such as the Atmel SAM3X8E ARM Cortex-M3 CPU used on the Arduino Due.

With a processor used on an Arduino, you will find that you can almost certainly compile code using the Arduino IDE, and the Arduino libraries, that will work on such chips.

You could say it is Arduino-Uno-compatible if the board physically was compatible with the Arduino Uno (ditto for other boards). In other words, if it was possible to plug a shield, designed for the Uno, onto such a board. That could be called "plug compatible" I suppose.

As for other boards, like sensors, relay boards, etc., I have seen a lot of those on eBay advertised as "Arduino compatible", but of course they would also be compatible with other micro-controllers as well. I'm waiting for the day someone advertises "Arduino compatible" resistors.

I think the practical answer is: it is not defined.
In practice:
For peripherals, it seems to mean that it can interact with an Arduino compatible board.
For boards, as far as I can tell, it has to be: instruction-set compatible, OR pin (layout) compatible with another board which was previously defined as Arduino compatible.


text:
Enabling keyboard feature on Arduino with CH340G
I've seen here that it is possible to enable keyboard feature on Arduino Uno so it can emulate a keyboard (send keystrokes to computer) like the Leonardo. They do it by updating ATmega16U2 firmware. But I bought a cheap arduino clone that uses CH340G instead of this chip. Is there any way to do the same with this chip? Can this even work on standard arduino uno?

Maybe you can find/write a c/c++ program for the PC that reads a COM port and sends it as keystrokes. The hardware is pretty much fixed in your project. Unless you use an Arduino with 32uX aa a serial/USB interface chip.

No. That chip can only act as a USB-UART bridge. You could use V-USB to turn the ATmega328P into a low-speed USB device, but the Arduino IDE has no support for that.


text:
Purpose of extra holes for pins or Arduino clone
I bought this Arduino clone recently and it has lot of extra holes for pins, but some of them I don't know what they do. There was no instruction manual that came with it. Here's a picture of it, I added a red rectangle around the ones I don't know. (4 pins with X1, SCL/SDA, AREF and blank pin in the bottom)

I thought I could use the pins SCL SDA 5V GND with my I2C LCD Display because the names of the pins are the same on it. Could it work? Usually I use analog pins to connect the display, does that mean that by using it some analog pins will be used indirectly? I didn't try connecting it because I don't want it to break.

What do these pins do?

I bought this one

I'v had the same question and searched for a manual... And where is the manual?

For the Arduino clone? Should be the same as standard Arduinos.

It's what they say they are.
SDA/SCL are I2C - what used to be A4/A5 on the old footprint. On the '328 based boards those are directly linked to the A4/A5 pins.
The blank pin isn't used. The 5V next to it is actually mislabelled and should be labelled "IOREF".
AREF has been there since the very first Arduino boards.
It's the standard "R3" Uno footprint, plus some extra breakouts for the I2C in different forms (probably to go with specific I2C devices they also sell).
All of that is on the Uno's product page if you'd care to read it some time...
The ones by the cheap Chinese USB interface chip will be something to do with that. Maybe RTS/CTS broken out on a header. You can ignore those - they are of no interest at all. In fact, just looking in their direction has a good chance of breaking the USB interface chip. Stay well away.

Does IOREF sets the voltage on I/O pins?

IOREF tells a shield what voltage the main board runs at.

It's all in the manual. I seriously suggest you read it. At the moment you're just making a fool of yourself asking such basic questions.

Would that make you happy?

If you were happy?


text:
Error saying an included library is not
The IDE tells me the included library isn't? I tried restarting the IDE and my computer but it doesn't work. The other libraries work fine it's only with Keyboard that it fails.
My code:
#include <Keyboard.h>

int buttonState = 0;

void setup() {
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);

  Keyboard.begin();
}

void loop() {
  buttonState = digitalRead(2);
  if (buttonState == HIGH) {
    digitalWrite(13, HIGH);
    Keyboard.press('A');
  } else {
    digitalWrite(13, LOW);
    Keyboard.releaseAll();
  }
}

Error log:
Arduino: 1.6.8 (Windows 10), Board: "Arduino/Genuino Uno"

D:\Documents\Test\Test.ino: In function 'void setup()':

Test:9: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
   Keyboard.begin();

   ^

D:\Documents\Test\Test.ino: In function 'void loop()':

Test:16: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
 Keyboard.press('A');

 ^

Test:19: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
     Keyboard.releaseAll();

     ^

exit status 1
'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?

I see you are using an Arduino Uno.
An Arduino Uno cannot act as a USB keyboard - therefore the Keyboard library doesn't exist for it (the file Keyboard.h is seen as being empty).
You can only use Keyboard.h on boards where using Keyboard.h makes any kind of sense, such as the Leonardo.

Ok thanks. Should I delete the question because that seems obvious now?

@Atom: Did you find any other questions asking same?

@IgnacioVazquez-Abrams If he'd looked I'm sure he would have done. I know for a fact that I have answered the same question before.

No but I think they say it here https://www.arduino.cc/en/Reference/MouseKeyboard, it just isnt clear


text:
Arduino Grounding Issue
I have a project that turns a LED strip on and off using capacitive touch.  The project uses an Arduino Micro as the brain and a 12v wall wart to power everything.  I have the Arduino ground and negative from the power supply running to a common ground.
Everything works as expected during testing and the Arduino is connected via USB to my computer; however, when I unplug the USB and connect the circuit to the light installation, the lights just flicker on and off.  When I touch my finger to the negative/ground (and presumably provide common ground), everything works as expected.
It seems obvious to me that I have a grounding issue, but really do not know how to proceed. Is there a specific technique for grounding from a wall wart? Do I need to somehow pull the ground/negative down? I feel like there is something obvious that I am missing.
Thank you in advance for any and all help.

Seems like there is a problem in your wall wart, actually some people are having problems using wall wart with arduino. The problem is with the circuit of thre arduino regulator and with sime ripple variances with de wall wart, i sugest you to setup in your project a regulator (7805) and see if the problem is gone. This is by far problem not just with grounding, but with the power suply in general. I was used to make PIC projects and once it was happening exatly the same that happaned to you but the microcontroller started to work when i put my hand or finger close without even touching it :x. Crazy thing. If the power supply isn't well suited, the arduino enter in continous reset looping because of supply noise. So just put an external regulator, an maybe an extra capacitor (generally 10 nF) in arduino micro power supply rais (VCC-GND). Here's my tip. Good look man, tell me if it worked :)

Yes, I agree with this and had exactly the same problem when migrating Arduino projects to PIC! If you're using a strip of Neopixels, there will be a lot of noise generated on the power rails, so use plenty of bypass capacitors and an LDO like @Matheus sugests.

Here's an article describing how you can configure the simple regulator circuit: http://jumptuck.com/2011/11/15/voltage-regulation-friend-7805/


text:
Which Microcontroller to use
I want to use a wifi shield, as well as a 2.8 inch touch LCD shield; both would fit the arduino uno V3 nicely.  Is that the best microcontroller to use

That isn't a mocrocontroller, it's a development platform.

Without any further comments on what you intend to do with it, it is impossible to say what is "the best" for your situation. Please provide more details about your project.

There are Uno Wifi shields and there are Uno LCD shields; do you ask whether you can stack both of them on top of the Uno simultaneously ?

yes, can I stack them simultaneously. @Omer

I meant which arduino microcontroller would be best to use? @Ignacio Vazquez-Abrams

I want to be able to scan for existing networks, and then go from there. @ jfpoilpret

I was wondering if the mega 2560 would work better? @Ignacio Vazquez-Abrams

@BMode35 - The main difference with the mega is that it has more pins for input and output. So you can control more external motors, switches etc.

If you want to do wifi and a GUI, you probably shouldn't be using an Arduino (or at least not an ATmega-based one) at all.  Get something with more memory - it won't cost more, in fact it will probably cost less.

To answer your first question, regarding stacking a WiFi Arduino Shield on top of a LCD Shield:

can I stack them simultaneously

The obvious answer is - it depends on the shields. Each shield might use a different set of Arduino I/O pins, making them unavailable to the next shield stacked on top of it.
for example, this formal Arduino WiFi shield makes I/O pins 10, 11, 12, 13 and 7 (on Arduino Uno) unavailable to the next top shield.
Unfortunately, this LCD KeyPad shield needs pins 7 and 10 available (among others) in order to function properly. This makes it incompatible for stacking on top of the WiFi shield mentioned above (or vice versa).
It doesn't mean that there is no way that any LCD shield could be stacked on top of a WiFi shield, but to be honest, I couldn't easily find any LCD shield that won't collide with a WiFI shield pins. You might want to change approach and send the WiFi data using the built-in Serial to a computer.

Is that the best microcontroller to use

If there would have been a manifest to this website, I'm sure that "The best product is the one that meet your needs best" would be it's first sentence. In order for someone with experience to answer what is best, (s)he would need to know your exact needs. Since you are still not sure what they are, and just want to play around a bit, I imagine that the classic Arduino Uno R3 could help you find your way, especially if you are doing your first steps with Arduino.

I'll have to chime in with the others and say "It depends." The Uno, or more precisely its Atmega328p microcontroller, is rather memory limited, especially the RAM memory needed for data buffers, stack-frames, and tables such as the character-generator for the LCD. That last one can usually be kept in program memory, but note that if you're having to plan memory assignment before you even start the project, it's a pretty good sign that you should consider something more capable.
An Arduino Mega 2560 is about twice the price of the Uno (in the US, US$50 vs. US$25) but gives you 4 times the RAM memory, 8 times the flash (program) memory, and a bunch more (sorry to get all technical :) I/O pins. Of these, the RAM is likely to be your most stringent limit with the UNO.
I keep one Arduino Mega around for prototyping or when don't want to build another board for an experiment, and a handful of AtMega328p chips to build into "Arduin-ettes" for my more permanent gadgets. Most of my toys will fit on the '328 chip but it's awfully nice to be able to shove a ton of code, libraries, debugging statements, logging buffers and what have you, into the larger processor without having to think about what will fit. Or, what's worse, if I cause a stack crash by stuffing all of that into too-little memory, I could waste a lot of time debugging a presumed coding error when it was really an out-of-memory problem.


text:
can this piece of a camera flash send an input signal to my arduino?
I have a piece of a broken camera flash (an old Yongnuo one) that has a single pin that tells the flash when to fire. The pin looks like this :
(I guess the ring is the return/ground?)
The other side of the piece looks like this:

If my guess isn't completely wrong, those four wires are the only thing that tell the rest of the flash unit what's going on, when. So if I plugged (two, three, all four?) of those pins into my arduino I could use it as an input, yes?
I.e. Arduino would detect when the camera has taken a picture via this unit, and do something else (in my case open the gate on a mos for a length of time). No actual camera flash involved (just the signal)
My question is: how do I determine which of these four wires carry the signal to the rest of the circuit, and can I plug this into my Arduino input pin? My multimeter is a cheap crappy one so I don't think it would react fast enough to measure a pulse like that...

First you need to determine how the flash works.  Does the camera send a pulse, or does it connect the pin to ground.  Try switching the flash on, then when it's charged, use a wire to connect the pin to the ring. If it flashes then you have the equivalent of an active low digital input.  You'd need to then know the voltage levels and maybe even isolate the whole flash unit form the Arduino. It's quite a broad question with lots of unknowns at the moment.

huh, i just tested it with one of my working flashes (similar model, and it is a yongnuo one) - and yes the flash (sans camera) is triggered by simply connecting the pin to the ring. So how do i figure out the voltage level? would my cheapo multimeter help at all? Thanks for your help so far, I had no idea that was how the flash triggered!

So let me get this clear - you want to have the flash attached to the camera, and add a feed off the flash to indicate to the Arduino when a photograph (using the flash) has been taken?  Or do you want the Arduino to make the flash trigger intendant of the camera?

nope sorry I wasn't clear. The flash that I took pictures of above is broken, it won't even turn on. I took it apart and gave up when I saw all the microscopic solder spots that I cannot fix by hand. So it stayed in pieces until now.
I now have another project which is a camera slider for timelapses - the camera sits on top of a wooden dolly which is pulled along a track by a bbq rotisserie motor. The rotisserie motor is currently too fast, pulling the dolly along the track in only 10 mins or so, and I need it to be a good few hours, so I need to find a way to slow it down... (cont)

Ok, so you want the Arduino to react when the camera would have fired the (non-existant) flash?  The pin in the middle of the camera's mounting will most probably be the drain of a MOSFET which is turned on (connecting it to ground) when the camera triggers.  Check the voltage (on the camera) between the centre pin and the ring while it's just idle.  If there is no voltage showing then that is most likely a safe assumption.  You can then just connect the ring to the Arduino's ground and the pin to an input pin.  Turn on INPUT_PULLUP and you should be able to read the state. You might want to

... use one of the interrupt pins so you can react fast enough.  If there is a voltage showing between the two pins and it's not 5V then you will have to build some kind of interfacing system to the Arduino, and that depends on what the voltage is.

(cont.) I tried strings and pulleys etc, but they weren't reliable enough. I figure if arduino can detect when the camera fires, then it can turn the rotisserie motor on for a few seconds, before shutting it off again. So I need a way of detecting when the camera takes a picture. I know from previous experience that my camera always fires the flash hotshoe at the end of an exposure (called "rear curtain sync") and I pulled out my box of broken flash bits and found the photographed piece.  make sense?

You've been a huge help Majenko - thanks so much!

I'd just connect the two green wires to the arduino and remove the entire circuit board. That is, if the camera just "shorts" those two contacts to signal a flash-request. However this connection could also be used to detect if a flash is present, so the camera can disable the internal flash. In that case my solution won't work.


text:
How to disable RX led on Arduino Micro
I am using the RX LED pin as CS for my SPI connection and experiencing problems while debugging and communicating via SPI. Is it possible somehow to disable the RX blinking while using the serial monitor?

If there isn't an easier way, you could probably neuter the TXLED and RXLED macros in pins_arduino.h. you could make a new board type called "micro-no-led" to have both options available.

When you say neuter do you mean remove them by clearing the defines? I assume removing them completely will cause compilation errors in USBCore.cpp

Sorry; By neuter I mean replacing them with a statement that compiles, but has no effect.


text:
fast memory buffer and setting output state
I'm intending to set up a digital delay using a circular buffer (in SRAM) with an Arduino Due (@84MHz). The lenth of the buffer determines the delay. I need about 1us resolution and the delay needs to be dynamically settable between 0 - 500us. I'll probably use most of the memory just for the buffer.
I've got a very basic setup going (with a fixed delay, no buffer), that just updates a temporary variable with the current state of the input signal and then writes the whole word to another port in order to set the state.
Next up is designing the buffer so I can add some delay to the output of the signal.
Filling the buffer using interrupts watching signals on the same port shouldn't be too difficult but I am wondering:
a) taking speed in consideration, which buffer method will have the least processing overhead? Memory stack or an array[], or someting else?
b) is there a way to read a port and set an output port in one clock cycle? I am now using REG_PIOD_ODSR=outbyte; but ideally it needs to point to a memory address directly.

What are you sampling / delaying with your project? how many bits is each sample?

@portforwardpodcast The idea is to signal two 3-phase IGBT's and be able to balance them independently, so be able to delay 1 set of three pulses relative to the other. The arduino is not generating the PWM's but simply intercepting them from a drive's circuit board and the outputting them.

So you are buffering 1 bit samples. It may sound counter intuitive but using a full byte to store a single bit May give more performance. This is because you avoid shifts and are just doing simple memory lookups. @amandoninc 's answer is correct, just use an array. As far as hand coding assembly i disagree. I bet you could get away with an output compare interrupt. Please comment back if you need more help

@portforwardpodcast Thanks, I'll give it a try and find out. At this stage the project is on hold but it's great to know how to move forward from here.

I would use an array, they're about as simple as it gets. 84 clock cycles per sample is very tight, but definitely possible. I'm guessing that's too close to the line to do any sort time testing - you will probably have to set up your loop to take exactly 84 instructions. This means you will probably need to hand-code in assembler. Be very mindful of branching instructions - both branches will need to take the same number of clock cycles.
The Uno (AtMega328) runs most (all?) instructions in one clock cycle, I don't know if the same applies to the Due. You would need to hand-code the assembler, check out how many cycles each instruction takes, and pad it out (there is a do nothing "NOP" instruction, which typically takes one cycle.
HOWEVER -
You can get all this work done for you by using a chip made for this purpose. This is called a Digital Delay Line, http://en.wikipedia.org/wiki/Digital_delay_line (or Analog Delay Line if you want analog values, e.g. for sound playback).


text:
Connecting arduino to a PC
How would you send data wirelessly from arduino uno to a pc?
I know you can connect wifi shield / wifi breakout to arduino and use that, but what other ways are there and how practical would they be?

Almost everything else would require an additional adapter.

Laptops and smartphones come with built-in bluetooth, maybe use that?

You would need a bluetooth extension to the arduino this one would work over serial http://www.ebay.com/sch/i.html?_trksid=p5197.m570.l1313&_nkw=bluetooth+serial+module&_sacat=0&_from=R40. Then you would need to do bluetooth programming on your laptop or smartphone. You can look this up for the specific system you are using.

You have several options. One is Bluetooth and another is nRF24L01+ 2.4GHz Wireless Transceiver. I love the nRF24L01+. They are cheap and there are tons of examples online.
The concept with the nRF24L01+ is to connect the RF24 to a Ft232rl Ftdi Usb to Ttl Serial Adapter. The Ft232rl  connects to your PC. Most modern computer languages support communicating via Serial. This is the way to go.
Google around for a ton of tutorials

Could you describe how you can plug the nRF24L01+ to a PC? This is what the OP wants to do.

@jfpoilpret - See my reside answer


text:
How to have code/sketch that's easily toggleable to work on different nodes
i have a question about best practice to achieve what i want to do. I would like to have a sketch setup, and then to be able to deploy to different devices of the same type, but each device/node will have a few different parameters, like ip address and mqtt topic etc,
What would be the quickest way to be able to upload new changes to all of my nodes without having to track my changes and update each seperate sketch for each node?
I was thinking about using some IFDEF statements if i can figure out how to? would that be the best way to go or is there something better?
Thx in advance

Why not just store the parameters in EEPROM?

I don't really know how to do that or how it would work in solving my problem.. it's not something i've done before.. can you point me to further info?

You can put the per-node parameters in a external EEPROM and load them during setup(). For example the IP address is the first 16 bytes of the eeprom (IPv6), the next bytes would the the topic, etc..
That way every node has exactly the same sketch and the customization is in the eeprom that you could put in a socket and possibly have a separate programmer for them.
EEPROMs with I2C interface are easy enough to get and can store 64kB. Which should be more than enough for most things.


text:
DS18B20 setting resolution without addressing
As i understand the dallas library, there are two ways of referencing the sensor, one is to refer to the address, and the other is just to grab it as it is indexed.(gettempbyindex)
I want to know how to set the resolution of the sensor when i'm using the gettempbyindex method, all the examples i can find seem to only set resolution when specifying the address explicitly..
Is it even possible?

You can use getAddress: bool DallasTemperature::getAddress(uint8_t* deviceAddress, uint8_t index)
If you want to set the resolution for all devices, you can just use void DallasTemperature::setResolution(uint8_t newResolution). (It will call getAddress for all indices.)

Thanks for the reply, i couldn't figure out how to implement what you suggested, but your suggestion led me to what seems like a good solution to my problem.
sensors.setResolution(10);  seemed to do the trick, with "sensors" being whatever was initially declared to the dallas library in setup...

Take a look at the implementation of setResolution to see how to use getAddress.


text:
Problem with SPI when using rf24 NRF24L01 transceiver with LED matrix MD_MAX72xx
I am currently using Arduino Mega to use a LED matrix and a NRF24L01 transceiver.
for LED matrix, I use MD_MAX72xx library. While for the transceiver I use the RF24 library.
I am already able to interface Arduino using two different LED matrix, and two matrix board is already using the SPI.
But when I try to add the RF24 library, and radio.begin(); the LED matrix isn't working properly anymore.
Here is my whole code:
#include <MD_MAX72xx.h>
#include <SPI.h>
#include <Servo.h>

#include <nRF24L01.h>
#include <RF24.h>

#define PRINT(s, v) { Serial.print(F(s)); Serial.print(v); }

#define BUF_SIZE      75  // text buffer size
#define CHAR_SPACING  3   // pixels between characters
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 4

const int buzzer_pin = 26;
const int servo_pin = 28;

unsigned long buzz_time;
unsigned long sys_time;
String buzz_type = "off";
int buzz_count = 0;
char charr[50];

Servo myservo;

RF24 radio(30, 32); // CE, CSN
const byte address[6] = "GLN71";
//const byte address[5] = {'R','x','A','A','A'};

struct LineDefinition
{
  MD_MAX72XX  mx;
  char    message[BUF_SIZE];
  boolean newMessageAvailable;    // true if new message arrived
};

struct LineDefinition  Line[] =
{
  { MD_MAX72XX(HARDWARE_TYPE, 51, 52, 53, MAX_DEVICES), "MAX", true },
  { MD_MAX72XX(HARDWARE_TYPE, 51, 52,  49, MAX_DEVICES), "MAX", true }
};

#define MAX_LINES   (sizeof(Line)/sizeof(LineDefinition))

void printText(uint8_t lineID, uint8_t modStart, uint8_t modEnd, char *pMsg)
// Print the text string to the LED matrix modules specified.
// Message area is padded with blank columns after printing.
{
  uint8_t   state = 0;
  uint8_t   curLen;
  uint16_t  showLen;
  uint8_t   cBuf[8];
  int16_t   col = ((modEnd + 1) * COL_SIZE) - 1;

  Line[lineID].mx.control(modStart, modEnd, MD_MAX72XX::UPDATE, MD_MAX72XX::OFF);

  do     // finite state machine to print the characters in the space available
  {
    switch(state)
    {
      case 0: // Load the next character from the font table
        // if we reached end of message, reset the message pointer
        if (*pMsg == '\0')
        {
          showLen = col - (modEnd * COL_SIZE);  // padding characters
          state = 2;
          break;
        }

        // retrieve the next character form the font file
        showLen = Line[lineID].mx.getChar(*pMsg++, sizeof(cBuf)/sizeof(cBuf[0]), cBuf);
        curLen = 0;
        state++;
        // !! deliberately fall through to next state to start displaying

      case 1: // display the next part of the character
        Line[lineID].mx.setColumn(col--, cBuf[curLen++]);

        // done with font character, now display the space between chars
        if (curLen == showLen)
        {
          showLen = CHAR_SPACING;
          state = 2;
        }
        break;

      case 2: // initialize state for displaying empty columns
        curLen = 0;
        state++;
        // fall through

      case 3: // display inter-character spacing or end of message padding (blank columns)
        Line[lineID].mx.setColumn(col--, 0);
        curLen++;
        if (curLen == showLen)
          state = 0;
        break;

      default:
        col = -1;   // this definitely ends the do loop
    }
  } while (col >= (modStart * COL_SIZE));

  Line[lineID].mx.control(modStart, modEnd, MD_MAX72XX::UPDATE, MD_MAX72XX::ON);
}

void buzz_start(){
    buzz_count = 5;
    buzz_time = millis();
}

void buzz_call(){
  if(buzz_count > 0){
    if(millis() >= buzz_time){
      if(buzz_type == "off"){
        tone(buzzer_pin, 1000);
        buzz_type = "on";
      }else{
        noTone(buzzer_pin);
        buzz_type = "off";
        buzz_count--;
      }
      buzz_time = millis() + 300;
    }
  }
}

void setup()
{
  Serial.begin(57600);
  pinMode(buzzer_pin, OUTPUT);

  myservo.attach(servo_pin);

  tone(buzzer_pin, 1000);
  Serial.println("BEGIN");

  for (uint8_t i=0; i<MAX_LINES; i++){
    Line[i].mx.begin();
  }

  radio.begin();
  radio.openReadingPipe(20, address);
  radio.setPALevel(RF24_250KBPS);
  radio.startListening();

  String charrr = "STOP";
  charrr.toCharArray(charr, 50);
  printText(1, 0, MAX_DEVICES-1, charr);

  myservo.write(90);
  delay(500);
  myservo.write(180);

  noTone(buzzer_pin);
  sys_time = millis();
}

int counter = 10;
int disp = 0;
void loop()
{
  String charrr = String(counter);
  charrr.toCharArray(charr, 50);
  printText(0, 0, MAX_DEVICES-1, charr);
  if(counter == 0){
    counter = 9;
    if(disp == 0){
     disp = 1;
     String charrr = "  GO";
     charrr.toCharArray(charr, 50);
     printText(1, 0, MAX_DEVICES-1, charr);
     myservo.write(90);
     buzz_start();
    }else{
     disp = 0;
     String charrr = "STOP";
     charrr.toCharArray(charr, 50);
     printText(1, 0, MAX_DEVICES-1, charr);
     buzz_start();
     myservo.write(180);
    }
  }
  if(millis() >= sys_time){
    counter--;
    sys_time = millis() + 1000;
  }

  buzz_call();

}

I think the problem here is not connection, but with the initalization of the RF24, and radio.begin();

I looked into the source code of the MD_MAX72XX library. The constructor with SPI pins starts software SPI.
Use the MD_MAX72XX::MD_MAX72XX(moduleType_t mod, uint8_t csPin, uint8_t numDevices): constructor to work with SPI hardware/library with all devices.
struct LineDefinition  Line[] =
{
  { MD_MAX72XX(HARDWARE_TYPE, 53, MAX_DEVICES), "MAX", true },
  { MD_MAX72XX(HARDWARE_TYPE, 49, MAX_DEVICES), "MAX", true }
};

Or if the MD_MAX72XX worked for you with software SPI, then use some other pins then hardware SPI pins to make hardware SPI free for the NRF24L01.
struct LineDefinition  Line[] =
{
  { MD_MAX72XX(HARDWARE_TYPE, SW_SPI_SI, SW_SPI_CLK, MAX1_CS, MAX_DEVICES), "MAX", true },
  { MD_MAX72XX(HARDWARE_TYPE, SW_SPI_SI, SW_SPI_CLK, MAX2_CS, MAX_DEVICES), "MAX", true }
};

are you suggesting that, to initialize the transciever (rf24), instead of radio.begin();.... I should use MD_MAX72XX::MD_MAX72XX(moduleType_t mod, uint8_t csPin, uint8_t numDevices): ?

Thanks! That did the trick. I changed the SI, and CLK. { MD_MAX72XX(HARDWARE_TYPE, 11, 8, 53, MAX_DEVICES), "MAX", true },   { MD_MAX72XX(HARDWARE_TYPE, 11, 8,  49, MAX_DEVICES), "MAX", true } Then the pins 50,51,52 are now used by the NRF24

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


text:
Problem with reading multiple potentiometer values on Arduino Uno
I'm working on an Arduino sketch that will read in values from two potentiometers. The code for this is below:
int lastPotentiometerOneValue = 0;
int lastPotentiometerTwoValue = 0;

void setup() {
  // initialize serial communication at 57600 bits per second:
  Serial.begin(57600);
}

void loop() {
  delay(10);
  readAndSendPotentiometerDataIfChanged();
}

void readAndSendPotentiometerDataIfChanged(void) {

  //Potentiometer One
  int newPotentiometerOneValue = analogRead(A0) / 10.2;
  if (newPotentiometerOneValue == lastPotentiometerOneValue) return;

  Serial.print("!pos1");
  Serial.print(newPotentiometerOneValue);
  Serial.print(";");
  lastPotentiometerOneValue = newPotentiometerOneValue;

  //Potentiometer Two
  int newPotentiometerTwoValue = analogRead(A1) / 10;
  if (newPotentiometerTwoValue == lastPotentiometerTwoValue) return;

  Serial.print("!pos2");
  Serial.print(newPotentiometerTwoValue);
  Serial.print(";");
  lastPotentiometerTwoValue = newPotentiometerTwoValue;
}

The schematic for my circuit is below (I've left out the code for reading the state of the push-button in my listing above, as that's in a separate method from the method that reads in the potentiometer data):

However, there seems to be a rather subtle error I'm experiencing. If I turn Potentiometer One, it will display the correct output in the serial monitor. If I turn Potentiometer Two, no value will be displayed. However, if I remove Potentiometer Two from the circuit board and turn Potentiometer One, then the serial monitor will display the Potentiometer Two as having the same data as Potentiometer Two.
I'm sure the problem is with my circuit, but I'm not quite sure what I'm doing wrong. Does anyone have some insight? Thank you!

One problem is that if the value for pot1 has not changed, the value for pot2 will never be sent, even if it has changed, due to the early return when checking the value of pot1. You could fix this by changing to:
void readAndSendPotentiometerDataIfChanged(void) {

  //Potentiometer One
  int newPotentiometerOneValue = analogRead(A0) / 10.2;
  if (newPotentiometerOneValue != lastPotentiometerOneValue) {
      Serial.print("!pos1");
      Serial.print(newPotentiometerOneValue);
      Serial.print(";");
      lastPotentiometerOneValue = newPotentiometerOneValue;
  }

  //Potentiometer Two
  int newPotentiometerTwoValue = analogRead(A1) / 10.2;
  if (newPotentiometerTwoValue != lastPotentiometerTwoValue) {
      Serial.print("!pos2");
      Serial.print(newPotentiometerTwoValue);
      Serial.print(";");
      lastPotentiometerTwoValue = newPotentiometerTwoValue;
  }
}

Worked beautifully! I realized that I was looking at a rather old code example that was based off of only one potentiometer (where those "return" statements came from).


text:
Arduino-controlled current limiter for lathe
I'm building a lathe that will be powered by a 3-phase 750w AC motor (4 pole, max unloaded RPM of 1400 RPM). I want to be able to control the RPM using a potentiometer attached to an Arduino mega which I can figure out how to do.
Under load, I'm guessing the motor is going to want to draw more current across each of the phases, the cabling can take the extra current draw but I don't want to damage the motor.
Could I use AnalogueRead (using current transducers) to tell the Arduino to increase the resistance with a servo-potentiometer setup or cut the power momentarily (using transistors on each phase) if the current rose above a certain level? If so, is there any code that would be good to steal/adapt?
Thanks all!


text:
Arduino Uno - What can I make with just the base board
So I just bought my first Arduino (an Uno r3), and dove right in.
All I have currently is the base board (I didn't want to invest too heavily and then realize arduinos weren't for me), so I made a quick script that translates input letters to morse via the LED on the top.
Now that I'm done with that, I figured I'd come here to ask: do you guys have any random ideas for things I can make with JUST the uno? I understand that I should probably just start buying kits and shields, but I'm just curious as to what I can make with the most minimal of items. I consider it a test :)
Thanks in advance guys!

You can do anything that only involves talking on the serial connection and blinking the LED.

Well,
Your question is very broad. But the Arduino essentially needs controlling gadgteers to make things easy ( and funny ).
However if you know a bit of electronics, then you may be able to use the IN/OUT analog ports and build other interfaces to control, for example the lights of your home, or even better. You can measure and control priate things should be linked. Increasing the power of your home.
If you have interest in cars, then you can perform to connect the on-board computer of your car to the Arduino, like this.
Well, there are numerous ideas, none of these I'm saying is new and there are even libraries ready to be used in these segments mentioned above.
Regards,
Andrew Paes

Thank you for your multiple examples! I realize my question is extremely broad, but I think you did a good job of answering it. I thought about making a lightswitch controller but that would require some other components, correct? Unless I'm mistaken.

At least 1 push button costing you $2,00. Would better Would better buy a LCD Multi Touch display costing around $9,00 giving you the chance to have any buttons as you want.


text:
How to use Timer1 (AT328Mega) to measure the time between rising edges of two input signals
I'd like to use Timer1 to measure the time between rising edges of two input signals.  Specifically, use Tn to start the timer counter and IPCn to latch the elapsed time since the rising edge of the Tn input signal.  The goal is to measure the time between the rising edges of two input signals.   Is there a Timer1 library out there that alread does this?  Code suggestions welcomed.

What is the minimal expected duration between two consecutive rising edges of your signal?

// ICNC1: Enable Input Capture Noise Canceler // ICES1: =1 for trigger on rising edge // CS10: =1 set prescaler to 1x system clock (F_CPU) TCCR1A = 0; TCCR1B = (0<<ICNC1) | (0<<ICES1) | (1<<CS10); If I read this correctly (questionable), it looks like the everything is set backwards from what the text says it is supposed to be. Am I reading it wrong? Doesn't "(0<<ICNC1)" put a 0 into the ICNC1 bit? Doesn't that disable the noise canceler? This should be what you WANT for the purposes of catching every rising edge, but the explanation doesn't match the code. Also, doesn't "(0<<ICES1)" catch t

It is not perfect for your simpler task, but here is a link to a sketch that I have used to record pulses, using the Timer1 Input Capture.
In short setup the Interrupt
void initTimer(void) {

  // Input Capture setup
  // ICNC1: Enable Input Capture Noise Canceler
  // ICES1: =1 for trigger on rising edge
  // CS10: =1 set prescaler to 1x system clock (F_CPU)
  TCCR1A = 0;
  TCCR1B = (0<<ICNC1) | (0<<ICES1) | (1<<CS10);
  TCCR1C = 0;

  //catchFallingEdge(); // initialize to catch
  { TCCR1B &= ~(1<<ICES1); TIFR1 |= (1<<ICF1); rising = 0; }

  // Interrupt setup
  // ICIE1: Input capture
  // TOIE1: Timer1 overflow
  TIFR1 = (1<<ICF1) | (1<<TOV1);        // clear pending
  TIMSK1 = (1<<ICIE1) | (1<<TOIE1); // and enable

  // Set up the Input Capture pin, ICP1, which corresponds to Arduino D8
  pinMode(8, INPUT);
  digitalWrite(8, 0);       // leave floating to count 60 Hz etc.
  //digitalWrite(8, 1);         // or enable the pullup
}

Then service it
ISR(TIMER1_CAPT_vect) {
  union twobyte {
    uint32_t word;
    uint8_t  byte[2];
  } timevalue;

  timevalue.byte[0] = ICR1L;        // grab captured timer value
  timevalue.byte[1] = ICR1H;        // grab captured timer value

  // watch for the other edge to catch the half-pulse width
  //rising ? catchFallingEdge() : catchRisingEdge();
  if (rising) {
    TCCR1B &= ~(1<<ICES1);
    TIFR1 |= (1<<ICF1);
    rising = 0;
  }
  else {
    TCCR1B |= (1<<ICES1);
    TIFR1 |= (1<<ICF1);
    rising = 1;
  }
}

For more help and info, and many examples of various detailed aspects of timers, check out Nick Gammon's articles here: http://www.gammon.com.au/interrupts
and here: http://www.gammon.com.au/timers
Under the first link, do a search for "The sketch below times intervals between RISING interrupts," for example, to find one code segment.
Now, important question: what is the minimum time you need to measure between events?  Are we talking milliseconds, microseconds, or nanoseconds?  For the former, you can use pin polling, external interrupts, or pin change interrupts, and the millis() or micros() Arduino functions to grab timestamps. For microseconds resolution, it depends. Even the micros() function only has a 4us resolution, so you'd have to custom-configure the timer if you want better than 4us resolution time-stamps, or you could use the timer2_counter library (http://electricrcaircraftguy.blogspot.com/2014/02/Timer2Counter-more-precise-Arduino-micros-function.html), or your own custom timer solution, for 0.5us resolution timestamps.
For nanosecond resolution (down to 62.5ns time steps), youd prob. need to use Timer1's input capture, as the other answer shows. You can also do a search for "Timing an interval using the input capture unit" under the 2nd link above, for another code segment on that.


text:
DigiSpark attiny85 computer not detecting
I purchased a DigiSpark attiny85 off of ebay. Over the weekend I tried to get my computer to recognize the DigisSpark, but it won't recongnize it. When I plug the device in, the 'Device Connection' Sound alerts me and then a second or two the 'Device Disconnection' Sound alerts, then 'Device Connection' Sound, then the 'Device Disconnection' sound. This happens until I unplug the device. The light does turn on, but Windows (10) doesn't recognize the device, it just loops the sounds.
I am trying on a Windows 10 machine.
I installed the drivers from the DigiStump Github: https://github.com/digistump/DigistumpArduino/releases/download/1.6.7/Digistump.Drivers.zip
I do see 'Digispark Bootloader' in my device manager for a couple of seconds in my device manager.
I tried different cables. I tried to install the drivers on another computer and the same thing happens.
What should I try next? Am I missing other drivers?

You can make the Device Manager to show unconnected devices (or whatever term it uses, I don't have an English Windows). Check there for the device.

Unless, during the short time it shows in device manager, you see that it is missing a driver, it would seem you don't need to do anything further with drivers.  You didn't mention it saying it was missing a driver or as an "unrecognized" device, so I'm guessing you mean it doesn't stay recognised or that it isn't recognized as a serial device.  If I'm incorrect in that, do say. The fact that it is showing in device manager for any length of time suggests that your cables are fine.
I'm not a Digispark user, but as far I can understand what you're saying, the connecting and disconnecting (once at least) is expected behaviour:

In addition remember the Digispark only shows up as a programmable
device for 5 seconds, after that it will start running its code (when
it is new and un-programmed this means it will blink) and disappear or
act like the USB device you programmed it to act like.

If anything in the sketch (or lack thereof) causes the board to reset or jump to the bootloader, it would continually reconnect for 5 second intervals.  They documentation suggests should blink, as in run a blink sketch that was put on the board before you received it.  But then you got this from ebay, so who knows what they did or did not put on it.  I haven't studied the micronucleous bootloader enough to know, but it wouldn't surprise me if it jumps to the sketch area irrespective of whether or not it's unprogrammed.  If it is unprogrammed then it is probably nop-sliding, for lack of a more appropriate term, right back into the bootloader.
You're not going to see it recognized as a serial port device like a typical Arduino.  The bootloader uses a vendor specific protocol that will not list as a COM# (or /dev/ttyXYZ#) device.
Indications are that if you compile the blink sketch and "upload", the IDE will run the micronucleus programming tool which gives you a 60 second window for you to plug the board in, at which point it will load the board with the blink sketch.  After which it should blink the LED.  If unplugged and replugged, you can expect it to show up for 5 seconds on USB and if left alone should disconnect (electrically) from USB and begin blinking.

You are correct. I was following a youtube video and the video was showing something else. Went to another tutorial and the device behaves as it does with mine.


text:
Working with multiplexers for constant voltage output
I'm working on creating a circuit where I'm trying to have the ability to switch multiple strands of LED rope on and off at a time using an Arduino and a multiplexer.
With my current configuration, I have the a circuit and a sketch that will cycle through the various LED rope strands, turning them on and off.
What I'm not sure how to do is modify my sketch / circuit so that I can turn ALL of the rope strands on and off, as well as individually.
Below is my current Arduino sketch:
//Mux control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux in "SIG" pin
int SIG_pin = 3;

int testValue = 255;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);

}

void loop(){

  //Loop through and read all 16 values
  //Reports back Value at channel 6 is: 346
  for(int i = 0; i < 9 ; i ++){
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[10][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  analogWrite(testValue, SIG_pin);

  //return the value
  return 0;
}

I'm using two multiplexers to control multiple rope strands. Here's roughly what that looks like:

I'm still a bit new to electronics prototyping (coming from software development); so I'm not sure if what I want to do is possible with a multiplexer
Happy to start offer a bounty to a helpful answer.
Thank you

This is going to be difficult! You should have bought a digital LED strip. The analog one you got needs to be continously fed with PWM signals, and the MUXes can only route your PWM output to one color channel of one strand at a time. Are you using PNPs or MOSFETs? With MOSFETs, it may be possible to use their gate capacitance (or an extra cap) to hold the value while you rapidly cycle the MUX. Not sure you can do this fast enough to avoid visible blinking though.

Ah - that makes sense. Yeah, definitely should have gone with the digital LED strip :/ Wondering if something like this may do the trick... https://www.adafruit.com/products/1429

Looks good to me. Notice that you will need pullup resistors between that chip and each of your transistors.

I would think that for a small number of channels, cycling through them wouldn't produce flicker, but 16 or more channels is a lot for that technique, especially if you want a fair amount of control over the brightness as opposed to just on/off. Another board to look at that might help out is the SX1509, which is cheaper and I think more programmable than the TLC5947.

I advice using ht16k33 (you will use this one with digitalWrite)

Even I am new to this and I also find it a bit challenging with the available setup and desired output. Though it seems tough, I want you to just try out this code (it is a little modification to the one posted by you) and check whether it matches the expected result.
    //Mux control pins
#define s0 8;
#define s1 9;
#define s2 10;
#define s3 11;

//Mux in "SIG" pin
#define SIG_pin 3;

#define testValue 255;  //maximum value for analogWrite() function

void setup()
{
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
}

void loop()
{
  //Loop through and read all 16 values
  for(int i = 0; i < 16 ; i ++)
  {
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel)
{
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[16][4]=
  {
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++)
  {
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  for(int i_testValue = 0; i_testValue < testValue; i_testValue++)
  {
    analogWrite(i_testValue, SIG_pin);      //incresing intensity slowly with delay of 100ms
    delay(100);
  }

  //return the value
  return 0;
}


text:
Using an Arduino and multiplexer for writing to multiple outputs
I'm attempting to use the multiplexer setup in this article with my Arduino Uno to control the output of LED's, as a way to fully understand the principles of multiplexing.
I'm working to modify the code in the article to switch from reading potentiometer values to writing voltage values to the LED's.
Below is the modified sketch; the biggest modified change is the loop in the writeMux function:
//Mux control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux in "SIG" pin
int SIG_pin = 3;

//Voltage value to write to the LEDs
int testValue = 255;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
}

void loop(){
  for(int i = 0; i < 9 ; i ++){
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[10][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
//    {0,1,0,1}, //channel 10
//    {1,1,0,1}, //channel 11
//    {0,0,1,1}, //channel 12
//    {1,0,1,1}, //channel 13
//    {0,1,1,1}, //channel 14
//    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  analogWrite(testValue, SIG_pin);

  //return the value
  return 0;
}

Below is a photo of my circuit:
However, none of the LED's light up.
I'm fairly certain that this is more of a problem with the code rather than the circuit...any advice is appreciated!

According to the analogWrite() documentation, apparently the trouble are that you have swapped the args.
The syntax are analogWrite(pin, value), so, the piece
//read the value at the SIG pin
analogWrite(testValue, SIG_pin);

may work if you simply change to
//read the value at the SIG pin
analogWrite(SIG_pin, testValue);

That with respect to code, and i hope it helps you. At the other hand, the circuit, may be a bit dangerous (and can damage the Arduino or the mux) to use LEDs without a current limiter series resistor (330 - 1K Ohm would be nice values, 1/4 W). At least, by a light sight in a datasheet of the CD74HC4067, shows max currents of +/- 25 mA per pin. Similar currents can be driven by the Arduino (Atmega 328P).
So, all depends on the internal construction of the 4067, if are a transparent mux, maybe just with a single resistance in the SIG_pin in that range of resistances, would be fine.
Edit - Some Circuit Troubleshooting
There are some other little tests that you can do after that change in code:

Open the wire that goes from the Arduino to the common of the mux, then place at the output of the same Arduino pin, a LED-resistor series. Then change in program only the value of testvalue at the beginning of the code and check if the led changes their intensity according to that. That would be an Ok for that pin of the Arduino.
Reply the previous step to each of the channel pins. According to the code, you should see an increasing 1 Hz, 4 bits counter (rather, a BCD counter) in thet formed 4 led array. That would be an OK for the channel selection pins.
Remove the leds and connect back the opened lines.

Any fail in steps 1 or 2 may indicate that the pin are damaged but you can use another analog pin and other pins for the channels respectively. But if at step 3 it doesn't works, may be a damaged 4067 or a little hidden bad connection...


text:
Mixing analog reads with raw port reads
I'm reading two digital inputs and one analog input. For [reasons] I must use A0 and A1 as digital ins, and A2 as an analog in.
I'm uncertain about how the Arduino hardware deals with mixing analog and digital inputs on the same port. For speed, I'm reading like this:
 uint8_t raw = PINC;
 boolean digitalA = (bool)(raw & 1);  // read A0
 boolean digitalB = (bool)(raw & 2);  // read A1
 int analogC = analogRead(A2);

Will the raw reading of the port interfere with the analogRead in any way? I did see a caveat about mixing A & D, but it only had to do with noise introduced in the analog ins when doing digital outs. Would reading analog first minimize that?

Ah, I see what you are asking.  Instead of using individual pin reads you are simply reading the entire set of Analog pins (0-5) then using an analogRead on pin 2.   I don't think this should be a problem.  But you may want to try using individual pin reads to see if it makes any difference.

@st2000 - Thanks. The concern is that performing a raw read may disrupt the ADC process. I'm coding in advance of having equipment available, that's why I'm asking about this rather than just experimenting. The actual code is more complicated than the simple example here.

What you are trying to do is perfectly safe. In fact, you reading PINC
will have no effect whatsoever on the input circuitry. You are just
reading an I/O register and, whether you read it or not, this register
is updated on every clock cycle from a set of comparators that monitor
the pin voltages.
Just for completeness, I should mention that it is possible to disable
the comparators that update the register. The Atmel datasheet recommends
to disable them if you want the lowest possible ADC noise. If you follow
that recommendation, then reading PINC will just return zero. The
Arduino core library does not disable them: the input comparators are
thus always active, and you can get a meaningful value by reading that
digital input register.
Edit: You can selectivly disable the input comparator on the pin
A2 by issuing DIDR0 |= _BV(ADC2D);. But that is only useful if you
really need to maximize the accuracy.

I agree, it is perfectly safe. The AVR microcontrollers have different kind of internal hardware parallel on the same pin. The digital part and the analog part are default both active and can both be used at the same time. They use the same pin, that's all, there is no internal mix.

In general, most embedded processors multiplex external pins into specialized internal circuits.  Circuits which check standard fixed threshold crossings (digital inputs), circuits which check variable threshold crossings (comparators) and circuit which combine comparators with a variable settable reference (analog to digital converter) to name only three.
Usually a pin is multiplexed to a particular internal circuit only once during initialization.  Switching between internal circuits as part of normal operation is tricky and can lead to unexpected results.
Analog reads are often problematic because of noise.  However, it is unlikely that reading the state of a digital input will effect the conversion of the ADC circuit.
It would be far more effective to read the actual processor's application note you are using and understand that processor's ADC issues.  You may be surprised that the number is significant bits (usable bits) are less than the number found in the ADC register.  Or that you can increase the number of significant bits simply by adding averaging to your software.

What part of initialization maps an analog pin to a digital input? As far as I can tell, using pinMode() to set A0..A5 as input doesn't specify how the input will be read from that pin -- that's determined by analogRead() vs digitalRead(), not fixed at init time. Yes? And I'm not using digitalRead() but raw port access, hence the question.


text:
Is code in a class repeated for each instance?
I haven't needed classes before in programming for Arduino, but I now have a good use case. I'm not sure I grasp how this will affect code space, though.
Currently I have a struct that holds the properties of an object, and common code that iterates over an array of 12 of that struct. It's fairly compact.
It would be cleaner to wrap the operations on the struct in a class and act on an array of 12 of that class. Essentially the current struct would become private data of the class.
Will all the code in the class be repeated in each instance, or is the compiler clever enough to avoid such repetition?
Any clarifications welcome. C++ is not my main language.

No, it is not repeated. Unless you are using templates, each method of
each class is stored only once in the compiled program. Or even not
stored at all if the optimizer notices it is not used.
Just to demystify the classes a bit, you can consider them as a kind of
“syntactic sugar” over an “object oriented” programming pattern. The
following C++ code:
class MyClass {
public:
    int aMember;
    long anotherMember;
    int aMethod(short);
};

int MyClass::aMethod(short theParameter)
{
    return aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    objects[1].aMethod(42);
}

is interpreted by the compiler as being roughly equivalent to this C
code:
typedef struct {
    int aMember;
    long anotherMember;
} MyClass;

int MyClass_aMethod(MyClass *this, short theParameter)
{
    return this->aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    MyClass_aMethod(&objects[1], 42);
}

Can you spot the differences and the similarities?

I get the idea but I'm not sure how to interpret return aMember + theParameter; In any case, the main question is answered, so thanks.

@JimMack: Within a method, the class is used as a sort of namespace. So the compiler knows that aMember actually means this->aMember.

No, the code is not repeated for each instance. Instance methods are like functions. There is only one copy of the code.
There's a dispatch table that maps method calls to their implementations. (Actually, that's standard C++. I don't know for sure how it's implemented in the Arduino C++ compiler)

Dispatch table is only used for virtual methods. As long as we are talking about non-virtual methods, everything works exactly as @Edgar Bonet described. No need for any tables. Arduino IDE C++ compiler is C++11 compiler with GNU extensions.

Important distinction about virtual methods. Thanks for pointing it out.


text:
Where to remove an ADC bias?
I'm using several ACS712-based 5A current sensors. They're non-polar and so (I gather) the output is biased to Vcc/2 to allow a swing in either direction. The sensor outputs +/- 185mV/A, plus the bias.
The example sketch I've seen does a computation like amps = ((analogRead(A0) * 5.0) / 1023) - 2.5 (where 2.5v is the bias).
In my case the actual current value and polarity aren't important, just the presence of current. Is there anything untoward about doing this instead?
boolean isCurrent = (abs(analogRead(A0) - 512) > thresholdValue);

This avoids floating point (unless abs() forces it?) and an ADC count of 512 should be equivalent to a bias of Vcc/2. The threshold just cores out some noise / jitter / drift. Seem OK? Can anyone suggest a better approach?

yes, but most (all?) of the "negative" is noise anyway right? or is the flow reversible?

@dandavis - For any given sensor the flow will be one-way, but I can't assume that all will be wired the same. There are 12+ of these and their inputs will arrive as pairs of black wires. Since the reading code is common to all (in a loop), I have to accommodate both polarities.

No, there is nothing untoward about that - it is perfectly acceptable and, in fact recommended, since as you note it uses no floating point.