text:
Script on pc only gets 640 characters via serial
I experience that if the Arduino (Teensy 3.2) writes a rather long stream of characters to serial, the python script on the other end only receives the first 640 characters. I have found this result both by printing chars, printing lines and by using ArduinoJson's prettyPrintTo(Serial).
Note, that it does not matter what chunks of characters I read in the Python scripts, whether it is read(5) or read(1000).
With the Arduino Serial Monitor, I get all the data, ie more than the 640 characters.
From what I can understand, it is not possible for a sketch to write "too fast" or "too much" to the serial, so there must be something on the pc side receiving the data. However, the Python script for some reason does not get all the data.
What is the problem here? Where should I look for the problem/solution? Perhaps this is more a Linux or Python question, but I will try here.
Sketch - printLines()
void printLines() {
  for (int i=0; i<100; i++) {
    // length below is 40 incl end of line character
    Serial.printf("abcdefthijklmnopqrstuvxyz123456789--%03d\n", i);
  }
}

void setup() {
  Serial.begin(9600);
  delay(500);
  printLines();
  //printChars();
  //printJson();
}

void loop() {}

Sketch - printChars()
void printLines() {
  for (int i=0; i<1000; i++) {
    Serial.write('x');
  }
}

Sketch - printJson()
void printJson() {
  StaticJsonBuffer<10000> jsonBuffer;
  JsonArray &root = jsonBuffer.createArray();
  for (int i=0; i<700; i++) {
    root.add(i);
  }
  root.prettyPrintTo(Serial);
}

Python script
import serial

ser = serial.Serial('/dev/ttyACM0')
ser.timeout = 0.5

# PARAMETERS:
# (As long as num_iterations*num_chars >= 640, EXACTLY 640 characters are read)
num_chars = 100
num_iterations = 10

chars_read = 0
for i in range(num_iterations):
    s = ser.read(num_chars)
    chars_read += len(s)
    print("### i: %d, reading %d chars, char %d to %d, len(s): %d, total chars: %d"
        % (i,num_chars, i * num_chars, i * num_chars + num_chars -1, len(s), chars_read ))

Terminal output
jan@jan:~/Desktop/batlogger/localserver$ sudo python localserver.py
### i: 0, reading 100 chars, char 0 to 99, len(s): 100, total chars: 100
### i: 1, reading 100 chars, char 100 to 199, len(s): 100, total chars: 200
### i: 2, reading 100 chars, char 200 to 299, len(s): 100, total chars: 300
### i: 3, reading 100 chars, char 300 to 399, len(s): 100, total chars: 400
### i: 4, reading 100 chars, char 400 to 499, len(s): 100, total chars: 500
### i: 5, reading 100 chars, char 500 to 599, len(s): 100, total chars: 600
### i: 6, reading 100 chars, char 600 to 699, len(s): 40, total chars: 640
### i: 7, reading 100 chars, char 700 to 799, len(s): 0, total chars: 640
### i: 8, reading 100 chars, char 800 to 899, len(s): 0, total chars: 640
### i: 9, reading 100 chars, char 900 to 999, len(s): 0, total chars: 640

You're not actually using a serial connection there - you're using a USB CDC/ACM connection, which is a whole different ball game. Are you sure you're not just missing the first chunk of the data while you're sending without the python program running?

Typically CDC/ACM will discard characters if the port is not open at the remote end - or it will discard characters after the buffer is full. This is different to UART since a UART can transmit regardless of what is wired or not wired to it - CDC/ACM can only actively transmit if the port is open at the remote end.

I am sure I don't miss the first chunk, because when I ask it to print, it shows that the first 640 characters is the start of the data.

It could well be that the Teensy is able to buffer 640 bytes in the USB buffer and discards everything else. When you open the port on the PC it then receives the 640 bytes that have been buffered.  Make the Teensy wait for the port to be opened before doing any sending (while (!Serial);)

CDC/ACM packets are 64 bytes in size. It makes sense that there may be 10 packet buffers allocated, which makes 640 bytes.

@MadsSkjern Have you tried the suggestions in both answers? Any improvements or differences? Still reading exactly 640 chars every time?

You are not using a serial connection, you are using a USB CDC/ACM connection, and that is a very very different thing.
With a serial connection when you send data it gets sent regardless of whether there is anything listening for it - the TX IO pin toggles high and low regardless.
However, with a CDC/ACM connection it's only possible to send data when there is something actively listening at the remote end - that is, when the port /dev/ttyACM0 has been opened by an application.
Until that port has been opened any data sent will remain in internal buffers.  These buffers are 64 bytes each in size (that's the size of a CDC/ACM packet), and there are (I would guess) 10 of them on the Teensy3.  After these buffers are full, because there is nothing receiving the data, there can never be any more room made for more data, so instead of blocking like a serial connection does it just discards the data.
So you have filled the buffers with 640 bytes of data and thrown away the rest.  That data just sits there.
Then eventually you open the /dev/ttyACM0 port and the Teensy3 is now able to send CDC/ACM packets through the USB.  And it has 10 of those packets sat there waiting to go out, so it sends them.  So you receive the 640 bytes of data that you had buffered up.
Your mistake is basically not waiting for the port to be opened before sending data to the remote end.  You can test the state of the port (kind of, but that's a whole other subject) by examining the Serial object:
if (Serial) {
    // ... the port is open
}

In general you can usually just wait at the start of your program before starting anything else with a simple while:
while (!Serial); // Wait for the port to be opened

Great, while(!Serial) fixed it. I knew of that "trick", I know people write it. But I thought the serial connection was in place as long as the pc had "registered" the /dev/ttyACM0. Obviously there is no connection before some proces on the pc opens a connection, fx serial monitor or a python script.

I wouldn't be running as root. Why do that, just to execute a Python script?
Anyway, your problem is that you are not waiting for input. Your Python script is executing faster than the Arduino can pump out the bytes. At 9600 baud you send one byte every 1/960 of a second, so to send 4000 bytes (100 x 40) would take 4000 * 1/960 = 4.166 seconds. However your Python script powers along, getting the first 600 or so which may have been buffered already, and then finishes. You need to rewrite so you wait for a line to arrive. For example:
import serial

ser = serial.Serial('/dev/ttyACM0')

while True:
  s = ser.readline()
  print (s)

When I ran that I saw all 100 lines.
Of course, you need to modify that to break out of the loop. Maybe a special character would do that. Typically a newline is used.

PySerial's read function is blocking by default. - or it has a long timeout anyway

Not when I tested it. Using the code in the question, and without the Arduino even plugged in, I get:
### i: 0, reading 100 chars, char 0 to 99, len(s): 0, total chars: 0
### i: 1, reading 100 chars, char 100 to 199, len(s): 0, total chars: 0
### i: 2, reading 100 chars, char 200 to 299, len(s): 0, total chars: 0
### i: 3, reading 100 chars, char 300 to 399, len(s): 0, total chars: 0
### i: 4, reading 100 chars, char 400 to 499, len(s): 0, total chars: 0
### i: 5, reading 100 chars, char 500 to 599, len(s): 0, total chars: 0
### i: 6, reading 100 chars, char 600 to 699, len(s): 0, total chars: 0
### i: 7, reading 100 chars, char 700 to 799, len(s): 0, total chars: 0
### i: 8, reading 100 chars, char 800 to 899, len(s): 0, total chars: 0
### i: 9, reading 100 chars, char 900 to 999, len(s): 0, total chars: 0

Execution time: 5.5 s.
Of course, the code sets the timeout to 0.5s. But that isn't good enough. You can't assume that 400 bytes will arrive within 0.5s. They should if both sides are perfectly synchronized (at 9600 baud it would take 0.416s).
But serial doesn't work that way. You can't just read for 0.5s and hope everything you want arrives in that time. Heck, it may not have even started sending.

OK, I admit I tested with my Uno and not a Teensy, but this amended Python script shows similar results:
import serial

ser = serial.Serial('/dev/ttyACM2')
ser.timeout = 0.5

# PARAMETERS:
# (As long as num_iterations*num_chars >= 640, EXACTLY 640 characters are read)
num_chars = 100
num_iterations = 10

chars_read = 0
result = ""
for i in range(num_iterations):
    s = ser.read(num_chars)
    result = result + str(s)
    chars_read += len(s)
    print("### i: %d, reading %d chars, char %d to %d, len(s): %d, total chars: %d"
        % (i,num_chars, i * num_chars, i * num_chars + num_chars -1, len(s), chars_read ))
    print ("String = " + str (s))
    print ()

print ("-" * 70)
print ("Total output =")
print (result)
print ("Total length =", len (result))

Output:
### i: 0, reading 100 chars, char 0 to 99, len(s): 100, total chars: 100
String = b'thijz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmnopqrstuvxyz123456789yz123456'

### i: 1, reading 100 chars, char 100 to 199, len(s): 100, total chars: 200
String = b'789--68\nabcdefthijklmnopqrstuvxyz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmn'

### i: 2, reading 100 chars, char 200 to 299, len(s): 21, total chars: 221
String = b'opqrstuvxyz123456789\xff'

### i: 3, reading 100 chars, char 300 to 399, len(s): 0, total chars: 221
String = b''

### i: 4, reading 100 chars, char 400 to 499, len(s): 0, total chars: 221
String = b''

### i: 5, reading 100 chars, char 500 to 599, len(s): 0, total chars: 221
String = b''

### i: 6, reading 100 chars, char 600 to 699, len(s): 100, total chars: 321
String = b'abcdefthijklmnopqrstuvxyz123456789--0\nabcdefthijklmnopqrstuvxyz123456789--1\nabcdefthijklmnopqrstuvxy'

### i: 7, reading 100 chars, char 700 to 799, len(s): 100, total chars: 421
String = b'z123456789--2\nabcdefthijklmnopqrstuvxyz123456789--3\nabcdefthijklmnopqrstuvxyz123456789--4\nabcdefthij'

### i: 8, reading 100 chars, char 800 to 899, len(s): 100, total chars: 521
String = b'klmnopqrstuvxyz123456789--5\nabcdefthijklmnopqrstuvxyz123456789--6\nabcdefthijklmnopqrstuvxyz123456789'

### i: 9, reading 100 chars, char 900 to 999, len(s): 100, total chars: 621
String = b'--7\nabcdefthijklmnopqrstuvxyz123456789--8\nabcdefthijklmnopqrstuvxyz123456789--9\nabcdefthijklmnopqrst'

----------------------------------------------------------------------
Total output =
b'thijz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmnopqrstuvxyz123456789yz123456'b'789--68\nabcdefthijklmnopqrstuvxyz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmn'b'opqrstuvxyz123456789\xff'b''b''b''b'abcdefthijklmnopqrstuvxyz123456789--0\nabcdefthijklmnopqrstuvxyz123456789--1\nabcdefthijklmnopqrstuvxy'b'z123456789--2\nabcdefthijklmnopqrstuvxyz123456789--3\nabcdefthijklmnopqrstuvxyz123456789--4\nabcdefthij'b'klmnopqrstuvxyz123456789--5\nabcdefthijklmnopqrstuvxyz123456789--6\nabcdefthijklmnopqrstuvxyz123456789'b'--7\nabcdefthijklmnopqrstuvxyz123456789--8\nabcdefthijklmnopqrstuvxyz123456789--9\nabcdefthijklmnopqrst'
Total length = 669

Since the output of the Uno would be deterministic (it would do the same thing every time) the problem is in the way you are processing the data at the Python end. Look at the line numbers in the above list. They don't even start at 0.

PySerial's read function is blocking by default. - or it has a long timeout anyway

See amended answer.

The exact round value (640) every time suggests something more exact than a few characters getting lost every time though.

See even more amended answer.

My user does not have privileges to communicated with /dev/ttyACM0. Running with sudo is just temporary until I figure another way out.

See Changing permissions on serial port


text:
Stepper motor doesn't start immediately when i pressed the button
When I release my hand from the button on pin 2, the stepper motor takes at least few seconds to stop, but I want it stop immediately. here's my codes:
 #include <Stepper.h>

    const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
    // for your motor

    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    bool dir = false;
    bool power = true;

    void dir_pin() {
      if (!digitalRead(3)) {
        dir = !dir;
      }
    }//when the switch is being pressed
    //it condition would be different from last time

    void setup() {
      // set the speed at 60 rpm:
      myStepper.setSpeed(60);
      // initialize the serial port:
      Serial.begin(9600);
      pinMode(2, INPUT_PULLUP);//it is a easier way to using INPUT-PULLUP
      //cause you dont have to use a real resistor
      pinMode(3, INPUT_PULLUP);//why choose those two pins
      //cause for uno, the interrupt pin are pin 2 and pin 3
      attachInterrupt(digitalPinToInterrupt(3), dir_pin, FALLING);
      pinMode(A0, INPUT);
    }

    void loop() {
      int pwr = analogRead(A0) / 100;
      Serial.print("power:");
      Serial.print(power);
      Serial.print("  pwr:");
      Serial.print(pwr);
      Serial.print("  dir:");
      Serial.println(dir);
      while (digitalRead(2) == 0)
      {
        if (pwr) {
          myStepper.setSpeed(pwr);
          int pwr = analogRead(A0) / 100;

          if (dir) {
            //Serial.println("clockwise");
            myStepper.step(stepsPerRevolution);
            //delay(500);
          }
          // step one revolution in the other direction:
          else if (!dir) {
            //Serial.println("counterclockwise");
            myStepper.step(-stepsPerRevolution);
            //delay(500);
          }
        }
        else
        {
          myStepper.step(0);
        }
      }
      while (digitalRead(2) == 1)
      {
        pwr = 0;
        myStepper.step(0);
      }
      delay(10);
    }

Doesn't start immediately? (as in the title?) or Doesn't stop immediately? (as in the body?)

You tell it to move whole 200-step revolutions, so once it begins a revolution, it must continue.  At 60 RPM, that should be up to 1 full second after you open pin 2.   Depending on the analogRead(A0)/100, a full revolution could take much longer than 1 second -- maybe 5.86s to 6000s
If you want it to stop immediately, disregarding full revolutions, you could:
      stepsPerButtonpress = 1;

      ...

      if (dir) {
        //Serial.println("clockwise");
        myStepper.step(stepsPerButtonpress);
        //delay(500);
      }
      // step one revolution in the other direction:
      else if (!dir) {
        //Serial.println("counterclockwise");
        myStepper.step(-stepsPerButtonpress);
        //delay(500);
      }

Or you could reduce stepsPerRevolution to the fraction of steps you want to treat as a unit, and increase rpm proportionally.

source: Stack Exchange

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

sort: votes


text:
Arduino Mega with nRF24L01+ module
I am having trouble getting this module to work using the tmrh20 lib. I am using these modules with two arduino mega and a 3.3V external power supply. I also placed 10 uF in parallel with the modules power pin. I would really appreciate any comments or suggustions.
In the code below all I am trying to do is turn on a led.
Here are my pin assignment for both arduinos
CE -> 7
CSN -> 8
SCK -> 52
MOSI -> 51
MISO -> 50
IRQ -> unconnected
Transmitter
//#include <DigitalIO.h>
#include <SPI.h>
#include "RF24.h"
#include <printf.h>
RF24 radio(7,8);
const uint64_t pipe = 0xE8E8F0F0E1LL;
unsigned long msg = 375983;

void setup() {
    Serial.begin(115200);
    printf_begin();
    Serial.println("Transmitter");
    pinMode(9, INPUT);
    radio.begin();
    radio.setChannel(108);
    radio.openWritingPipe(pipe);
    radio.startListening();
    radio.printDetails();
}

void loop() {
  radio.stopListening();
  if (digitalRead(9) == HIGH)
  {
    while (!radio.write(&msg, sizeof(msg))){
      radio.write(&msg, sizeof(msg));
}
  Serial.println("Sending.....");
  }
  else {
    Serial.println("Awaiting Input....");
  }
  delay(500);

}

print detail report
STATUS = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
RX_ADDR_P0-1 = 0xffffffffff 0xffffffffff
RX_ADDR_P2-5 = 0x7f 0xff 0x7f 0xff
TX_ADDR = 0x0000000000
RX_PW_P0-6 = 0xff 0x7f 0xff 0x7f 0xff 0xff
EN_AA = 0xff
EN_RXADDR = 0xff
RF_CH = 0xff
RF_SETUP = 0xff
CONFIG = 0xff
DYNPD/FEATURE = 0x7f 0xff
Data Rate = 1MBPS
Model = nRF24L01
CRC Length = Disabled
PA Power = PA_MAX

Receiver
//#include <DigitalIO.h>
#include <SPI.h>
#include "RF24.h"
#include <printf.h>
RF24 radio(7,8);
const uint64_t pipe = 0xE8E8F0F0E1LL;
unsigned long msg;

void setup() {
    Serial.begin(115200);
    printf_begin();
    Serial.println("Receiver");
    pinMode(9, OUTPUT);
    radio.begin();
    radio.setChannel(108);
    radio.openReadingPipe(0,pipe);
    radio.printDetails();

}

void loop() {
   radio.startListening();
   digitalWrite(9, LOW);
  if(radio.available()){
    while(radio.available())
    {
    radio.read(&msg, sizeof(msg));
    Serial.println("Incoming...");
    delay(500);
    Serial.println(msg);
    }
  }
  else{
    Serial.println("No Msg");
  }
  radio.stopListening();
  Serial.println(msg);
  if (msg == 375983){
    digitalWrite(9, HIGH);
    Serial.println(msg);
  }
  delay(500);
}

print detail report
STATUS = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1 = 0x0000000000 0x0000000000
RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00
TX_ADDR = 0x0000000000
RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA = 0x00
EN_RXADDR = 0x00
RF_CH = 0x00
RF_SETUP = 0x00
CONFIG = 0x00
DYNPD/FEATURE = 0x00 0x00
Data Rate = 1MBPS
Model = nRF24L01
CRC Length = Disabled
PA Power = PA_MIN

UPDATE:
Transmitter PrintDetail
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0x00000000e1 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0x00000000e1
RX_PW_P0-6   = 0x20 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x02
RF_CH        = 0x6c
RF_SETUP     = 0x07
CONFIG       = 0x0f
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX

Results form tmrh20 Getting Started Example
First Arduino
Sent 8340224, Got response 0, Round-trip delay 547172 microseconds
Now sending
Sent 9889124, Got response 0, Round-trip delay 511072 microseconds
Now sending
Sent 11401920, Got response 0, Round-trip delay 43348 microseconds
Now sending
Sent 12446992, Got response 0, Round-trip delay 635580 microseconds
Now sending
Sent 14084352, Got response 0, Round-trip delay 1620788 microseconds
Now sending
Sent 16706968, Got response 0, Round-trip delay 1227548 microseconds
Now sending
Sent 18936340, Got response 0, Round-trip delay 145372 microseconds

Second Arduino
*** PRESS 'T' to begin transmitting to the other node

The second arduino is not printing anything on the serial monitor, no matter what I enter.

Bad wiring. Double, no, triple check the wiring and modules.

The output on both the transmitter and the receiver clearly state the nRF24 module are not properly connected and the SPI is not communicating with it.

(not enough point to comment, so here's a potential answer)
I had enormous troubles getting these things to work reliably.  I tried all kinds of caps over the power supply. In the end I went for a 1$ piggy back board that takes 5v input and regulates to 3.3V. It also has the right pin female header to fit the nfr nicely. Since then I've had no issues. I also did a bit of experimentation and found that the RX side was the side giving problems.

Number one reason they don't work is bad wiring, wrong CE/CSN or whatever and they don't work.

Well, in my case I checked the wiring several times. After obtaining the 3.3v boards, I did extensive testing to see what factor made the difference. My results are noted above. Whilst your mileage might vary, my tip for those still having issues is to try using these boards.

Yes that is one way. But it's easier to decouple with 1000uF electrolytic capacitor. Just as I did when I found my Mega's regulator noisy.

At first I tries this too, using different cap sizes, including 1000uF, but to no avail.I know that filter caps are often suggested, and maybe often work, but these boards did the trick for me.

Try these:

Set pin 9 on the TX side as a pulled-up input i.e. pinMode(9, INPUT_PULLUP);
Connect one end of the switch to GND and the other to pin 9. Then in your code, test for a button press like this: if (digitalRead(9) == LOW){...}
Use a byte array for holding the address instead of the 64-bit int you're using.
Remove the stopListening() call in your RX loop(); there is no need for it since all its doing is receiving.
Remove the 500 ms delays in the RX loop() just in the unlikely case that its causing you to lose bytes

I have implement the changes you suggested. Still does not work.

@guow3 any changes in printDetails()? Update your post if there are any changes. I also forgot to include something in my answer. Editing now...

Only the transmitter printdetail report changed. The receiver remained the same.

@guow3 have u tried using the library examples? If they work, then modify them to send your long integer instead

Updated. Note the transmitter - > first arduino, Receiver -> second arduino

I hope you are using the example as it is. Just one small change: look for the variable radioNumber near the top in the example. Set it to 1 in one Arduino and to 0 in the other Arduino. Then try again. Update your post with any new results.

I have tried this already. Thanks for your efforts and suggestions.

The output on the receiver clearly states the nRF24 module is not properly connected and the SPI is not communicating with it.

That can be caused by poor power too. But bad wiring is common too.

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


text:
How to program arduino due without arduino ide
Is it possible to program the Arduino Due without the Arduino IDE? Is there a standalone program that can be downloaded, and be used to upload a .bin file (which has already been generated from the arduino IDE) to the Due? Any guidance appreciated.
I read about SAM-BA programmer, downloaded it but double clicking the .exe file does nothing. Something seems to open but it disappers.

The standalone program for most arduinos is avrdude: http://www.nongnu.org/avrdude/
However, for the Due, it is BOSSA:

Unlike other Arduino boards which use avrdude for uploading, the Due
  relies on bossac.
   -- Arduino Due Overview

thanks. Do you know if this one can upload the code via the native USB port? or does it need to have a jtag port?

It can use the USB port.  avrdude is the program the IDE uses to do its stuff.

Err… are you sure it's avrdude? The DUE features a SAMX ARM microprocessor, not an AVR.

I was wrong.  Edited.

Usually when on opening a program you get a console that pops on, it means that this program is meant for commandline usage and not CLI.
You should open a terminal, cd in the downloaded .exe directory, and then type that tool's name. You might want to try adding --help after the program's name to learn how to use it.
Another good idea is to look at what Arduino does by clicking on the verbose option in the preferences. Then you'll be able to copy/paste the command call and modify it to upload the firmware blob you want.
Finally, if you look up "AVR SAMX upload tool windows" on google you might find a GUI wrapper for the command line tool.


text:
Can a KCPI-3101 be replaced with an Arduino?
I'm planning to use a KPCI-3101 Keithley with a computer to creat a DAS with a sensor to show the data on computer
can i replace the Card and computer with an Arduino?

can you elaborate more? what sensor are you trying to use? If you planing to only do trivial computations and sensor readings it may be good.

Geosig-ve53 is the seismic sensor

An Arduino's ADC cannot sample fast enough to sustain 225ksps over 16 channels. That equates to a total of 3.6Msps.  The Arduino can manage something like 120ksps in total.
That's not to say there aren't microcontrollers that can't do that kind of speed - there are.  The PIC32MZ, for instance, can run at 15Msps (although it's somewhat buggy still) and there are many other microcontrollers.
The main bottleneck though is in the communication between the microcontroller and the computer.  Regardless of the sampling speed of an Arduino the serial interface is too slow for high speed sampling. Even at its practical maximum of around 2Mbps it gives you 200000 bytes per second, which with 2 bytes per sample would be 100ksps maximum throughput, not taking into account any protocol overheads.
So that's where having a PCI card is a big advantage. A 32-bit (or even 64-bit on PCI64) 66MHz direct channel to the CPU means you can shift considerably more data. And having the computer perform DMA access means that smooth data transfers without the CPU needing to be involved can be performed.

You can't replace the KPCI-3101 Keithley's 16 channels of 12 bit 225kS/s with an Arduino.


text:
Can I connect an Arduino GSM Shield directly to a PC?
Is it possible to communicate with and use the GSM shield directly from the computer, without using an arduino board?

You can connect a https://www.arduino.cc/en/Main/ArduinoGSMShield to your computer with a USB-TTL serial cable, but you need to make sure you supply enough 700-1000ma to drive the GSM when it is transmitting.

Power
  It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use.

thanks. A follow up: I'm assuming I wont be able to use the existing Arduino libraries (gsm, softwareserial). Do you know of any that I could use?

@sferaud A GSM shield is usually be controlled as a modem using AT commands. You don't need "libraries" to make an operating system control a modem. You may need an "application" or maybe a "driver" but never a "library".

Actually that depends a bit if you want the operating system to treat the modem as a general purpose network interface, or if you want to use it more explicitly, similar to how it would be used by an Arduino.  In the latter case library code (maybe even Arduino stuff backported to processing?) could be an option.


text:
What variables to declare for controlling a motor with high power motor controller
I was getting started with programming a motor controller with the Arduino Uno, in this case it's a mega motor shield (the motor driver shield I'm using).
The problem I have doing this is that I'm not sure what variables to use for the motor which is connected to two outputs labeled MA and MB.  I used motorValue to set the speed previously and used motorPin for writing the speed with the Arduino and a breadboard, but I'm not sure what to use in place of that for the motor being connected to the driver shield outputs.

Do you care about both direction and speed?

Variables are just names assigned to numbers. The names, as far as your program is concerned, are completely meaningless.
It's the numbers you assign to the variables and, more importantly, what you do with those variables that is important.
Your shield seems to have jumpers to select what I/O pins perform which function, so you just need to write the software to control the chosen I/O pins in the right way.


text:
Read ISO/IEC 14443B (NFC Type B) with PN532
I bought a PN532 from Elechouse (documentation here) because I need to read IDs from Type B NFC cards.
My problem is that even if they say the hardware supports Type B, the official libraries an examples they provide are not made to.
I have not problem reading Type A cards, but nothing happends when I tap Type B cards.
After long searchs on internet I found that absolutely every PN532 sellers have chosen to support only Type A cards in their libraries because according to them, a librari supporting both types would have taken too much space in Arduino's memory.
So today my problem is as simple as that: how to read Type B NFC cards using PN532 on an Arduino UNO?
I'm a bit new in Arduino so after many hours of searching and trying I couldn't figure out how to do it.

Same problem even using libnfc
doesn´t work with that card, only recognizes it
i read that it could be an antenna problem, because of the elechouse pn532.
I´m going to try to made an external antenna

We eventually gave up after many attempts, even involving other developpers, turned out the protocol was quite specific, in the end we used smartphones with NFC capability that could read it.

I dont have an exact reply but
1) are you certain the other tags are type b?
2) hace you tried connecting the reader using a UART USB cable? You could use libnfc, to check if the reader works.
And going forward at commands FOR the reader are a good way to debbug.


text:
ESP8266 GET OR POST Request Timeout Error
i am using ESP8266 module serially with PC and i also tried it using uno
I am stuck at the following point
I am able to made connection to server but when i will send the following command
POST /test.php HTTP/1.1\r\nHost: 192.168.1.36\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 5\r\n\r\nb1=ON\r\n\r\n
every time i get the following server timeout error after 3 sec
+IPD,4,500:HTTP/1.1 408 Request Timeout
Date: Tue, 08 Mar 2016 14:10:07 GMT
Server: Apache/2.4.9 (Win64) PHP/5.5.12
Content-Length: 305
Connection: close
Content-Type: text/html; charset=iso-8859-1

408 Request Timeout

Request Timeout
Server timeout waiting for the HTTP request from the client.

Apache/2.4.9 (Win64) PHP/5.5.12 Server at localhost Port 80

4,CLOSED
And i am getting same issue whether i will use local server or online server

If you post the same string to your server(s) from your PC, bypassing the ESP8266, do you get the same error?

no through PC i m getting the repsonse from server

Try adding Connection: close\r\n to the header. Also remove the \r\n\r\n at the end. Lastly, are you using the correct length in AT+CIPSEND=...?

Try turning off your firewall.

yes i am sending the correct length


text:
how to detect the incoming message from sim800 GSM module
I am designing an motorcycle security system and I need to receive the message  from the user.Hence i need to detect the incoming message and read the number and data from the message

How does your question differ from http://arduino.stackexchange.com/q/2899/6628 ?

i am not using gsm shield i am using sim800

So you are looking for the specific codes or a library for receving SMSs on the SIM800?  Wiring? Code for parsing the messages?

yea, i need to first identify the incoming  message if it is received i need to the parse the phone number and content of the message


text:
Arduino millis() won't work
This is my program. The LED should turn off after four seconds.
int vraag = 7;
int gloeikaars = 5;
unsigned long previousMillis3;
boolean gloeistate = true;

void setup() {
    pinMode(gloeikaars, OUTPUT);
}

void loop() {
    int x = digitalRead(vraag);
    if (x == 0) {
        digitalWrite(gloeikaars, !LOW);
    } else {
        Gloeikaars();
    }
}

// *********************************************************************
// Gloeikaars aansturing
// *********************************************************************
void Gloeikaars() {
    unsigned long huidig = millis();
    digitalWrite(gloeikaars, !HIGH);
    if ((gloeistate == true) && (huidig - previousMillis3 >= 4000)) {
        huidig = previousMillis3;
        digitalWrite(gloeikaars, !LOW);
        gloeistate = false;
    }
}

Can someone help me because it won't work?

At the moment your code doesn't know when you turned the LED on - so how can it know when 4 seconds have passed?

you are doing pinmode with a function. How do you conclude millis doesn't work?

@Patrick, I'm also Dutch, but I code in English, not only does it spice up your English, it also works better when working with international people (or StackExchange websites).

(Dutch, to avoid language barriers) Patrick, het is beter om je programma ook in het Engels te schrijven, zo kunnen internationale collega's ook je programma lezen/begrijpen (of mensen op stack-exchange).
Je vertelt er namelijk ook niet bij dat je een "glowing-candle" probeert te maken, wat uiterst interessant kan zijn voor mensen die je code proberen te begrijpen. Over het algemeen zijn vragen als: "Dit is mijn code, het werk niet" ook geen goede vragen. Beschrijf wat je probeert te doen, welk gedrag je verwacht en wat er gebeurt (dat niet zo zou moeten zijn).

Your previousMillis variable is never set.  Two changes:
In setup:
...
previousMillis3 = millis();
...

In loop:
...
previousMillis3 = huidig;
...

Not needed in setup, as both the millis() counter and previousMillis3 are initialized to zero.


text:
In Linux how do I start up Atmel Studio
I am using Linux Fedora 20. In order to compile C programs for the Arduino, as described in the book "C Programming with Arduino" by Warwick A Smith, pub by Elektor, I have downloaded and untarred/unzipped "avr8-gnu-toolchain-3.5.1.1671-linux.any.x86.tar.gz". That's as far as I can get. Please how do I proceed from this point? Is there anything else I need or should have done?

What you have there is the compiler. If you want the IDE you should download and install the IDE.

You do not need atmel studio to do C development for the AVR - you can use any text editor or configurable IDE along with a toolchain such as avr-gcc (possibly what you just downloaded).  You can even "borrow" the version of avr-gcc (and if you like, also avrdude) installed by the Arduino IDE.

https://mil.ufl.edu/374/docs/Install_Atmel_Studio_7.0.pdf :
Note for Mac and Linux Computer Users
If you have a Mac (i.e., a Macintosh computer from Apple) or if you use Linux, you will need an alternate Windows installation
or you will need to install a Windows virtual machine in order to then install and run Atmel Studio.
We suggest that you install
Boot Camp (free and the best); Parallels (not free) or possibly VMware (not free) may also work. UF offers free copies of
Windows 10 Software.
We do not recommend Virtual Box. Wine is another alternative, but this has not been verified to work.
(Note: My best students use Boot Camp!)

Why not VirtualBox?  Any specific reason?

Atmel Studio is a windows only product.
The only way to run it on linux is in a virtual machine running windows.

See http://www.atmel.com/tools/ATMELAVRTOOLCHAINFORLINUX.aspx

De toolchain maar niet de studio. De toochain is puur commandline terwijl de studio eigenlijk microsoft visual studio is met een plugin.

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


text:
ILI9163C screen not working properly
I've just tried out my new TFT_ILI9163C display with TFT_ILI9163C library but I'm having an issue with it. The graphics has moved down (the "hello world" should be in the top left) and the leftover space looks like there was no signal. Can be seen in the photo.
What could be wrong?

Have you read the section entitled "BLACK, RED or ..." in your link above?

Arduino\libraries\TFT_ILI9163C_settings\TFT_ILI9163C_settings.h
Change value here... #define __OFFSET 0//*see note 2

I had the same board and problem as you, what fixed is was changing the board setting to black even though it is phyiscally red.
Inside
Arduino\libraries\TFT_ILI9163C\_settings\TFT_ILI9163C_settings.h

Change
//  ---> SELECT HERE <----
#define __144_RED_PCB__//128x128
//#define __144_BLACK_PCB__//128x128
//#define __22_RED_PCB__//240x320

to
//  ---> SELECT HERE <----
//#define __144_RED_PCB__//128x128
#define __144_BLACK_PCB__//128x128
//#define __22_RED_PCB__//240x320

This worked but I'm unable to accept this answer. Is it due to lots of time having been spent since it was written?

I wrote my own driver for DisplayCore for that very same board a while back and found the exact same problem.
The issue is just the setting for the offset of the GRAM which it looks like there is a setting for in the library you are using.  Get that value right and you will have a proper display.

I see it - but what to do with that? I'm trying to make work the benchmark example. Copied the #define stuffs but no luck so far ...

Open the file
{sketchbook folder}/libraries/TFT_ILI9163C/_settings/TFT_ILI9163C_settings.h
in a text editor. You can find the location of the sketchbook folder in the Arduino IDE at File > Preferences > Sketchbook location.
Change:
#define __OFFSET      32

to:
#define __OFFSET      0

Save the file.
Upload the sketch to the Arduino board again.

This was what worked for me too. Although there is a white line in the right and bottom borders now and it wasn't there before, This line is not at the top and left borders.


text:
How do you control the amount of times the void loop loops per second?
int firstAnalogPin = 0;
int secondAnalogPin = 5;
int firstVal = 0;
int secondVal = 0;
void setup(){

  Serial.begin(9600);          //  setup serial

}

void loop(){

firstVal = analogRead(firstAnalogPin);
   // read the input pin

secondVal = analogRead(secondAnalogPin);
   // read the input pin

Serial.print(firstVal);

Serial.print("\t");

Serial.println(secondVal);

}

Basically, I want to know how to convert from the baud rate to the number of times loop() runs per second. How do I control the number of loop()s per second?

You don't. See the answers. Assuming you found that it looped (say) 1000 times per second, and then you added code to do something, knowing that, then the extra code would make it loop 900 times per second. So you allow for that, and then it loops 800 times per second. This is not the way to go about it.

If you don't need precise control, you can simple add a delay at the end of the loop.

how to set code while one loop is completed their work, then after the next loop is executed.

The number of times loop() runs every second depends on the time taken for the execution of the instructions within loop(). For instance, in your code, the time taken for one loop() is roughly equal to the time taken for the MCU to execute all the statements in loop() (more specifically, the time taken for each operation or function from call to return): in your case, the time taken for the Serial.print()s + the time taken for the analogRead()s (not considering any interrupts between statements).
That said, you generally don't want to control the interval between loop()s; I assume you actually want to control the interval between the execution of certain operations within your loop(). Say, you want to set the time between executions of analogRead(0) to 500 ms. This can be done like this:
#define INTERVAL 500   // time between reads
unsigned long lastRead = 0;

void setup(){
  Serial.begin(9600);          //  setup serial
}

void loop(){
  //....your other code....

  if (millis() - lastRead >= INTERVAL){  // if INTERVAL has passed
    val = analogRead(0);
    lastRead = millis();
    Serial.println(val);
    //...anything else
  }

  //...your other code...
}

With this code, you now have about 2 analogRead samples every second. Of course, this is only useful if loop() runs faster than your chosen interval. If there are function calls, or any operations otherwise, in loop() (within or outside the IF block) that always take more time than your interval, then this code would serve no purpose.

If your goal is to control how often the sensor is polled and printed to SD card, I would suggest you check out Blink Without Delay https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay it would be a much cleaner way than trying to slow down the loop to a specified time.

Marcello Romani's SimpleTimer library was made for this kind of problem. You let loop() run as fast as possible but only maintain the timers and do other short tasks. The timer library runs your periodic tasks when necessary:
#include <SimpleTimer.h>
SimpleTimer timer;         // creates a set of timers

// A timer call-back function - there can be more than one
void onTimer(void){
   ;   // do stuff here, keep it short
}

void setup(void){
   ;   // Serial.begin() and other setup

   timer.setInterval(1000L, onTimer); // set a 1-sec repeating timer
}

void loop(void){
   timer.run();   // updates timers, maybe calls a callback func
   ;              // whatever other loop code
}


text:
Stuck on uploading sketch via USB 6 pin
I'm just got a Galileo Gen2 and wanted to try a simple blinking-led. The firmware have been updated to 1.0.4. My problem is whenever I try to upload the code I get this error:
Sketch uses 83,775 bytes (0%) of program storage space. Maximum is 10,000,000 bytes.
...
echo "Sending Command String to move to download if not already in download mode"
echo "~sketch downloadGalileo" > $tty_port_id

Deleting existing sketch on target
#Move the existing sketch on target.
echo "Deleting existing sketch on target"
"$fixed_path/lsz.exe" --escape -c "mv -f /sketch/sketch.elf /sketch/sketch.elf.old" <> $tty_port_id 1>&0
Login timed out after 60 secondsPoky 9.0.2 (Yocto Project 1.4 Reference Distro) 1.4.2 clanton /dev/ttyS1clanton login:`

The answer was simply that 6-pin are not designed for uploading sketches. Instead use the micro-USB port to upload sketches.


text:
Arduino Timer Button
I am wandering how I would make it so the arduino uno will start a timer when button a is pressed and send "Start" or "Begin" or something like that to the console window. after the timer has started when button b is pressed it will mark the time from start of the timer and put it in the console window. After the timer has started when button c is pressed it will mark the time from start of the timer and put it in the console window. So on and so forth until button e, when button e is pressed i need the time to get logged in the console and they say "End" or "Stop" or something and then pause the sequence until I restart the board. This is for a school project and my only issue really is how to log the times On a timer loop persay.

What should happen if any of b-e are pressed while timer isn't running?

+jwpat7 Preferably Nothing. If anything just say something in the console to dis regard it.

Also, My buttons (I dont know if there is another way) are connected all to 5V and the other end (Through the Switch) goes to say for example Digital Pin 9. And then the next to DP 10. So on.

Ordinarily, posters are expected to say what they've tried so far, and to show the code they've written.  However, with a problem as difficult as this one, it seems reasonable to illustrate a complete program.
Note, this program assumes that one side of each button goes to Ground and the other side goes to a digital pin with its input pullup turned on.  (If you connect one side to +5V instead of to ground, you will need additional circuitry to sense button presses.)  The digital pins that are used are selected by changing the values swA, swB, and so forth, in the third line of the program.
//  jw - 8 Mar 2016 - Program for buttons demo
// Ref: http://arduino.stackexchange.com/questions/21590/arduino-timer-button
enum { swA=8, swB=9, swC=10, swD=11, swE=12}; // Switchbutton lines
enum { nSwitches=5 };
byte buttonPins[nSwitches]={swA, swB, swC, swD, swE};
byte buttonBusy[nSwitches]={  0,   0,   0,   0,   0};
unsigned long startTime;
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
  // Note, this code assumes one side of button goes to Ground
  // and other side to a digital pin with its input pullup turned on
    pinMode(buttonPins[i], INPUT_PULLUP);
  Serial.begin(115200);
  Serial.println("Program begins");
}
//--------------------------------------------------------
void doButton(byte b) {
  char *blabels[] = {"A, Start", "B", "C", "D", "E, End"};
  if (digitalRead(buttonPins[b]) && !buttonBusy[b]) {
    // The b'th button has freshly turned on.
    unsigned long now = millis();
    if (b>0 && !buttonBusy[0]) // To ignore B-E if A isn't on
      return;
    buttonBusy[b] = 1;
    if (b==0) startTime = now;  // Button A resets timer
    Serial.print("Button ");
    Serial.print(blabels[b]);
    Serial.print(" at time ");
    Serial.println(now-startTime);
    if (b==nSwitches-1) {   // Last Button ends timing, restarts cycle
      for (byte k=0; k<nSwitches; ++k)
        buttonBusy[b] = 0;  // Clear all the busy-flags
    }
  }
}
//--------------------------------------------------------
void loop() {
  for (int b=0; b<nSwitches; ++b)
    doButton(b);
}

Edit: Note that triggering messages on button-release instead of button-press would be relatively easy if buttons didn't bounce.
Before explaining that, let's look at why the above code should work.  Assume the cycle (buttons A and later E getting pressed, and possibly some of B, C, D too) lasts at least a couple of seconds.  Assume we have ordinary button hardware, and that contacts can bounce for several milliseconds at each make or break.  When you press a button the Arduino sees a lot of pin-turning-on events, eventually settling at pin-is-on.  When you release a button the Arduino sees a lot of pin-turning-off events, eventually settling at pin-is-off.  And finally, assume each button press is long enough that at least one digitalRead() happens while contacts are closed.
Under those assumptions, the very first time in each cycle that we see a given button closed, we know that button has just been pressed.  Also, we can plausibly expect closure of button A to register before closures of other buttons, and can expect the closure of E to register after that of other buttons.  So we can ignore bounce.
On the other hand, with on-release triggering we need to distinguish whether a pin-turning-off event is due to contact bounce of a button just pressed, or is actually part of a button-release bounce sequence.
Here's a method worth considering if you want to implement trigger-on-release:
 • First, add a delay(1) call, in loop().  This will make the code timing less processor-dependent, so it can run on a 48- or 72-MHz system as well as on 16-MHz Unos.
• Each time you detect that button b is on, execute buttonBusy[b] = 40 to start (or restart) a 40-ms timeout.  That is, while a button is held down, we keep setting its timeout to 40.  (40 ms may be overly conservative.  20 ms should work ok with most switches, and 10 is ok with a lot of them.)
• When you detect that button b is off,
 • if buttonBusy[b] is zero, do nothing.
 • if buttonBusy[b] > 0, then decrement buttonBusy[b] and test if it now is equal to 1.  When it's equal to 1, regard b as released, so do its action.

+jwpat7 This suits me perfect! Thanks! But one question. How would I make it so on button release it does this (all buttons are pressed and trigger when released. ) (For my personal Knowlage. ) THANKS!!

See edit re that


text:
why does it use A0 to define analog pin 0 in some case and why use 0 directly?
https://www.arduino.cc/en/Tutorial/AnalogInput
https://www.arduino.cc/en/Tutorial/Knob
For first line of both examples(not in comments), it define the same pin, analog pin 0, but they use different values. why and can use A1, A2, etc. to define other analog pins?

The answer is in the source code. Keep in mind that for this answer, I'm assuming you have a standard Arduino Uno. For other Arduino platforms the values are different but the situation is the same.
If you look at the analog pin definitions in hardware/arduino/avr/variants/standard/pins_arduino.h, you'll find these lines:
static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
...

Which tells you that if you call analogRead(A0), it is equivalent to calling analogRead(14). So, really, the question is "How can calling analogRead(0) work?"
The answer to that is in hardware/arduino/avr/cores/arduino/wiring_analog.c. If you wade through the defines, you'll see that at the top of analogRead, there is the following code:
if (pin >= 14) pin -= 14; // allow for channel or pin numbers

The result is that passing either 0 or A0 results in 0 being used in the analogRead code.

You can use 0 to 5 for analogRead of pins A0 to A5. However if you want to do digitalRead or digitalWrite on those pins then you have to use A0 through to A5 in order to avoid confusing them with the digital pins 0 to 5 (on the other side of the board).

can use A1, A2, etc. to define other analog pins?

Yes.


text:
IOt application example Error
I have downloaded code from below linkLink of code. I am trying test code from below. I am getting warning for below code.I couldnot able to find how to sort out
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

/* ------------------ */
/* SKETCH CREDENTIALS */
/* ------------------ */

const char *deviceId     = "<D56debb6351d9d4e74e000015>";             // * set your device id (will be the MQTT client username)
const char *deviceSecret = "<Y4h+R1NRAxrhFciRhtHLj66ERSv8RExu>";         // * set your device secret (will be the MQTT client password)
const char *outTopic     = "devices/<D56debb6351d9d4e74e000015>/set"; // * MQTT channel where physical updates are published
const char *inTopic      = "devices/<D56debb6351d9d4e74e000015>/get"; // * MQTT channel where lelylan updates are received
const char *clientId     = "<CLIENT-ID>";             // * set a random string (max 23 chars, will be the MQTT client id)

/* ------------ */
/* SKETCH LOGIC */
/* ------------ */

/* Server settings */
byte server[] = { 178, 62, 108, 47 }; // MQTT server address

/* Sample payload published to lelylan */
/* The id is the status property id of the basic light /*
  /* http://lelylan.github.io/types-dashboard-ng/#/types/518be107ef539711af000001/ */
const char *payloadOn  = "{\"properties\":[{\"id\":\"56debb6351d9d4e74e000015\",\"value\":\"on\"}]}";
const char *payloadOff = "{\"properties\":[{\"id\":\"56debb6351d9d4e74e000015\",\"value\":\"off\"}]}";

/* Ethernet configuration */
byte mac[] = { 0xA0, 0xA0, 0xBA, 0xAC, 0xAE, 0x12 };
EthernetClient ethClient;

/* MQTT communication */
void callback(char* topic, byte* payload, unsigned int length); // subscription callback
PubSubClient client(server, 1883, callback, ethClient);         // mqtt client

/* Pins configuration */
int inPin = 2; // button
int outPin = 4; // led

/* Button and led logics */
int state = HIGH;     // current state of the output pin
int reading;          // current reading from the input pin
int previous = LOW;   // previous reading from the input pin
long time = 0;        // the last time the output pin was toggled
long debounce = 200;  // the debounce time, increase if the output flickers

/* arduino setup */
void setup() {
  Serial.begin(9600);
  delay(500);

  Ethernet.begin(mac);
  Serial.print("Connected with IP: ");
  Serial.println(Ethernet.localIP());

  lelylanConnection();      // MQTT server connection
  pinMode(inPin, INPUT);    // button pin setup
  pinMode(outPin, OUTPUT);  // led pin setup
}

/* arduino loop */
void loop() {
  lelylanConnection();

  const char *value;
  reading = digitalRead(inPin);  // read the button state

  // if the input just went from LOW and HIGH and we've waited long enough to ignore
  // any noise on the circuit, toggle the output pin and remember the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == LOW) {
      Serial.println("[PHYSICAL] Led turned on");
      lelylanPublish("on");
      state = HIGH;
    } else {
      Serial.println("[PHYSICAL] Led turned off");
      lelylanPublish("off");
      state = LOW;
    }

    time = millis();
  }

  // effectively update the light status
  digitalWrite(outPin, state);
  previous = reading;
}

/* MQTT server connection */
void lelylanConnection() {
  // add reconnection logics
  if (!client.connected()) {
    // connection to MQTT server
    if (client.connect(clientId, deviceId, deviceSecret)) {
      Serial.println("[PHYSICAL] Successfully connected with MQTT");
      lelylanSubscribe(); // topic subscription
    }
  }
  client.loop();
}

/* MQTT publish */
void lelylanPublish(char *value) {
  if (value == "on")
    client.publish(outTopic, payloadOn); // light on
  else
    client.publish(outTopic, payloadOff); // light off
}

/* MQTT subscribe */
void lelylanSubscribe() {
  client.subscribe(inTopic);
}

/* Receive Lelylan message and confirm the physical change */
void callback(char* topic, byte* payload, unsigned int length) {
  // copu the payload content into a char*
  const char *json;
  json = (char *) malloc(length + 1);
  memcpy(json, payload, length);
  json[length] = "\0";

  // update the physical status and confirm the executed update
  if (String(payloadOn) == String(json)) {
    Serial.println("[LELYLAN] Led turned on");
    lelylanPublish("on");
    state = HIGH;
  } else {
    Serial.println("[LELYLAN] Led turned off");
    lelylanPublish("off");
    state = LOW;
  }

  digitalWrite(outPin, state);
  free(json);
}

Arduino: 1.6.6 (Windows 8.1), Board: "Arduino/Genuino Uno"
C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino: In function 'void
  loop()':
C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:77:26: warning:
  deprecated conversion from string constant to 'char*'
  [-Wwrite-strings]
   lelylanPublish("on");

                      ^

C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:81:27: warning:
  deprecated conversion from string constant to 'char*'
  [-Wwrite-strings]
   lelylanPublish("off");

                       ^

C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino: In function 'void
  callback(char*, byte*, unsigned int)':
IOT_Testcode:124: error: invalid conversion from 'const void*' to
  'void*' [-fpermissive]
memcpy(json, payload, length);
                           ^

In file included from C:\Program Files
  (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:25:0,
             from sketch\IOT_Testcode.ino.cpp:1:

c:\program files
  (x86)\arduino\hardware\tools\avr\avr\include\string.h:117:14: error:
  initializing argument 1 of 'void* memcpy(void*, const void*, size_t)'
  [-fpermissive]
extern void *memcpy(void *, const void *, size_t);
          ^

IOT_Testcode:125: error: assignment of read-only location '*(json +
  ((sizetype)length))'
json[length] = "\0";
            ^

IOT_Testcode:125: error: invalid conversion from 'const char*' to
  'char' [-fpermissive]
C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:130:24: warning:
  deprecated conversion from string constant to 'char*'
  [-Wwrite-strings]
 lelylanPublish("on");

                    ^

C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:134:25: warning:
  deprecated conversion from string constant to 'char*'
  [-Wwrite-strings]
 lelylanPublish("off");

                     ^

IOT_Testcode:139: error: invalid conversion from 'const void*' to
  'void*' [-fpermissive]
free(json);
        ^

In file included from C:\Program Files
  (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:23:0,
             from sketch\IOT_Testcode.ino.cpp:1:

c:\program files
  (x86)\arduino\hardware\tools\avr\avr\include\stdlib.h:305:13: error:
  initializing argument 1 of 'void free(void*)' [-fpermissive]
extern void free(void *__ptr);
         ^

exit status 1 invalid conversion from 'const void*' to 'void*'
  [-fpermissive]
This report would have more information with   "Show verbose output
  during compilation"   enabled in File > Preferences.

Kindly let me know how to resolve these warning

Most of those warnings are caused by the author not having a clue what they are doing. That code is so badly written and broken that you should just throw it away and start from scratch. I can't even begin to list the problems with it here.

This code was written and tested using an earlier Arduino IDE version, the author's upload of the source files happened over a year ago.
Within the Arduino 1.6.x branch the preprocessor and compiler behaviour have changed (among other things).
Older libraries will require an earlier Arduino IDE version (i.e. the 1.5.x branch) from https://www.arduino.cc/en/Main/OldSoftwareReleases#previous.
Additionally, we have to keep in mind that there are differences between Arduino.cc and Arduino.org. Those two projects split apart, their IDEs aren't equivalent any more.


text:
Brand new to Arduino, and can't even make an LED blink
So I'm going through Getting Started With Arduino. I skipped to making a LED blink when you press a button.
First I wrote the code, then I copied it directly from the .pdf I have, neither has worked.
The code is here:
// Example 02: Turn on LED while the button is pressed
const int LED = 13;   // the pin for the LED
const int BUTTON = 7; // the input pin where the
                      // pushbutton is connected
int val = 0;          // val will be used to store the state
                      // of the input pin
void setup() {
  pinMode(LED, OUTPUT);   // tell Arduino LED is an output
  pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
  val = digitalRead(BUTTON); // read input value and store it
  // check whether the input is HIGH (button pressed)
  if (val == HIGH) {
    digitalWrite(LED, HIGH); // turn LED ON
  } else {
    digitalWrite(LED, LOW);
  }
}

You need to have a resistor in series with that LED or you will damage it and/or your board.

The sketch uses pin 13, i.e. the built in LED; I think the one at the top right is unconnected.

@Nick: The book doesn't say that. It shows a drawing with the LED connected directly to pin 13 and ground.

Chuck the book out and get a different one. That's incorrect. Also, can you get the blink sketch to work? Disregard the button and just see if you can get an LED to blink on its own.

It looks like you are right. However that book was written years ago when the Arduino had a built-in resistor. Modern ones don't.

@uint128_t Yeah, blink makes the built in LED blink, which is progress. I'm starting to wonder if pin 13 does anything.

Do you have a multimeter? You can measure the pin voltage to make sure it's doing what you expect. And RSM is right, to make the switch work, you need to bridge your power rails.

Other than what what Nick Gammon said that you need the resistor from the board to led, as that will cause your microcontroller pins to get damaged.
The other possible problem is the two breadboards you have put together, the power rails have not been bridged between the two boards. This means that the switch is not providing any logical state to the microcontroller.
Also the only reason why the led is show in the book as a separate thing is that it is meant as an educational exercise to make you build something, the L led will do the same thing.

the power rails have not been bridged between the two boards - you are totally right. You can see from the red line on the board that the two sides are not connected.

In fact they are just two smaller boards which happen to be adjacent. Those power and ground lines won't be connected.

@NickGammon I think some believed the power is transfered wirelessly when placed adjacent to one another, which unfortunately many newcomers are ill informed about the way the things work. Its the second time I've seen this.

Nah, they just don't realize that the board doesn't run all the way through. I've had a few lengthy arguments about this in the past. :)


text:
How do I statements for the various conditions of this function?
I am still new to Aduino and I am trying to use a library's example sketch but I don't understand the following part of the code. I want to trigger an led when the "Pressed" condition is fulfilled. Pardon my ignorance.
if (b != ClickEncoder::Open) {
Serial.print("Button: ");
#define VERBOSECASE(label) case label: Serial.println(#label); break;
switch (b) {
  VERBOSECASE(ClickEncoder::Pressed);
  VERBOSECASE(ClickEncoder::Held)
  VERBOSECASE(ClickEncoder::Released)
  VERBOSECASE(ClickEncoder::Clicked)

  case ClickEncoder::DoubleClicked:
      Serial.println("ClickEncoder::DoubleClicked");
      encoder->setAccelerationEnabled(!encoder->getAccelerationEnabled());
      Serial.print("  Acceleration is ");
      Serial.println((encoder->getAccelerationEnabled()) ? "enabled" : "disabled");
      setMode = true;
       value = 0;
    break;
}

}

I'm no expert either, but I think this is just Displaying the status of the button out to the Serial port, whether it's been Pressed, Held, Released etc.

You will have to explicitely expand the case ClickEncoder::Pressed. So instead of
VERBOSECASE(ClickEncoder::Pressed);

you should write something like
case ClickEncoder::Pressed:
    Serial.println("ClickEncoder::Pressed");
    digitalWrite(ledpin, HIGH);
    break;

Of course then you'll have to turn it off then, but.. Well, that's another problem


text:
Mounting Arduino in an enclosure
I've decided to use Sparkfun's Pro Mini boards to make my project into a semi-professional product.
My first thought turned to enclosures - of which the entire internet seems to be bereft. If I ever DO see an enclosure, it's for the Uno sized board and costs about twice the price of the board, which seems incredible to me.
No matter, I have found a way to make quite good enclosures for the Pro Mini pretty easily and cheaply.
HOWEVER, the next problem is mounting the board inside the box. I would like to be able to mount it firmly to the base but in a way which allows it to be removed if necessary. Obviously, there's not a lot of scope for putting screws through the board. It occurs to me that anything which holds it would need to do so by gripping the edges or the corners. Is there such a thing?
If there's nothing that fits the bill, would the board be OK if I were to HOT GLUE it to the base of the enclosure?

What about using the pins to secure it? If you want to make it look "professional", just make a custom daughter board with the connections, make it so that you can firmly attach it (screws, plastic tabs, hot glue or even just rubber and a well-sized enclosure), then use the two pins rows to join them, so that you can unmount it easily

What do you mean by "The Pins"? The pro mini doesn't have any pins, just connection "holes", is that what you mean?

Ok, then one more step should be added (forgive me, I thought it was obvious): you should solder the pins to the pro mini like this image (of course without the serial connector - the six pins 90-degrees connector on the top layer)

@frarugi87 It probably WAS obvious to most people but not to me unfortunately. I'm not intending to use pins for the electrical connection - was just going to solder wires direct to the board as needed. However, I like the idea of using a few of the pins as "legs", I will explore that option if no-one offers anything better as an answer. Thanks for your help.

that's why I wrote it ;) and the comment was not sarcastic: I really meant "forgive me", because I really though it was and I understand it wasn't.. Anyway I suggest you to avoid soldering them directly on the board (this will limit your replacing easiness), but instead solder them on the base and then use just the pins for connection. If you want to avoid an extra board, you can use a perfboard or even just two female headers glued on the case and with the wires soldered to it.

I like the idea of the female headers as a holder, I'll experiment with this suggestion too. Thanks for all your help.

There are also little clips available, that grip a board by the edges, for example https://www.adafruit.com/product/1116 For boards with holes, I just hot-melt glue a few bolts to the case, sticking up in the right places, then put the board on and secure it with nuts; or use stick-on board clips like https://www.amazon.com/gp/product/B00R4ZT1FY

Seems like someone could make a good amount of money if they designed a plast slotted standoff that could hold the edges of the smaller like mini and nano boards into an enclosure. I’m kind of amazed I don’t see any at all.

One thing to be aware of, if your intention is to make this a consumer item is safety regulations. These tend to be quite specific, so you would need to have documentation to evidence your adherence to them. For example, UL certificates for the plastic enclosure you choose to use, RoHS certificates, etc.

What type of box?
Howmany times/how easily do you want to remove the Arduino Mini?
Hot glue
Hot glue is the way to go in many occasions.

It does not conduct electricity, so is pretty safe. (Please check your specific hot glue first)
It sticks quite well, for quite a time. You should also check if it's water resistant or fit for your target environment though.

But, it may have some side-effects:

It can get quite messy (which does not look really professional)
It's not that easily removable and has to be "re-glued" when you want to stick it back.
It might be too sticky (in a carboard box, you won't be able to just rip out the Arduino, withouth damaging the box).

You could use double sided tape, which might actually work fine. Or atleast better/neater as the hot glue.
Sticky velcro
A neat solution would be sticky velcro. You can easily attach, detach and re-attach the arduino to the velcro. It looks quite fancy and should hold well.
Again, you should check the specific velcro, it might not last 1000+ times of re-attaching (become loose or smh). But will be a good option overall.

Extra
You can use mint-boxes as an enclosure. But they're usually made of tin or another conductive material. Please take care and cover the back of your arduino (or box) with electrical tape, to avoid shorts.
Extra-extra, you should (for "replacability") add connectors or headers to your Arduino. Since soldering the leads directly will still give the need to un-solder or resolder your Arduino when replacing.
Note on making your Arduino project a consumer item
You might save yourself quite some money by using a barebones arduino. Or actually, an ATmega 328P chip. Which is around 3€.
These will be a little more difficult to program, but might also look more professional.
You can also enable "program protection" fuse bits, so that others can't download the code from your arduino/microcontroller.

Excellent answer, thank you @paul. I don't really intend to keep removing the Arduino from the box, but I'm sure I will need to, especially on the first ones. I like the idea of the sticky velcro - I actually have some of that in house already so will give it a try. The box is going to be made from plastic and I can easily make them exactly the size I need. The Pro Minis work-out to around the £2/3 euro cost too, so I'm not that concerned, especially if it's going to be harder to program - BUT, I am interested in keeping my code secret though so will investigate.

@Lefty, Pro Mini's are 10€ at more "official" shops. But indeed, for €3,- it's not really worth it. You could however use barebones arduino's to fit in even smaller enclosures or, on your very own PCB (if you need other circuitry). Programming should actually be the same as in the pro mini (IF you have a bootloader installed in your barebones implementation.).  (Basic) code protection involves disabling the "Fuse bits" for SPI download. Keywords to search will be: "flash protect, code download disable, fuse bits" etc.

thanks again. I will investigate the barebones option, purely because of the code-protection aspect, but size-wise, the Pro mini is well within the maximum size I can tolerate. I don't need any extra components and haven't made a PCB since I was at school - 40 years ago! So the pro-mini is ideal except for the code protection aspect. I paid £3.75 for the one I have bought so far, but the price drops significantly if I get 5, 10, or 20 at a time. Amazingly, it's about the cheapest part of the project.

@lefty the pro mini isn't that much different from a barebones arduino. If you have an icsp programmerer. You can actually enable read protection on a pro mini. But it won't work through serial-usb programming. By using an icsp programmerer, you don't even need the bootloader, thus have more program memory and others can't just upload arduino sketches through serial. Which might be usefull

More interesting stuff! I don't know about "ICSP" but I have an FTDI(?) programmer that I realised I needed for the Pro Mini. I used it successfully with the IDE. Looks like I have some more searching to do....

@lefty Arduino's have a bootloader that allows programming over serial. FTDI is an USB to serial converter. Bigger Arduino boards have these converters built on the board, even the Arduino Nano has this. Most Arduino's have/are an Atmega328P microcontroller, which are usually programmed with an ICSP programmer, since they do not have a bootloader.


text:
How to read data from Arduino with Raspberry Pi via I2C?
I have connected a Raspberry Pi 2 model B to an Arduino Uno via Bi-Directional Level shifter, from this BLOG:
Raspberry pi    GND    ----------   GND     Arduino
                3.3v   ----------   5v
                SCL    ----------   A5
                SDA    ----------   A4

I hope my I2C connection is correct.
And my Arduino is connected to an 8-Channel relay board.
Now I have written code in which I can control the relay board with the Raspberry Pi. For example, if I Press '1', relay 1 goes high.
Now I want to send data back from the Arduino to the Raspberry Pi in order to cross-check if relay 1 is high or not. If relay 1 is high then it should send some data back to the Raspberry Pi.
My Raspberry Pi code is:
import smbus
import time
# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

def writeNumber(value):
    bus.write_byte(address, value)
    # bus.write_byte_data(address, 0, value)
    return -1

def readNumber():
    number = bus.read_byte(address)
    # number = bus.read_byte_data(address, 1)
    return number

while True:
    var = input("")
    if not var:
        continue
    writeNumber(var)
    number = readNumber()

My Arduino code:
#include <Wire.h>

#define SLAVE_ADDRESS 0x04
#define RELAY1 9

int number = 0;
int state = 0;

void setup() {
    pinMode(RELAY1, OUTPUT);
    Serial.begin(9600); // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);
    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);
    Serial.println("Ready!");
}

void loop() {
    delay(100);
}

// callback for received data
void receiveData(int byteCount){
    while(Wire.available()) {
       number = Wire.read();
       Serial.print("data received: ");
       Serial.println(number);
        if (number == 1) {
            if (state == 0){
                digitalWrite(RELAY1, HIGH); // set the LED on
                state = 1;
            } else {
                digitalWrite(RELAY1, LOW); // set the LED off
                state = 0;
            }
        }
    }
}

// callback for sending data
void sendData(){
    Wire.write(number);
}

Now if I type 1, and due to some loose connection relay 1 doesn't go high, I want the Arduino to take data from the relay board and send it to the Raspberry Pi every time.
It will be great if someone can explain also that how it works.
Hope I was able to explain the problem. I have done lots of research but was not able to find some answer.
I am a beginner in Python so please help me.
Thanks in advance.

Character '1' is not number 1. Try "number == '1'.

That is not the question, The question is how to pass the value from digital pin of Arduino to rapsberry pi.

See my answer here about connecting I2C between a 3.3V device and a 5V device.

You might want to graduate to the pigpio library for the Pi side of this.
Here is where you can find examples of how it works.
here is a fun one that is like Wireshark - will show you the I2C traffic:
https://github.com/joan2937/pigpio/tree/master/EXAMPLES/C/I2C_SNIFFER
Here is the FAQ about I2C

Character '1' is not number 1. Try "number == '1'. – Mikael Patel Mar 9 '16 at 11:34


text:
How to use a common anode 7-segment, 4-digit display?
Please take this question as an example to (my own) answer below.
I've got an 7 segment, 4 digit LED display, but I don't have any idea on how to wire it.
I don't understand the difference between common anode/cathode, and I don't have 2 pins per LED, which is strange.
Quite recently, a question on a "7 segment 4 digit common anode" got deleted.
At that very moment I was typing an answer.
Though, I still want to share my answer with you, or the person who asked it.
Please verify/update my answer with more information.
Specifically, could someone add working code, I can't at the moment.

Just curious. Did you post a question so you can answer it?

There is actually an option for that. However, the comments in my question also tell the "background story". I was answering a question, that got deleted. And felt a need to post my answer neverthless. So yes, I did. But it's a valid method and I had the answer before the question. So it made sense to me. If you've got a really good question (and answer), I could only encourage you to do the same, as it might come usefull to someone at some point.

Just as a complement to Paul's answer, I wrote a short program to show
how to drive the 7-segment 4-digit display of his figure:

This is actually a common cathode display, so the program assumes that,
as well as the particular wiring of the figure. The interesting part is
the refresh_display() function, which should be called periodically.
The algorithm is as follows:

drive the 7 anodes with the appropriate signals for one of the digits
we want to show
set HIGH the output that controls that digit's cathode through the
NPN transistor
wait for 2.5 ms (for a refresh rate of 100 Hz)
set LOW the cathode-controlling output
move to the next digit.

It should be noted that the waiting is done without blocking the CPU, by
using the technique described in the Blink Without
Delay Arduino
tutorial. Here is the program:
const int NB_DIGITS     = 4;  // 4-digit display
const int FIRST_ANODE   = 2;  // anodes a..g on pins 2..8
const int FIRST_CATHODE = 9;  // cathodes, right to left, on pins 9..12

// Digits to display, from right to left.
uint8_t digits[NB_DIGITS];

// Set all the used pins as outputs.
void init_display()
{
    for (int i = 0; i < 7; i++)
        pinMode(FIRST_ANODE + i, OUTPUT);
    for (int i = 0; i < NB_DIGITS; i++)
        pinMode(FIRST_CATHODE + i, OUTPUT);
}

// This should be called periodically.
void refresh_display()
{
    // Our 7-segment "font".
    static const uint8_t font[10] = {
        //abcdefg
        0b1111110, // 0
        0b0110000, // 1
        0b1101101, // 2
        0b1111001, // 3
        0b0110011, // 4
        0b1011011, // 5
        0b1011111, // 6
        0b1110000, // 7
        0b1111111, // 8
        0b1111011  // 9
    };

    // Wait for 2.5 ms before switching digits.
    static uint32_t last_switch;
    uint32_t now = micros();
    if (now - last_switch < 2500) return;
    last_switch = now;

    // Switch off the current digit.
    static uint8_t pos;
    digitalWrite(FIRST_CATHODE + pos, LOW);

    // Set the anodes for the next digit.
    pos = (pos + 1) % NB_DIGITS;
    uint8_t glyph = font[digits[pos]];
    for (int i = 0; i < 7; i++)
        digitalWrite(FIRST_ANODE + i, glyph & 1 << (6-i));

    // Switch digit on.
    digitalWrite(FIRST_CATHODE + pos, HIGH);
}

/***********************************************************************
 * Example usage.
 */

void setup()
{
    init_display();
}

void loop()
{
    uint32_t now = millis();

    // Change the number displayed every second.
    static uint32_t last_change;
    if (now - last_change >= 1000) {
        digits[3] = digits[2];
        digits[2] = digits[1];
        digits[1] = digits[0];
        digits[0] = (digits[0] + 1) % 10;
        last_change = now;
    }

    refresh_display();
}

Paul provided a link to a tutorial on
Parallax
that suggests using the
Multiplex7Seg
Arduino library. That library is more general than the example code
above, as it does not make assumptions about the pins used. But the big
difference between the library and this code is in the way the timings
are managed:

The library is driven by the Timer 2 overflow interrupt. This should
provide a very steady timing, at the cost of having one timer
dedicated to this job.
The code above relies on the user calling refresh_display() often
enough. It doesn't require dedicated hardware resources, but it
doesn't play well with programs that take too long to loop(): it
won't like you calling delay().

This is why I like open-source stuff. You can share workload with the rest of the world and create something really nice. Which is then shared with the rest of the world again :) You can learn a lot from other developers and that knowledge will be persistent and not just hidden from everyone else.

I have a question in mind regarding Tranistor's base resistor value. I've a great problem with calculating resistor value. What is the reason for using 4.7K resistor in four 2N2222 transistor? If a single segment consume 10mA then there will be maximum 80mA current drawing for all segment including DP. If V(BE *sat) = 1.3v and I(B) = 15mA then 300ohm will be enough. Is there any wrong with my calculation?

@maruf: The minimum required I_B is the expected I_C divided by the minimum transistor gain. If you want 80 mA on the collector and expect a gain of at least 100 (it may be optimistic, I did not check the datasheet), then you need at least 80/100 = 0.8 mA on the base. Then the maximum value of the base resistor is the voltage drop across it (about 5 V − 0.7 V) divided by that current, or about 5.3 kΩ.

I'll try and take you through the complete basics of LED's etc.
As 4-digit 7-segment displays are a combination of multiple "LED techniques".
Wiring LED's
LED's, or Light Emitting Diodes, are one of the fun things of Arduino.
Essentially, they're easy to use, power them up and they'll light up.
They can be annoying, because they have some kind of polarity, meaning that they will only work when you wire them right. If you reverse positive and negative voltage, they won't light up at all.
Annoying as it is, it's also quite usefull.
Cathode vs Anode
On a traditional LED, the long lead is the (+), Anode.
The other lead being the (-) Cathode.
"Or, if someone’s trimmed the legs, try finding the flat edge on the LED’s outer casing. The pin nearest the flat edge will be the negative, cathode pin." - Sparkfun
Source: https://learn.sparkfun.com/tutorials/polarity/diode-and-led-polarity

Basic wiring
I'm not sure if this is correct, since I ripped the image from the internet.

Wiring an LED is quite easy, the Anode (+) connects to positive voltage, preferably through a current limiting resistor.
The Cathode (-) connects to ground (with a current limiting resistor, if you didn't have one on the positive side).
The current limiting resistor will avoid the LED from shorting out, damaging the LED or Microcontroller/Arduino.
Multiple LEDs, matrices, RGB leds
With multiple LED's you often have them with the positive side connected (+), "common Anode" or all connected to the (-) "common Cathode".
Basically it'll come down to this.

For a common cathode, you supply current to the pins that you want to have on.
For a common anode, you sink the current through the LED.
Multiplexing (multiple digit, 7-segments)
You should check out the tutorial of parallax: http://learn.parallax.com/4-digit-7-segment-led-display-arduino-demo

When you've got a lot of LED's, it's often smart to "multiplex" them. Usually you go through "groups" of LED's rapidly, so that it looks like they're all on at the same time.
Usually you sink current from a column of LED's and supply current to individual LED's of a row.
Or, you supply current to a column of LED's and sink current from individual LED's of a row.
So that you can choose which column to activate, and which LED's of that column to light up. Changing these columns/rows rapidly will enable you to control multiple LED's with a lot less pins.
There even are display controllers for this, if you don't want to take care of the switching in your software.
So when you have a 4 digit, multiplexed 7 segment, common anode
The diagram will be more like this:

http://www.mytutorialcafe.com/Microcontroller%20Application%20C%207segmen.htm


text:
RF24 + High speed pwd
I'm using the arduino to generate a 100kHz pwd using timer 1
void setup() {
  // put your setup code here, to run once:

   // Timer 1 Fast PWM mode *toggling* OC1A at 50kHz with *two* OCR1A counts
   // And 7.32 bits 0-159 PWM on OC1B at 100kHz
   // Output on OC1B
   // Set at TOP, Clear at OCR1B
   // WGM =15 0b1111

   DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;
}

void loop() {
  // put your main code here, to run repeatedly:
  OCR1B = 160/4 -1 ; // 25% duty cycle.
}

I used this to test the modules:
Receiver
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int LED1 = 3;

void setup(void){
 Serial.begin(9600);
 radio.begin();
 radio.openReadingPipe(1,pipe);
 radio.startListening();
 pinMode(LED1, OUTPUT);}

void loop(void){
 if (radio.available()){
   bool done = false;
   while (!done){
     done = radio.read(msg, 1);
     Serial.println(msg[0]);
     if (msg[0] == 111){delay(10);digitalWrite(LED1, HIGH);}
     else {digitalWrite(LED1, LOW);}
     delay(100);}}
 else{Serial.println("No radio available");}}

Transmitter
#include  <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int SW1 = 7;

void setup(void){
 Serial.begin(9600);
 radio.begin();
 radio.openWritingPipe(pipe);}

void loop(void){
 if (digitalRead(SW1) == HIGH){
 msg[0] = 111;
 radio.write(msg, 1);}}

I'm using this library
https://github.com/TMRh20/RF24
And it works ok, now first issue is that both, RF24 and the pwm
are using the pin 10 but the library allows you  to change it, so now I'm using pin 7 instead. I tested it again and still works fine.
But when I add the lines at the setup to use the pwd  the communication doesn't work
   DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;

I try line by line and the issue is here:
TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
When setting the prescaler at 1.
Which is the dependency of the RF24 on this timer? and which options to I have to make it work
EDIT.
Now I'm using pins 6 and 7 for CE and CS
Also removed  "| bit(COM1A0) " form the register  setting
Still doesn't work
I've this
void setup(void)
{

  /// RF settings

  Serial.begin(9600);
 radio.begin();
 //radio.openReadingPipe(1,pipe);
 //radio.startListening();
 pinMode(LED1, OUTPUT);

 /// end RF settings

  //// pwd settings
 DDRB |= bit(DDB1) | bit(DDB2);
   OCR1A  = max_count;       // 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;
   TCCR1A =  bit(WGM11) | bit(WGM10) |  bit(COM1B1); // bit(COM1A0) | Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   TCNT1 = 0 ;

  ////
 }

If I put the settings for the PWM before the settings for the RF24 then the PWM doesn't work, the RF settings at first the the communications doesn't work.
radio.begin() must be overwriting the registers but I haven't found how.

The "TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B"    line set up the PWM to control both the OC1A and OC1B pins, which are 9 and 10 on an Arduino Uno,  Is Pin 9 interfering with the RF24 per the "RF24 radio(9,10\7);" line?    If so, you could take out the " | bit(COM1A0)" portion to free up pin 9 for digital IO rather than PWM.

Maybe the fact that you have pin 10 as PWM is messing up the SPI module that requires pin 10 to be set to output for SPI to operate?

@DaveX I try it, still doesn't work

@Majenko if the RF24 doesn't need to use pin 10 how can I check if the SPI library is causing the issue

The nRF doesn't need pin 10 but the SPI does. It's a hardware thing. If you can run the pwm without pun 10 it may prove or disprove it.

Maybe doing 100kHz PWM with timer2 instead of timer1 would be good.  The registers look similar to timer1, but they are only 8 bit, so you can't go bigger than 255 in the compare and count registers. The prescaler would be the same, and the timer controlled pins would be D11 and D3:
  //// pwm settings for 100kHz on Timer 2
  //// Toggle OC2A/D11/PB3 at 50kHz, PWM OC2B/D3/PD3 at 100kHz:
   DDRB |= bit(DDB3); //Enable output
   DDRD |= bit(DDD3); //Enable output
   // WGM2x=0b111 for fast PWM with TOP=OCR2A
   // COM2Ax=0b01 for toggle OC2A at OCR2A
   // COM2Bx=0b10 for set@bottom-clear@match_OCR2B PWM
   TCCR2A =   bit(WGM21)  | bit(WGM20)
            | bit(COM2B1)  // PWM on OC2B
            | bit(COM2A0); // Toggle OC2A
   TCCR2B =   bit(WGM22) | bit(CS20);  // Set /1 prescaler
   OCR2A  = 159;       // 16000000/(PreScaler *Ftimer)-1
   OCR2B  = 10;        // 6.25% PWM
   TCNT2 = 0 ;

I haven't tested this on an Uno/Atmega328P, but it looks reasonable per the datasheet (p153-157).
If you don't want both the 50kHz toggle and 100kHz PWM outputs, (as in your posted code,) you could disable one or the other and adjust the frequency as needed.


text:
How to write modular code for arduino?
I would like to create a program with separated modules, is this this possible using Arduino IDE?

Also see https://arduino.stackexchange.com/questions/348/how-to-organize-my-arduino-projects-structure-for-easy-source-control

While you can create your own libraries for the Arduino, a simple way to make reusable code is to create a header (.h) file that contains the code you would like to make reusable.
Specifically, in the Arduino IDE create a new tab with some name foo.h, and in your main tab, add #include "foo.h" at the top of your code. What this does is essentially copy paste the code from foo.h into your code during the build process. While simple in execution, it really helps organize more complex code, and in your case, helps with reusing code.
You can alternativly use "Normal Arduino code files (no visible extension), C files (.c extension), C++ files (.cpp), or header files (.h)."
And one extra note to help you - the header files do not have access to some of the typical Arduino commands and functionality, such as delay() or Serial unless you add #include "Arduino.h". However, for IDE versions less than 1.0, use #include "WProgram.h". This will give you access to those functions.

Arduino sketches can include Libraries (see https://www.arduino.cc/en/Guide/Libraries).
In order to work with the Arduino IDE, such a library is required to adhere to a certain folder structure and naming convention (as described in the above guide).
Other than that, it's similar to modularized code in any other language. The canonical language in Arduino libraries is C++.
Since a regular Arduino IDE installation already comes preinstalled with a multitude of libraries, you can take a look and go from there.
I recommend that you look through the example sketches (from the "Examples" menu option). Whenever you see an #include statement at the top of the sketch, you have a hint where to look next in order to gain a better understanding about the inner works.

The sketch code can be easily split into several files by creating a new tab (file) without file name extension or .ino (source). No need for #includes as the Arduino IDE combines these files for the build process.
For proper modularisation make a Library or see the link above for further information on using .h/.c/.cpp as modules.

I would like to create a program with separated modules, is this this possible using Arduino IDE?

the answer depends on your code.
writing modular code is mostly a thought process:
1) you have to design your code to a logic model: rather than setting an led on pin 2, you design your code to set a pin, use that code to set a pin specified as LED_PIN, and then define LED_PIN to be pin 2. With this approach, you can simply redefine LED_PIN in your new project to use the same code.
2) you have to design your code top-down: rather than start writing your code right away, break it down to logic blocks, design the input and output of each block so that they work together cohesively. this is the toughest part of writing modular code.
after that, breaking the code down to .c/.h files is a piece of cake.

Well.... The answers are interessting but depend on what JuanV is thinking about when he say "separated modules"...
For me, as an "old timer software dev", "separated modules" mean I build a central bloc of code (a nutshell) and the user download module which are automaticly "plugged" to the nutshell, expanding the feature.
A bit like a printer driver you add to your system, and which add feature for all software.
When I look at my past dev using this, I must admit I've some problems thinking of that on Arduino.
If you are looking for that you must think about various problems:
1) how to update? Maybe with an Android App getting the code from the Web and sending these data to the Arduino via Bluetooth. You can also think of adding a Wifi interface on the Arduino
2) where to store the new piece of code... It's seem you can write on flash "on the fly" but seems to be complicated
Due to this second point, maybe the easiest way would be to create a nutshell which will "interpret" data (so which read a kind of small script) and then you'll have just to send the data.
I suggest to have a look at the CNC made with Arduino. In most cases they use a  GCode interpreter. GCode is a descriptif langage for CNC machine. So the interpreter read the code and according to the code, send "orders" to the machine.
Maybe such a thing would be a good starting point.
On the other way, if what you call "modular approach" is just the way of building lib and re-use them, Lord Gonk answer is the way :)


text:
Arduino minimal power usage
I know there is a lot on this subject on the net but i cant seem to be able to join the dots together.
I am trying to make sensor system than can run for as long as possible if not indefinitely using an Arduino, and also to do so very cheaply. I have a £1 Arduino Nano clone that is running with sensor and alarm fine, but currently its runs off USB power from PC.
I have followed this guide to minimize power usage code side: https://www.openhomeautomation.net/arduino-battery/
And I have read that the Vin pin needs at least 7 volts to work properly, so 2 volts would be wasted in heat making a 5V level.
I have a 3.7V lithium cell 4300mAh so I thought I would need a step up boost module.
But it looks like the Nano can run using 3V. But the 3.3V rail is apparently made for external sensors, assuming I want a mixture of cheap/simple and high efficiency. Can i just hook a 3.7 lipo into the 5V rail of the Nano and a 5V solar panel (with diode) up to same point? Will this kill my Nano?
If not, is it worth stepping the 3.7V down to the minimum the Nano can run with?
Underclocking is not an issue, it essentially wakes up every hour reads 5 sensors and if all is well (99% of the time) goes back to sleep for an hour.
Linear voltage regulators seem to burn the excess voltage as heat. And then what will happen when the battery dies off and is no longer 3.7 volts? And if my solar panel is around 5V in good light, if its partly shaded and only has 3.5 volts for example it would not charge my lipo to 100% capacity. Should I step up DC/DC boost the panel voltage to charge my cell.
Guidance please.

Don't use an Arduino! The Atmega328 (the microcontroller the arduino is built around) runs with 2.7-5.5V, so you can hook it directly to the lithium cell. The arduino board is essentially a PCB with an Atmega328, voltage regulators and a serial programmer. You neither need nor want to power the latter two, so use a plain Atmega328. You can still use the Arduino IDE and software.

Nick Gammon's guide to power management on Arduinos: http://www.gammon.com.au/power

I have to agree with @Olin Lathrop about the fact that Arduinos are not really tuned for your goals.
I am doing microcontroller projects for like 20 years, and I found the nanowatt PIC microcontrollers offering the best price/performance/tricks ratio if you need to have something running on batteries for a seriously long time (and has not too much to calculate). There we're talking about nanoamperes in sleep, and there are a lot more tricks you can consider.
You have chosen Arduino for a valid set of good reasons. But which Arduino please? They come with different CPUs and hardware!
If you go with Uno:

power your board directly by batteries, e.g. 3xAA batteries at the 5V pin to bypass power loss on the 5 V regulator (you can also give a try to feed power via the USB socket if you feel that more convenient)
remove the 3.3 V regulator (assume you don't need 3.3 V)
sleep a lot and sleep well, listen to @Nick Gammon and check his page about power saving

Then comes the minor tricks:

do not let any pin float. Before going to sleep, put all inputs to output. I.e. if you have a button input, change port direction to output and set to 0. (assuming that you don't need the button in sleep)
turn off not only all internal peripherals, but also external ones. For example, things like I2C temperature sensors may have remarkable 0.5 mA sleep current. The easiest thing is to power those from a port pin, and set the port to 0 before going to sleep.
turn off all pullups (and all inputs to outputs), don't forget the I2C as well. Although the bus will be idle, there is a serious leakage current (serious means microamperes, and you wanna go to the nanoampere range, right?)

Then if you want to go really to the hard parts:

throw away all hardware you don't need. The power checking comparators (I am referring to this schematics http://brittonkerin.com/annotateduino/arduino_uno_rev3_schematic.png), the USB interface chip altogether
throw away u1 (the 5 V regulator) - also has some leakage current

And the final steps:

I would check the electrolytic capacitors on the power rails, e.g. C2. These also have a leakage.
Although Arduino does not have suppressor diodes to protect anything from any voltage spikes, I have to emphasize that single high capacity unipolar and bipolar suppressor diodes may have a leakage current of 1 uA.

Note about underclocking: this is not necessarily a wise thing to do. It is true that on slower speed the CPU consumes less. However at slower speed the CPU has to stay awake much longer to perform the same tasks.

I found that if you need to perform some complex calculations (not just reading some sensors) it may make sense to switch to a higher CPU speed, and do the calculation in less time and go back to sleep more efficient.
On the other hand, if your CPU is awake just to wait for some sensor readings and just burning cycles while waiting, a slower CPU speed is more beneficial.

The off-the-shelf Arduinos are not suitable, because they have voltage regulators, power LEDs, etc. However the processor (Atmega328P) can sleep at 100 nA (with the watchdog disabled). I'm not sure the PICs are much better. 100 nA is pretty low, batteries discharge faster than that.

Interesting! I have no experience in low powering the Atmega328P, so I did some digging of datasheets.
ATMega328p
3V 4MHz = 1.7mA
5V 8MHz = 5.2mA
PIC18LF1xK50
3V 4MHz = 0.5mA
5V 24MHz = 4.7mA
Atmega power down mode, WDT disabled, 3V = 0.1uA
power down mode, WDT enablede, 3V = 4.2uA, PIC power down, WDT disabled, 3V 0.07uA
power down, WDT enabled, 3V 1.37uA max.
Doh, this formatting! So PIC is 70nA in sleep, and even if it runs with PLL at 24MHz, consumes less than a 8MHz Atmega328P. Of course we're comparing apples to oranges because of different architecture of the cpus.

Nevertheless, as Microchip has purchased Atmel, they're one family now! Time to develop the GRAND microcontroller now :)

So PIC is 70nA in sleep - well I won't quibble over 30 nA, which is all the difference is. It's hard to measure that anyway. as Microchip has purchased Atmel - uh oh.

I have a project along those lines. I am reading temperature, humidity, and light level and logging it, with a timestamp, to an SD card.
Schematic (click for larger image):

Photo:

It was designed with low power in mind. It runs from 3 x AA batteries which I think I have only changed once since I made it (in August 2013).
Also see my page about power saving.
I don't see any problem with running it directly from 3.7V - you would need to slow the processor down to 8 MHz (which I did anyway in that project).
The code (available here) compiles under the Arduino IDE.

Arduinos are for rapidly getting something going without having to know much about the underlying electronics and microcontroller.  As a result, some design tradeoffs were made for you, generally optimized for development simplicity.
You now have a different primary concern, which is low power consumption.  If that is truly important, then you have to design the system with that goal up front.  This means starting with the bare microcontroller, designing the electronics around it carefully to minimize power, and designing the firmware architecture to minimize high-power cycles and maximize sleep time.
You are asking where to strap the big engine on a Honda Civic to make a high performance racing car.  You can make a Civic higher performance, but to get really high performance you have to start with that goal from the beginning.

Then I guess my question is how to make my Honda Civic go as far as it can on one tank, given i'm not going to make a space ship. in sleep mode the biggest use of power is in the regulators. and thats kinda what the question was about. im not looking for the BEST MOST efficient solution in the world.  just some help to a guy who stuck some wire in an arduino and wants it to live for more than 2 days on a battery, if i get no sun, and how to make use of the panel so it will always help(if there is sun)