text:
Get servo to travel full length
Recently we purchased servos for use in an Arduino and began testing with servos. It turned out that the uSec for the servos differed from the online documentation and we had to find the min and maxes of the uSecs manually:
while (Serial.available()) {
    char c = Serial.read();  //gets one byte from serial buffer
    readString += c; //makes the string readString
    delay(2);  //slow looping to allow buffer to fill with next character
}

if (readString.length() >0) {
    Serial.println(readString);  //so you can see the captured string
    int n = readString.toInt();  //convert readString into a number
    Serial.print("writing Microseconds: ");
    Serial.println(n);
    myServo.writeMicroseconds(n);
    readString = ""; //empty for next input
}

The issue is that the servos don't travel the full 180 degree advertised price (more like 135-160) and that lack of angular distance is affecting performance of one of our products. The servos can even mechanically travel a noticeable distance farther than 180, but not "programmatically" farther even when given a larger PWM uSec value that the observed "max" PWM value

What I've found
I looked around and apparently there are "Servo Programmers" to calibrate endpoints and midpoints, but cost an arm and a leg. I find it strange that I would have to "program" my servos. I was part of an First (FTC) robotics team using tetrix/nxt electronic control systems, and never noticed a problem with uSec values or not getting the full range of motion using the same brand of servos I currently am now.

How can I perform a low cost, easy way to simply get the full range
  of motion I paid for?

what do they say about this where you bought the servos from? they get paid to give you that service?

This servo can operate 180° when given a pulse signal ranging from 600usec to 2400usec I have tried giving it more than 2400usec, but it is noticeably off from 180°.

do you have a logic analyzer? you might want to check the actual length of the pulse.

No we don't have a logic analyzer/oscilloscope, nor do we have the funding for one. I don't think the PWM would be incorrect becuase the problem is at longer PWM than shorter PWM. For example, manual implementation of Pulse Width Modulation: void loop() {   digitalWrite(pin, HIGH);   delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz   digitalWrite(pin, LOW);   delayMicroseconds(1000 - 100); }

This is an analog servo, so there is no endpoint calibration on the servo side. This type of calibration is for digital servos (which can be tuned) and controllers.
On the servo description page, they talk about a stretcher. This is a translation tool to help with old controllers:  usually servos have a narrower band: 1000us to 2000us for 0° to 180°. Therefore old controllers can only do 1000us to 2000us, and would fail to achieve full range with this servo, which requires 600us to 2400us
Also, note that RC servo input signal isn't really a PWM: duty cycle doesn't matter, only lengh of the pulse does.
Your servo doc says: 600us to 2400us for -90° to +90°, which correspond to what the Servo lib does by default according to its documentation. You should be fine. What are the results of a super simple sweep-like code? eg:
loop() {
  myServo.writeMicroseconds(600);
  delay(2000);
  myServo.writeMicroseconds(2400);
  delay(2000);
}

With super simple code, it doesn't travel full angular length. Using uSecs higher/lower than 600-2400 range doesn't do anything different.


text:
How do I count time in seconds?
I have a statement:

if(control > 100 && control < 130)
{

  //count time 30 seconds and open pin1 for 3 seconds.

}

How can I count 30 seconds and open a pin for 3 seconds?

Arduino measures time in millis() and delay() and in milliseconds, so to convert counts of time in seconds to milliseconds would be 1000x.

A non-blocking version is often needed as there is often other tasks to be performed during the wait. The "blink-without-delay"-pattern is a solution but unfortunately it becomes tedious to use with several time periods and logic.
The Timemark library helps abstract the pattern and hide a lot of the details. The below sketch uses two timemarks and a simple state-machine to help reduce complexity.
#include <Timemark.h>

Timemark turnOnWait(30000L);
Timemark turnOffWait(3000L);

enum {
  IDLE,
  TURN_ON_WAIT,
  TURN_OFF_WAIT
};
int state = IDLE;

const int pin = 4;
int control = 0;

void setup()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loop()
{
  ...
  switch (state) {
  case IDLE:
    if ((control > 100) && (control < 130)) {
      turnOnWait.start();
      state = TURN_ON_WAIT;
    }
    break;
  case TURN_ON_WAIT:
    if (turnOnWait.expired()) {
      digitalWrite(pin, HIGH);
      turnOffWait.start();
      state = TURN_OFF_WAIT;
    }
    break;
  case TURN_OFF_WAIT:
    if (turnOffWait.expired()) {
      digitalWrite(pin, LOW);
      state = IDLE;
    }
    break;
  default:
    ;
  }
  ...
}

Two timemarks are used for clarity. It is possible to use a single timemark and reinitiate it with a new time limit.
#include <Timemark.h>

const uint32_t TURN_ON_TIMEOUT = 30000L;
const uint32_t TURN_OFF_TIMEOUT = 3000L;

Timemark timemark;

enum {
  IDLE,
  TURN_ON_WAIT,
  TURN_OFF_WAIT
};
int state = IDLE;

const int pin = 4;
int control = 0;

void setup()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loop()
{
  ...
  switch (state) {
  case IDLE:
    if ((control > 100) && (control < 130)) {
      timemark.limitMillis(TURN_ON_TIMEOUT);
      timemark.start();
      state = TURN_ON_WAIT;
    }
    break;
  case TURN_ON_WAIT:
    if (timemark.expired()) {
      digitalWrite(pin, HIGH);
      timemark.limitMillis(TURN_OFF_TIMEOUT);
      timemark.start();
      state = TURN_OFF_WAIT;
    }
    break;
  case TURN_OFF_WAIT:
    if (timemark.expired()) {
      digitalWrite(pin, LOW);
      state = IDLE;
    }
    break;
  default:
    ;
  }
  ...
}

The Scheduler library allows the blocking version (delay) to be used. Non-blocking is achieved by context switching on yield() or delay(). Below is a rewrite using this style:
#include <Scheduler.h>

const int pin = 4;
int control = 0;

void setup()
{
  ...
  Scheduler.start(setupController, loopController);
}

void loop()
{
  ...
  delay(1000);
}

void setupController()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loopController()
{
  ...
  if ((control > 100) && (control < 130)) {
    delay(30000L);
    digitalWrite(pin, HIGH);
    delay(3000L);
    digitalWrite(pin, LOW);
  }
  else {
    delay(100);
  }
}

Cheers!

What you can also use is non-blocking code, where delay() would block for the 30s. My suggesting makes use of millis(), one could say similar to blink without delay code example.
Here is an example of what you could place in the loop:
//declared variable stuff here

if(control > 100 && control < 130 && !toggled_bit){

    toggled_bit = true;     //to control the timing section
    start_time = millis();
}
else if (!(control > 100 && control < 130)){
    toggled_bit = false;
}

if (toggled_bit){
        test1 = millis()
    if(test1 - start_time > 30000){

        digitalWrite(1, HIGH);
            short_wait = millis();
            // wait for 3s after fist time
                if(short_wait - start_time > 33000)
                    digitalWrite(1, LOW);
                    toggled_bit = false;
                }
        }
}

// other code here

The code sets a 'flag', toggled_bit, which is checked by the if() later on in the loop, also it sets start_time. It then checks if 30s has passed and then waits an extra 3s to turn the output off after being turned on. It then resets the toggled_bit.
This will also allow you to check or do other things while waiting.

Rearrange the Blink example:
if(control>100 && control<130)
{
  //**count time 30 seconds and open pin1 for 3 seconds.**
  delay(30000);             // wait for 30 seconds
  digitalWrite(1, HIGH);    // turn the LED on (HIGH is the voltage level)
  delay(3000);              // wait for 3 seconds
  digitalWrite(1, LOW);     // turn the LED off by making the voltage LOW
}

Well 30s equals 30,000ms and the arduino comes with a native function that counts in Milliseconds so the following code should work:
Time = millis();  //time passed before entering loop…
If((control > 100) && (control < 130))
{
While (millis() < Time + 30000) //counts to Thirty seconds
{
While (millis() < Time + 3000) // counts to three seconds
{
DigitalWrite(1,HIGH);
};};};

This way you can add some code in the while loops if u want to multitask.

source: Stack Exchange

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

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

sort: votes


text:
Dereferencing char into a struct
I am sending some data over an NRF24 link, using the RF24Network  library. So far I have only sent numbers, now I also want to send a string, so I have set up my payload struct as
struct payload_t {                  // Structure of our payload
   unsigned long data;
   unsigned long datatype;
   char sensorid[20];
   unsigned long counter;
};

As far as I do understand, I can not use string here, since I need to know the length of the data I am sending.
At the moment I am using sensors without an internal ID, so in loop(), I am calling:
 writeToNetwork(voltage,'v',"nosid",packets_sent++);

My writeToNetwork function is defined as
 bool writeToNetwork(unsigned long data,unsigned long type,char sid[20],unsigned long package){

and within that, I am setting up the payload with
 payload_t payload = { data,type,sid, package };

Which gives me an
 error: invalid conversion from ‘char*’ to ‘char’ [-fpermissive]

Clearly, I have no interest of the address the pointer is referencing, so I need to somehow dereference the sid - pointer to get my array into the struct. How can I do that?
Or am I barking up the wrong tree? I tried to transfer the id as a string:
#include <string.h>
bool writeToNetwork(unsigned long data,unsigned long type,String sid,unsigned long package){
char sidchar[20];
sid.toCharArray(sidchar,20);
payload_t payload = { data,type,sidchar, package };

Which gives me the error
array must be initialized with a brace-enclosed initializer

Which I do not understand. Doing
char sidchar[20]={0};

gives me the same error.

Just to clarify - I can not use string here - do you mean a "string" or a "String" object? I only ask, because you are using a "string" with char sensorid[20];... Also, have I linked to the correct RF24Network library?

Thanks, wrong library, but I've corrected it. Where you quoted, I did mean "string".

Best check the payload size. That is 32-bytes which is max for NRF24L01 but the libraries you want to use will needs some of the payload for addressing etc.

In your situation, your best bet is probably to use the standard C function strcpy:
payload_t payload;
char* source = "abcdef";
strcpy(payload.sensorid, source);

Note that source string does not have to be declared as char source[20] and can be declared as the rather standard C string char*.
Also, since you are limiting the size of the string to be passed in payload, you may prefer to use strncpy which will ensure no more than 20 characters get copied:
payload_t payload;
char* source = "abcdef";
strncpy(payload.sensorid, source, 20);
// Explicitly add a string termination to the end of string
payload.sensorid[19] = 0;

In the snippet above, please notice the last line, it is necessary in the situation where source string length is 20 or more non-null characters, as in this case, strncpy will copy all 20 characters but will not add the terminating 0 at the end of the string.

I deleted my comment as I was wrong with the missing \0.

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


text:
If a Timer is used, disabling some PWM pins, can I still use those pins for Digital write?
It's my understanding that when a Timer is used on an Arduino (in my case the Arduino Mega), it can disable analog write on some PWM pins, which pins depends on the Timer being used. For instance on the Mega, pins 44,45,46 are controlled by Timer 5.  If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.

If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.

You can view the connection between the Timer and the pins as programmable. The connection is enabled by, for instance, analogWrite(). The Timer control registers have a setting for both the connection and control logic of the pin (clean, set or toggle on timer value match).
You can use the Timer to generate interrupts without connecting a pin. This is the case with micros() and millis() which get their values from a counter which is updated by an ISR on Timer 0 (overflow). analogWrite() on pin 5 and 6 connects to Timer 0 value match logic.
analogWrite() uses the Timer value match and connects the pins. Enabling only the Timer (as you suggest) will allow you to use the pins with digitalWrite(). You can also use the Timer ISR for overflow. The Timer prescale is set for analogWrite().
Cheers!

When using an timer (other than by PWM) you can choose to enable it's output to a pin (which basically is what PWM does). So you can still use them as a digital pin (if you choose not to).
You could set up an PWM signal and enable timer interrupts afaik. But changing PWM, would also change the timer.
There is a difference in only using Arduino functions, or changing the registers directly.
Try to read the "timers" part of the datasheet and find some tutorials about avr/atmel/atmega register changing or/and setting up timers.


text:
Modify Arduino Due's Bootloader to flash when reset
I bought an Arduino Due, and I noticed unlike the other boards, the onboard LED does not flash after reset. I prefer this behavior, so I want to modify the bootloader to do this behavior when it starts. I have burnt bootloaders before, but I never modified one before.
How can I do this?

The Arduino Due bootloader is built-in. If you check the Arduino SAM core there are no bootloader files. There is a firmware file for the ATmega16u2 on the Programming Port. You might be able to modify this to do that (given that there is a LED to flash).
The alternative solution to a modified bootloader is modifing the init() of the Arduino SAM core. Please see https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/cores/arduino/main.cpp#L36 or https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/variants/arduino_due_x/variant.cpp#L372. Blink code as proposed by Majenko could be added there.
Cheers!

In my Arduino Folder, in /hardware/arduino I do not have a sam folder. Do I need to reinstall Arduino?

Nevermind, I found it in the AppData folder. Thanks!

The newer Arduino Boards Manager uses packages. They are typically installed in a "hidden" folder such as AppData, .arduino15, etc. Editing the files there is only a very temporary solution as they may "disappear" in the next update. A long term solution would be to get the code into the Due/SAM core by filing a github issue and a pull-request.

You cannot.
The SAM3X's bootloader is hard-coded into ROM and can never be changed.
Ever.
Yes, I know, it sucks, doesn't it?
However, the bootloader only executes if the flash is empty (bit of an odd choice if you ask me, but there you go) so you could "emulate" the operation by flashing an LED as the first thing in your sketch.
pinMode(13, OUTPUT);
for (int i = 0; i < 5; i++) {
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);
}
pinMode(13, INPUT); // This will "reset" the pin to default.

The blink code could be added to the main.cpp for SAM core. There is actually an initVariant() that is available. That would be the place to put this or the init(). Please see https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/cores/arduino/main.cpp#L36 or https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/variants/arduino_due_x/variant.cpp#L372


text:
how to change increase pwm frequency by changing resolution?
As told in this post:
http://forum.arduino.cc/index.php/topic,16612.0.html#
The arduino can achive up to 62.5khz with 8 bits resolution
adding this line in the setup:
TCCR0B = TCCR0B & 0b11111000 | 0x01

sets the divisor of the timer to 1
int output = 5;
void setup() {
  // put your setup code here, to run once:
  TCCR0B = TCCR0B & 0b11111000 | 0x01;

}

void loop() {
  analogWrite(output,127);

}

But I need a frequency of 100khz or as close as possible, the 8 bits resolution is not necessary of my porpouse, it will work just fine with 6 or 7 bits.

For 100kHz, you need to use a fast PWM mode, with a TOP specified by OCRxA,

http://arduino.stackexchange.com/a/19553/6628 has an exellent answer.  You do need the smaller /1 prescaler though.

Here's code for timer 1 on a atmega32u tested in a Teensy 2.0:
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(DDB5) | bit(DDB6);  // atmega32u OC1A and OC1B outputs
  // 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.
}

The trick here is using OCRxA to set the TOP value/resolution/frequency of the timer, and then using OCRxB as the PWM-controlled output.  The popular examples aim for a specific frequency with toggling, but often don't go into showing the PWM with the non-TOP OCRxx registers.
If you check the registers for your chip, this should also adapt to the other timers.  Here, I used timer1 to avoid confusing delay() and millis().

This will correspond to the pin 10 of the arduino uno rigth? https://www.arduino.cc/en/Hacking/PinMapping168. I have no try the code and get no output

Yes, per that diagram digital Pin 10 is OC1B, but since on the atmega168, it is PB2, so the DataDirectionRegister needs to enable bit 2.  I added it in a comment in the above code, but I'm not able to test it.

Tested, it works just fine.


text:
Troubleshoot Arduino LCD 16 x 2 shield
I tried to assemble Adafruit's Arduino LCD 16 x 2 using the instructions RGB LCD Shield: Control a 16x2 Character LCD using 2 pins - Assembly  without any success.
After assembly, I uploaded the HelloWorld example sketch on to the Arduino. The shield doesn't seem to be working. The LCD didn't turn on.
If I push back/press the LCD it turn on. Any idea on how to troubleshoot this?

Please upload the picture of your completed board.

Where have the photos disappeared to? Where they lost when the answer  that you posted was deleted? If so, could you edit your question and add the photos there? It may help other people who are having the same issue as you did.

By visually assessing the pictures, the issue seems to be due to poor soldering job.
You should try re-heating the soldering joints and make sure they are clean. There could be dry joints that may not be conducting signals.
Also you should upload pictures to your question post, not as an answer.

Thanks Chetan. I reheated some of the soldering joints and its started working. Thanks again! Feeling like a champ!

@user1261620 I'm glad that my post helped you in fixing the board. Before investing in expensive kits, you can practice soldering on some cheap scrap boards.


text:
Sustainable power source for outdoor arduino weather station
I have been running a simple weather station composed of a Sparkfun Pro Micro (8kHz/3.3V), a DHT22 and a NRF24L01+ transceiver during the last couple of months, and I can tell you up here in Canada weather stations save lives...
The board checks the temperature and the humidity once every second and transmits the new measurements back to my home server over RF if the changes are above some threshold. As such, the board sleeps most of the time, and the transmissions happen rarely (about once to thrice per minute).
The system has been running off an iPhone charger up to now, but I am now thinking of weaning it off the mains. The maximum power consumption of the whole circuit when DHT22 is on and RF chip is transmitting remains below 200mA and many articles suggest that with some optimization one can reduce the power draw by levels of magnitude. Actually, from what I read I gather that the average consumption of the circuit can be pushed below 1mA.
So, I was thinking of adding a solar panel, a charging circuit and a Li-ion battery to my setup, when I discovered these low-cost solar-powered USB power banks on several vendor websites. They make outrageous claims about their charge capacity, that in my experience one has to divide at least by two (20,000 ~= 10,000), but they are pretty rugged and seem appropriate for outdoor installation. The units seem to use a 6V/0.6W (100mA) solar cell that should theoretically be sufficient for charging the battery even if some days are less sunny or shorter.
I wonder if anyone has used one of these as a continuous power supply for an arduino kit, or can inform me about the possible limitations. The idea is not to deal with the power apparatus myself each time I want to assemble a kit.

Can the Power Bank (solar battery charger) be used out-doors? That would require some extra sealing. Otherwise that is plenty of power. I have a project where I hacked a Garden Solar Light; removed the LEDs and added an ATtiny84, sensors and NRF24L01 (alt. RX433) transmitter. The Garden Light has two rechargeable batteries (less than 600 mA) but with low power software tricks you can reduce power to under 100 uA in standby.

Good to know! Yes, it seems this second one is pretty sturdy and resistant.


text:
How to set string in the structure part of NRF24?
Can anyone help me on how to correct my program ? I want to transmit value in string form.
I put this to TX code
struct payload_t
{

 String sensor1;
};

..................
At the loop part I put this code
String sensor1 = (String(x) + "," + String(y) + "," + String(z)) ;

In the RX part I put this code
 struct payload_t
{

 String sensor1;
};

At the loop part
RF24NetworkHeader header;
payload_t payload;
network.read(header,&payload,sizeof(payload));

Serial.println("Sensor1 ");

Serial.println(payload.sensor1);

Below is the Attach picture result of RX code.
Thanks in advance :)

Did you actually 'instantiate' the struct in the TX and construct sensor1 as payload.sensor1 = ...? Anyways, there's still a problem.
You are using String in your payload. The third argument to read is the maximum message length that can be stored in payload. In your read call, you passed the size of payload as MAX_LEN. You will receive incomplete payloads since the String object in the RX payload struct has no content in it yet and thus payload's size, which you passed as MAX_LEN, will be less than that of the actual payload that was transmitted. Just ditch the Strings and try:
TX:
int vals = {x, y, z};   // guessing they are ints

network.write(header, &vals, sizeof(vals));

RX:
int vals[3];
network.read(header, &vals, sizeof(vals));

Serial.print(vals[0]); Serial.print(',');
Serial.print(vals[1]); Serial.print(',');
Serial.println(vals[2]);


text:
Will enabling parity bit actually decrease corruption?
I have an Arduino Mega communicating with a Bluetooth adapter through one of the auxiliary hardware serial ports. It works, but there appears to be a corruption rate of approximately 1 in 200 small packets. In other words, about 0.5% of the packets are being corrupted, it seems. I have the option of configuring the serial mode on both ends. While I cannot decrease the baud rate for bandwidth reasons, I do have enough room to enable parity or a larger stop bit if that would help.
Granted the corruption is on the serial line and not on the Bluetooth, if I enable parity, will this actually decrease the corruption rate? Or will the corrupt bytes simply be dropped without being re-sent? In other words, what happens when the hardware detects a bad byte?

"Granted the corruption is on the serial line" in the somewhat unlikely case that is actually true, you have fundamental problems in your system which you should be trying to solve.  With no information about the nature of the "corruption", we can't even rule out a programming mistake (not uncommon when juggling multiple serial devices) at this point.  Understanding exactly how the actual data differs from the expected may be a key guide to what is actually wrong.

You seem to be detecting corruption. How are you detecting corruption?

The Bluetooth protocol for serial communication has several encoding layers to avoid corruption. You might have a race condition in your code that is giving this. What does the ISR load look like? What baudrate and message frequency? And what is the communication "environment"; distance, electronics, wifi, etc.

You could consider adding Hamming code. This will double the message size but you can get 1 bit error correction and 2-bit error detection.

@ChrisStratton, I have only one serial interface enabled on the Arduino.

@slebetman, I am detecting corruption by receiving ping responses with bad nonce values.

@MikaelPatel, I am using Bluetooth BLE. The underlying virtual serial link is completely abstracted from the PC. There is no COM port like there would be with the older Bluetooth devices. There is only a "characteristic" to be consumed. Baud rate is 115200. Frequency is about twice per second. Used baud is currently about 10,000 (while testing). Distance is about 2 meters. There is no WIFI involved or nearby. The CPU load of the Arduino should be low. The PC program takes like 3% CPU. Bandwidth is more important than accuracy.

Parity doesn't, and was never intended to, decrease corruption.
All parity does is allow you to DETECT errors. If you detect errors, you still have to handle them.
Parity in memory is usually fatal - your code or data is corrupt, the solution is to halt the box, to stop this corruption (in memory) getting on to disk.
When used in communication (as it is here), parity errors usually mean you have to request a re-transmit (or, if acknowledgements are sent back, fail to send an acknowledgement and wait for an automatic re-transmit).
Also, be aware that the relevant error rate is per bit, not per packet. If a small packet (very small!) is 20 bytes, and there is corruption 0.5% of those packets, this indicates a 0.5% / 20 bytes per packet / 8 bits per byte (assuming 7 data bits, 1 parity bit, for example). This comes out to 0.003% errors.
Note that parity checks only work for 1-bit errors - in fact, a 2-bit error (in the same byte), the parity change will cancel out, and it will look ok.
An alternative to requesting re-transmits, is to use forward error correction - send redundant data (reducing your bandwidth). A very easy scheme is to send each packet twice (halving your bandwidth). You still need error checking (or some checksum) - if two packets are different, you still need to know which one was right. Checksums, on a more complex device, could let you try each combination, but for an Arduino, this would probably be too expensive (the code would take up sizable space, which an Arduino may, or may not, have spare).
All of this is usually written into higher level protocols (TCP, used for most internet file transmission, ZModem file transfer used for modems prior to the Internet). Other protocols, such as internet radio, will use either forward error correction, or will accept the occasional glitch.

My packets are actually quite small. The largest one is around 18 bytes. The ones in question are something like 7 bytes. I have not looked into the corruption closely enough to know what type of corruption it is. I do not know, for example, whether there is a missing or extra byte, or whether one or more bytes are corrupted. My protocol was designed around corruption from the start, so it is not a big deal. I just wanted to know whether parity would help. I actually come from the network world, so that side of things I know very well. The electrical stuff is where I have limited experience.

By not looking into the nature of the corruption, you are wasting everyones time as we cannot tell you if parity would help. Voting to close.

@ChrisStratton, Wasting everyone's time? I think not. This discussion about parity is important. You seem to be assuming the problem is not in the serial. Whether or not the problem in my case is in the serial is completely irrelevant to the hypothetical case that it is. I am not asking others to solve my problem. I was simply asking whether parity or a longer stop bit would decrease corruption caused by a low quality serial connection. The answers so far are quite educational for many people. SE is not just about solving the OP's problem.

Your question cannot be answered without knowing if you are getting altered characters or missing ones.  Note that substituted is not the same as altered.  Questions insufficienctly specific to be answerable are off topic here - this is not a discussion forum.

@ChrisStratton, I agree that my particular case would require more information to give a definitive answer, but the hypothetical question about parity can, and seems to have been, answered as-is. If it matters to you, my data so far suggests that specific bytes are being corrupted, hence the bad nonce values on otherwise successfully returning ping responses. Perhaps I will do further testing later, but so far I feel the answers here have been helpful and informative.

Parity by itself does not reduce the error rate, it is used to detect errors. It is up to higher level protocols to determine what to do when the error is detected.
To answer your question about stop bits, going to two might help. The extra stop bit adds a 1-bit-time gap between characters and gives the receiver a little more time to sync up with the transmitter. If the baud rates are a little off between the sender and receiver, it would make it more likely that errors would be limited to one character rather than a whole string of them. That said, the 2 stop bit option is mostly a relic from the days of mechanical Teletype machines. These days it is usually better to make sure both clocks are at the correct frequency.
Have you determined where the errors are occurring - in the serial connection between the Mega and the BT adapter, in the BT link itself, or at the other end? With short wires, correct baud rates (check for the correct clock frequency), a good ground, and correct logic voltages, the raw error rate in the serial connection should be extremely low. I would focus on finding the source of the errors before trying to correct them.

If this is true that parity itself is only for indication, then I can understand why it is often disabled by default these days. I would rather use a hash to check for data integrity than a single bit anyway. I guess parity is just a vestige of the olden days. As for the source of the errors, I have no idea. I am relatively new to serial, and I am very new to programming for Bluetooth (BLE). The wires are indeed short, and the ground is definitely good. The voltage may be a little off, but that may not be worth messing with since the Mega likes 5V and there are other pins using 5V input.

The thing is, I actually started with software serial, which was giving me a packet corruption rate of around 20% (only barely affected by baud rate). Now that the corruption rate is more like 0.5% by using hardware serial, I am pretty happy with it overall. I just wanted to make sure I was not missing any tricks to make it extra clean.

@Michael - that strongly suggests that what you actually have is a mistake in your program.

@Michael if you're doing bitbanging serial ("bitbanging" => just setting & clearing bits at the right time), then you need to have very accurate timing. One common issue is sending a bit, then setting a timer for when to start the next bit - your clock will drift by the amount of time it takes to set the pin high or load plus the time it takes to set the next alarm, plus overhead. Hardware is always better.

I am guessing that the problem is that your clock is not 100% divisable to produce exactly 115200. If so it makes sense that communication sometimes fail.
See this question for more details, in particular
the link to WormFood's AVR Baud Rate Calculator.

That is very interesting actually. According to WormFood (which I had actually referenced in my initial implementation over USB virtual serial), 76800 would be an ideal high baud rate for a 16MHz CPU. Unfortunately, the HM-10 Bluetooth controller does not have any options between 57600 and 115200. When I used USB, I had the baud at 125000 (16MHz divided by 128), which seemed to work very well.

Parity checking will only let your code detect a corrupted byte, and not very well at that. Assuming your primary goal is to get packets transferred reliably, you'd be better off to add a checksum to each packet sent, testing the checksum when the packet is received, and asking the transmitter to re-send a failed packet. Since you only expect 1 packet in 200 to be retransmitted, your bandwidth shouldn't take a big hit.


text:
(HELP)How to read Physical Dimensions in datasheets
Sir/ Ma'am,
.
How to read the dimension labels of this IC?

I have annotated your drawing a little to help you understand it better:

Values above the horizontal lines are in inches. Values below it are in mm.

why there is an plus and negative sign?

that is tolerance values, allowed variations in production (for instance). 0.060±0.005 is the range 0.055 to 0.065.


text:
Is there a way to upload precompiled code to an arduino?
My company is developing a programmable remote control car which is driven by an Arduino Nano. We would like a way for the user to install software updates to the Arduino, but we don't want to give the user access to the code.
Is there a way to compile Arduino code without automatically uploading it, so that I can put the pre-compiled binary up for download on a website?
Then after this how would I go about manually uploading it (to the Arduino)?

There are similar questions to this one. Certainly it can be done.

i developed avrdude based exe, try it, http://iot.6te.net/ardiuno.php

Is there a way to compile arduino code without automatically uploading it, so that I can put the pre-compiled binary up for download on a website?

Yes, you can save the .hex file produced by the compiler. If you turn on verbose output from the compiler you can find the temporary directory where it is stored. Simply copy from there to a folder for download on the website.

And then after this how would I go about manually uploading it (To the arduino)?

You can do that with the command line tool avrdude but as that is somewhat complex with a lot of parameters it might be easier to use a graphical front-end. One such tool is xloader. There are several. This depends on your end-users and the host machine that they will be using.
You can find some more info here.
Cheers!

That said, I would like add, that if you can put hex file on website for users to download and flash the Arduino with it, then I (or anybody else) can also make a hex file and flash it to the arduino.

I think if you do not publish the source code, the project will be a little bit unconstructive, both for developers and users, especially when it is based in open hardware.
You can put hex files available to users, but also the source code, allowing the community to participate in the development of your product.
Anyway, if you use third-party code in your project, such as libraries, remember to respect their licenses.
Best regards. Good luck with the project.

I actually agree with you, and I would like to just make everything open source. But my boss has other plans

@TheIronKnuckle If you are using any libraries (even Arduino's libraries (the Arduino language)) then make sure you are not violating any of those licences either.

@TheIronKnuckle Your boss must pay you a salary. That is the whole point.


text:
Problem with running 2 DC motors with ultrasonic sensor
I'm not expert in electrical circuits, maybe I am making a very simple mistake or missing some basic points with my circuit.
What I'm trying to achieve is simple, to run 2 DC motors with an ultrasonic sensor to detect obstacles and change direction. When I unplug the ultrasonic sensor everything is working fine as expected without obstacle detection but when I connect the ultrasonic sensor, sensor always responds with 0 cm distance. Then I removed 9 V battery from the circuit and plug Arduino to computer via USB, sensor works fine but motors are not working properly, it looks like the power from USB is not enough to drive motors at the same time. I've added my circuit scheme below:

Measure the voltage (Vin, 5V, 3V). Check the power consumption for the motors. What type of 9V battery? Can it provide the power required? By measuring the voltage drop you might get a better understand of the issue(s).

Thank you Mikael, I will check the values. Between the power source is a standard Duracell 9v battery.

A 9V battery may have a hard time providing power for both the motors and the board. You might need to rethink this. Or at least use a separate battery for the board.

How (acoustically) loud are the motors?  If they're the typical RC car motors, they can screech harmonics right up into the 40 KHz range typical of ultrasound ranging sensors, interfering with the sensor's ability to work at all.
How (electrically) loud are the motors?  If RC as above, they throw all sorts of transients onto the power lines (and everything else within electrical pickup range).  You might want to put some ceramic capacitors across the motor leads to absorb some of those transients.
Kudos for the suggestions to provide separate power supplies for the motors and the Arduino / sensor combination.  I'd go even further, and provide separate power for all three, and use opto-isolators for the connection between the ultrasound and the Arduino.
Some years ago I used two Novak Super-Rooster motor drivers for a battle-bot competition.  They were driven by PWM outputs of an Arduino, where 50% duty cycle was off, 0% was full speed reverse, and 100% was full speed ahead.  These were powered by a sealed lead acid battery, and driven full-out, the motors got +/- 12VDC at about 40 amps.  There was a common ground with the Arduino, going to the Super Roosters, but not the motors, and the drivers took care of the electrical shielding, with a little help from the ceramic bypass capacitors I mentioned.  Worked great!

Thank you for your detail explanation. I think you hit a good point with the high frequency sound issue. I'll look for ceramic capacitors etc. and let you know about my progress.


text:
Why the need to use the volatile keyword on global variables when handling interrupts in Arduino?
I am familiar with the keyword Volatile being used to declare variables that are shared among multiple threads on a software application (basically on a multithreaded application).
But why do I need to declare a variable as Volatile when running the code on an an Arduino interrupt? Is the code running in the interrupt executing on different thread? Is there something else going on?

You have to tell the compiler that the variable exists so that optimization algorithms don't remove it entirely from your executable.

"I am familiar with the keyword Volatile". Then forget about it, and read again.

Effectively the interrupt handler is a separate thread from main. Without the volatile declaration, compiler does not know that main must re-read the global (which may have been changed by the interrupt handler).

Is the code running in the interrupt executing on different thread - well sort of, only the opposite. Interrupts are the mechanism, the technique used by OS programmers, to implement threads. So we need to use volatile in multithreaded code because their context has been switched by the OS in an interrupt. We need to use volatile in interrupts simply because interrupts run in a different context.

First, it's volatile not Volatile. I cover these concepts in my page about Interrupts however to avoid giving a link-only answer I'll repeat the relevant bits.

What are "volatile" variables?
Variables shared between ISR functions and normal functions should be declared volatile. This tells the compiler that such variables might change at any time, and thus the compiler must reload the variable whenever you reference it, rather than relying upon a copy it might have in a processor register.
For example:
volatile boolean flag;

// Interrupt Service Routine (ISR)
void isr ()
{
 flag = true;
}  // end of isr

void setup ()
{
  attachInterrupt (0, isr, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  if (flag)
    {
    // interrupt has occurred
    }
}  // end of loop

Critical sections ... accessing volatile variables
There are some subtle issues regarding variables which are shared between interrupt service routines (ISRs) and the main code (that is, the code not in an ISR).
Since an ISR can fire at any time when interrupts are enabled, you need to be cautious about accessing such shared variables, as they may be being updated at the very moment you access them.

First ... when do you use "volatile" variables?
A variable should only be marked volatile if it is used both inside an ISR, and outside one.

Variables only used outside an ISR should not be volatile.
Variables only used inside an ISR should not be volatile.
Variables used both inside and outside an ISR should be volatile.

eg.
volatile int counter;

Marking a variable as volatile tells the compiler to not "cache" the variable's contents into a processor register, but always read it from memory, when needed. This may slow down processing, which is why you don't just make every variable volatile, when not needed.

Atomic access
Consider this code:
volatile byte count;

ISR (TIMER1_OVF_vect)
  {
  count = 10;
  }

void setup ()
  {
  }

void loop ()
  {
  count++;
  }

The code generated for count++ (add 1 to count) is this:
 14c:   80 91 00 02     lds r24, 0x0200
 150:   8f 5f           subi    r24, 0xFF     <<---- problem if interrupt occurs before this is executed
 152:   80 93 00 02     sts 0x0200, r24   <<---- problem if interrupt occurs before this is executed

(Note that it adds 1 by subtracting -1)
There are two danger points here, as marked. If the interrupt fires after the lds (load register 24 with the variable count), but before the sts (store back into the variable count) then the variable might be changed by the ISR (TIMER1_OVF_vect), however this change is now lost, because the variable in the register was used instead.
We need to protect the shared variable by turning off interrupts briefly, like this:
volatile byte count;

ISR (TIMER1_OVF_vect)
  {
  count = 10;
  }  // end of TIMER1_OVF_vect

void setup ()
  {
  }  // end of setup

void loop ()
  {
  noInterrupts ();
  count++;
  interrupts ();
  } // end of loop

Now the update of count is done "atomically" ... that is, it cannot be interrupted.

Multi-byte variables
Let's make count a 2-byte variable, and see the other problem:
volatile unsigned int count;

ISR (TIMER1_OVF_vect)
  {
  count++;
  } // end of TIMER1_OVF_vect

void setup ()
  {
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  if (count > 20)
     digitalWrite (13, HIGH);
  } // end of loop

OK, we are not changing count any more, so is there still a problem? Sadly, yes. Let's look at the generated code for the "if" statement:
 172:   80 91 10 02     lds r24, 0x0210
 176:   90 91 11 02     lds r25, 0x0211  <<---- problem if interrupt occurs before this is executed
 17a:   45 97           sbiw    r24, 0x15
 17c:   50 f0           brcs    .+20

Imagine that count was 0xFFFF and was about to "wrap around" back to zero. We load 0xFF into one register, but before we load the second 0xFF the variable changes to 0x00. Now we think count is 0x00FF which is neither the value it had before (0xFFFF) or now (0x0000).
So again we have to "protect" the access to the shared variable, like this:
void loop ()
  {
  noInterrupts ();
  if (count > 20)
     digitalWrite (13, HIGH);
  interrupts ();
  }  // end of loop

What if you are not sure interrupts are on or off?
There is a final "gotcha" here. What if interrupts might be off already? Then turning them back on afterwards is a Bad Idea.
In that case you need to save the processor status register like this:
unsigned int getCount ()
  {
  unsigned int c;
  byte oldSREG = SREG;   // remember if interrupts are on or off

  noInterrupts ();   // turn interrupts off
  c = count;         // access the shared variable
  SREG = oldSREG;    // turn interrupts back on, if they were on before

  return c;          // return copy of shared variable
  }  // end of getCount

This "safe" code saves the current status of interrupts, turns them off (they may already be off), gets the shared variable into a temporary variable, turns interrupts back on - if they were on when we entered the function - and then returns the copy of the shared variable.

Summary
Code may "appear to work" even if you don't take the above precautions. That is because the chances of the interrupt occurring at the exact wrong moment is fairly low (maybe 1 in 100, depending on the code size). But sooner or later it will happen at the wrong moment, and your code will either crash, or occasionally return the wrong results.
So for reliable code, pay attention to protecting access to shared variables.

I thought volatile would handle the multi-byte types read and write access in the main loop and ISR!
So, I was completely wrong and should turn off the interrupts before accessing them in the main loop, right?! ;-(

That's right. volatile just tells the compiler to not optimize and keep variables in processor registers. It doesn't have any other side-effects (apart from letting the compiler know these variables may change at any time, so volatile variables are never optimized away because they "aren't used"). So yes, as illustrated above, "guard" access to multi-byte variables by turning interrupts off.

Is it safe to remove volatile if we use the final version of getCount()?

I don't understand why the line (sbiw r24, 0x15) uses the value 0x15 instead of the value 20 in the "Multi-byte variable" section. Could it be a mistake?

@ecc Well, one is hex and one is decimal. Of course, 0x15 is 21 in decimal, not 20. However the compiler may have decided to subtract 21 and check if the carry bit was set, instead of comparing to 20. This would be part of compiler optimization. In other words, > 20 is the same as >= 21.

volatile has nothing to do with multithreading per se, and it seems to be among the most miused keywords in that area. It is never a substitute for proper synchronization.
As per standard C, volatile invokes mostly implementation defined behaviour of telling the compiler to not optimize away accesses to the memory a variable resides in, even if the compiler thinks there can't be any other.
This can be useful in the following situations where the compiler is not aware that outside means can change a variable:

memory mapped hardware registers
variables accessed from other threads but checked in a tight loop
variables accessed from interrupt or signal handlers but checked in a tight loop


text:
HC-06 Bluetooth Module on Arduino Nano
I'm working on a project where I need to have Bluetooth capability on my Arduino Nano to send data from a sensor over to the computer. Unfortunately, I'm having a difficult time figuring out how to establish a connection from the HC-06 to the computer.
I've hooked up the HC-06 to my Arduino in a fashion similar to the picture shown below.

I've also been testing it with various code that I've found online that deal with tutorials on the HC-06.  The current code I'm working with is below.
#include <SoftwareSerial.h>
SoftwareSerial BT(1, 0);

void setup()
{
  // set digital pin to control as an output
  pinMode(13, OUTPUT);
  // set the data rate for the SoftwareSerial port
  BT.begin(9600);
  // Send test message to other device
  BT.println("Hello from Arduino");
}
char a; // stores incoming character from other device
void loop()
{
  if (BT.available())
  // if text arrived in from BT serial...
  {
    a=(BT.read());
    if (a=='1')
    {
      digitalWrite(13, HIGH);
      BT.println("LED on");
    }
    if (a=='2')
    {
      digitalWrite(13, LOW);
      BT.println("LED off");
    }
    if (a=='?')
    {
      BT.println("Send '1' to turn LED on");
      BT.println("Send '2' to turn LED on");
    }
    // you can add more "if" statements with other characters to add more commands
  }
}

When I search for a connection on my computer, it finds the HC-06 and I can then attempt to establish a connection.  I enter the pairing code of 1234.  It then says that a connection has been established so I go into the Bluetooth Services tab where it tells me what COM port to use (either COM7 or COM4 depending on which computer I try it on.  I've tried this on two separate computers.)
So, I open a PuTTY session and attempt to connect to the indicated COM port.  About 50% of the time, it says that a connection could not be established to the indicated COM port.  The other 50% of the time, I am able to open a PuTTY session but then nothing happens.  The green LED on the HC-06 continues to blink away no matter what I try to do.
Any help would be VERY appreciated as I feel like I've tried everything I can think of.
Thank you!

You double checked the baud speed used in putty? And a=(BT.read()); has unneeded brackets. Remove the outside ones

Yeah, I'm setting my PuTTy session at 9600 baud.

Your voltage divider looks wrong. You should be dividing voltages from the Nano to the module and not the other way round.

Also why lay SoftwareSerial over those pins? They are already UART pins from what I can see.

I agree with TisteAndii's comment. Your voltage divider is in the wrong place. You are dividing down the 3.3V signal from the HC-06 to be a maximum of 2.269 volts. However the Nano requires at least 3.5V to be considered HIGH.
Plus, you are putting 5V from the Nano into the HC-06 which may damage it.

Try changing the order of the pins on the Software Serial declaration, the correct order is (Rx,Tx), so SoftwareSerial BT(0, 1);
Or, just forget Software Serial altogether and remove the first two lines and change "BT" to "Serial" to use the hardware UART on those same pins which works better.


text:
Can someone explain how to program i2C communications without using the library?
I am starting to get into i2C, SPI, and other forms of communication. I have read about them and have a fuzzy idea of how they work electrically, but can someone explain how I would turn the electronic portion into the coding/controlling portion? I really want to get a great understanding of it.

If you have Arduino Uno, you can try my free I2C terminal. I2C communication is quite complex. Check out https://iobtoolkit.com/s/i2c/
and https://www.youtube.com/watch?v=4x3NNWLgtTU .
The idea is that you hook up I2C device and you can chat with the device using a console, exploring the protocol and device functions, without writing a single line of C.

I really want to get a great understanding of it. - reading the existing library would help (Wire.cpp and twi.c amongst other files).

The AVR microcontrollers that Arduino uses have built-in hardware support for the said protocols.
That means that you don't have to write program to control the transmission/reception process but you only need to configure the appropriate registers and the hardware will initiate transfer and inform you when it's done.  I suggest you carefully read the datasheet of the microcontroller you are using with your Arduino and you should find all the information there.  It even has code examples, so you can actually copy-paste functions and use them in your program, here is one of the examples:
void SPI_MasterInit(void)
{
    /* Set MOSI and SCK output, all others input */
    DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
    /* Enable SPI, Master, set clock rate fck/16 */
    SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}

void SPI_MasterTransmit(char cData)
{
    /* Start transmission */
    SPDR = cData;
    /* Wait for transmission complete */
    while(!(SPSR & (1<<SPIF)));
}

The keywords with the capital letters are usually register and bit names: you can look them up in the datasheet.

Would that work for I2C?

Can someone explain how to program i2C communications without using the library?

The AVR has hardware support for this but you can implement it with the pin functions. I2C is a lot about timing the signals and detecting the reply signal from the slave.
The hardware support for I2C requires understanding of a complex state-machine. If you have implemented the I2C protocol it becomes easy to understand the hardware support and how this help remove a lot of work from the processor core. The state machine, control and status registers and interrupts, are described in the AVR product specification. There are also lots of excellent descriptions on the web. Do not miss the AVR application notes for the I2C. Most of the code in the Arduino core originated from them.
Cheers!

So its based all on timing, and hardware application? Sounds like it has to almost be like clockwork

I2C hardware is present in almost any modern microcontroller. It's all about writing a driver for it. Hardware interface will take care of low-level details, such as clock generation and timing.

A good way to learn how to code for these interfaces is to look at the source code for the libraries themselves. In the PC world, these will be in the directory
Program files (x86)\Arduino\hardware\arduino\avr\libraries


text:
How to connect a 12V power supply to an RGB LED strip receiving RGB values via Arduino Uno PWM pins?
Desired Behaviour
I want to send RGB values from my Arduino Uno PWM pins to an RGB LED strip.
What I've Tried
I've purchased this RGB LED strip and 12V power supply (specs below).
I'm trying to follow this adafruit tutorial but am finding the diagram references unclear.
I've mocked up a diagram but am not sure it would work:

( I haven't used the Vin pin before, so, just to be clear, that is the pin that is connected to the positive line on the breadboard - is that how to transfer the 12V power to the breadboard? )
Questions
01)  Is the above diagram safe and sound?
02)  How do I connect the power supply to the RGB LED strip?
03)  Is it ok to keep the Arduino 'powered' by the USB whilst plugged in to the 12V power (so that it can keep sending the RGB values to the LED strip via the PWM pins)?
04)  I've seen references to grounding the power source, how do I do that?
05)  Are the MOSFETS I have from the Arduino Uno starter kit sufficient for this task?
Printed Text on MOSFET:  IRF520 Y32K BE
MOSFET Datasheet:  Link (IRF520NPbF)
Specifications
RGB LED Strip

LED type:  5050 SMD
Color:  RGB
LED quantity:  300LED
Package:  5 Meter/REEL
Voltage:: 12V DC
Working Power:    14.4W
Working temperature: -20° to 50°
Size: ⌀180mm
Length :  5m
Life Span:    50000+hours
Weight:   0.3kg

Power Supply

Input Voltage: AC 100 - 240V
Output Voltage : DC 12V, 6A
Power : 72 Watts
Connector Size:
External Diameter: 5.5mm
Internal Diameter: 2.5mm

01) Is the above diagram safe and sound?

It looks to be OK, except one thing:
The current you can draw from the Arduino's VIN pin is limited to about 1A. That is a sixth of what your power supply can provide, and the LED strip when everything is on needs more than that (1.2A), so you could run into problems.  The limit is threefold:

The barrel jack itself is rated at up to 1A
There is a protection diode with a limit of 1A
The header pins are rated at up to 1A

And of course the Arduino itself needs to use some of that available 1A.  So you might be better off splicing your LED circuit into the power supply's wire before it enters the Arduino.

02) How do I connect the power supply to the RGB LED strip?

Power goes in (+) to the common pin of the LED strip and then out of any of the three colour pins that happen to be connected to the ground of the power supply. That is, the ground of the Arduino in your schematic since they are (as they should be) all shared.

03) Is it ok to keep the Arduino 'powered' by the USB whilst plugged in to the 12V power (so that it can keep sending the RGB values to the LED strip via the PWM pins)?

Yes. There is circuitry on the Arduino that allows both the USB and barrel jack to be plugged in together.

04) I've seen references to grounding the power source, how do I do that?

That refers to connecting the external power supply's ground and the Arduino's ground together. By using the barrel jack that is all taken care of for you.

05) Are the MOSFETS I have from the Arduino Uno starter kit sufficient for this task?

Not really.  They are designed to be switched with a higher voltage than the Arduino's IO pins provide.  While they will work, they may cause the LEDs to be dimmer than they should be, or the MOSFETs might get hot.  Basically a MOSFET has a "threshold" voltage range which is the voltage range at which the MOSFET transitions from off to on. That is 2V - 4V for that MOSFET, which while within the range of an IO pin isn't really that great. At 4V the MOSFET still isn't completely on. You may notice from the datasheet that the "R_DS(ON)" value - that is the resistance of the MOSFET when it is on, is measured with the gate voltage at 10V. That is a voltage where the MOSFET is guaranteed to be fully on. Anything less than that and the resistance will be higher causing more losses across the MOSFET.  I could see that instantly from the model number - it starts with "IRF".  There is a specific range from International Rectifier which is designed to be directly driven by an IO pin - these are the "IRL" (for International Rectifier Logic-level) series.  These have their R_DS(ON) values measured typically at a gate voltage of 4.5V and a threshold voltage in the region of 500mV to 1.5V. When directly driving from an Arduino these IRL (or equivalent from other manufacturers) are preferred.

It works! You have no idea how long I've been wanting to make this happen, thank you!  Soldering iron, accessories and other MOSFET's are arriving in the mail tomorrow so I can solder header pins on the LED wires and make more secure connections to the breadboard.  (These are the MOSFETS I've ordered - IRLB8721PBF - http://docs-asia.electrocomponents.com/webdocs/0f35/0900766b80f35037.pdf).

Just curious. R_DS is 0.2ohm at 10v (GS), which is pretty insignificant. Would the R_DS be so much higher that the leds will look dimmer, even at 1.2A?

Take a look at Fig3 of the datasheet and do the maths.  At 10V V_GS and 50V V_DS, R_DS calculates at around 1.6Ω. At 5V V_GS it calculates at around 11Ω. So we're talking 10x the resistance.


text:
Arduino PWM Pins Interrupt
I am creating pwm from an arduino pin with 50% duty cycle. I just want to know how can i detect its every falling edge using timer interrupt? I don't want to connect that PWM pin to an external interrupt pin. Please help me.

You can define an interrupt service routine (ISR) for each Timer and PWM pin that it handles. These are known as TIMERn_COMPA_vect, TIMERn_COMPB_vect and TIMERn_COMPC_vect. The Mega has six Timers (n=0..5).
ISR(TIMERn_COMPA_vect)
{
// Timer/Counter compare match A
}

Check the PWM configuration for how the pin is set, cleared or toggled.
Cheers!

Besides creating the ISR(... you also need to enable that interrupt (e.g. TIMSK1 |= _BV(OCIE1A))

Referring to the datasheet of ATMega328P: If you want to generate an interrupt every falling edge you must know if the Pin is inverse mode or not. As you can see from the timing diagram the Pin stays high until the compare unit matches (current value of the TCNCT == value stored in OCRn ) and then goes low in the normal mode or works as opposite in the inverting mode.
This could be regulated by changing the bits COMnx in the TCCRn register. If, for example: COM0 = 1 and COM1 = 1 the table says: Set OC0A on Compare Match, clear OC0A at BOTTOM, (inverting mode).
Now with these settings the falling edge happens when the timer overflow, so the ISR must occur when the timer reach its maximum value.


text:
Arduino app hangs on upload for all boards
I'm at a loss. I have many boards and have not had much trouble in the past uploading to feather, uno, light blue bean and others. I have a lot of boards loaded in the board manager and I'd rather not delete everything just yet.
But, after taking a month off of arduino programming I've come back to the app to discover that I can't upload anything to any board. I've tried a brand new uno, an adafruit feather and the light blue bean. In each case I can see the port, but the upload just hangs like this:

On the board the light that normally blinks during upload never blinks. It's like the upload just isn't happening. But there is no error in the app.
I tried reinstalling the app, but that didn't help. My next thought is to delete everything, and do a fresh install. Which will be annoying. Is that my only hope?

UPDATE:
Here are the settings from the tools menu as requested:

In the Tools menu, what do you have set for the Board, Programmer and Port?

I added that information.

Try changing programmer to AVR ISP.

I tried AVR ISP. Same issue. In fact, that is what I normally have it on. I was trying ArduinoISP when I took the photos to see if that would help.

Do you have an ISP device or not? If not, there is no point in using Upload Using Programmer. If so, you must use that. after taking a month off of arduino programming - it looks like a Mac. Have you upgraded the Mac operating system in the meantime?

Yes I did upgrade. Is there a known issue?

I tried that once. A very common reason for this problem is a different cable. Some USB cables are not suited for uploading the data to the Uno board.
Have you brought a new cable? If so, switch back to the old one. It may not look like it makes a difference, but it requires attention.

Thanks for the suggestion. But this was not the issue. I have had the issue with cables before and it would at least cause and error in the app. But, just to check I have tried many combinations of cables old and new and this error persists. I think I will just have to delete everything and see if that works.

Also try plugging in several boards at once (on several USB ports), to allow testing different serial ports.  Possibly run fuser or similar program on /dev/SLAB_USBtoUART

I appreciate that this is an old post but I have recently been experiencing this problem.
I found that the issue was caused when I had a wireless SD shield attached to the Arduino. Taking this shield off allowed me to upload. This occurred across 5 different Arduino's.
After some more testing I found that switching the "serial select" toggle on the wireless shield from "MICRO" to "USB" allowed me to upload as well. Switching it back to "MICRO" subsequently blocked the upload.
Hope this help anyone having this problem in the future.

You should ask the original questioner if a SD shield was used, I don't think so since the OP state "brand new uno, an adafruit feather and the light blue bean".

I was also using brand new Arduino boards. I doubt the original poster is having this issue still 2 years later. I am merely contributing an answer for future readers as I experienced this issue today and this question is one of the first search results when Googled.

Since you are making asumptions, you should use the comment since it's not a answer.

Well it is an answer... Other people gave potential solutions too just like this one - making assumptions. Maybe go and answer a question or two rather than nit-picking people providing input on a problem they have come across.

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


text:
Arduino: Read frequency of input from audio jack
I want to trigger an arduino from a sound from an audio jack from a mobile phone. The audio is a 1 Khz sound that the mobile will play. I want to avoid accidental triggering of the audio by testing for specifically that frequency.
I've found several tutorials using analog read, but the output is not in hertz.
How do i get the output in Hertz?
int incomingAudio;

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

void loop(){
  incomingAudio = analogRead(A0);//read voltage at A0
  incomingAudio = (incomingAudio+1)/4 - 1;//scale from 10 bit (0-1023) to 8 bit (0-255)
  if (incomingAudio<0){//deal with negative numbers
    incomingAudio = 0;
  }
  PORTD = incomingAudio;
  Serial.println(PORTD);

}

Edgar Bonets Program is ingeneous, but the power fluctuations tested with a tone at 1000 kHz (square wave Signal) are quite high. A factor of three using LOG_TAU = 6. May be, some improvement is possible.

@ChristianRempel: Testing with synthetic data shows the reported power fluctuates within a factor 2.2 with a square input and a factor 1.2 with a sinusoidal input.

You can measure a single "pure" frequency by counting the number of times that the pin changes, by using the inbuilt timers. Here is a sketch from my page about timers that accomplishes that:
// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

ISR (TIMER1_OVF_vect)
  {
  ++overflowCount;               // count number of Counter1 overflows
  }  // end of TIMER1_OVF_vect

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

ISR (TIMER2_COMPA_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

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

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

Feeding in a 1 kHz sine wave (from 0V to 5V) I get this output:
Frequency Counter
Frequency: 1000 Hz.
Frequency: 1002 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1002 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.

There is the occasional mis-reading but it looks accurate enough. You might sample a few times, and if you get something between 990 and 1010, five times, you might consider that a match.
You will need to make sure that the input is in the range for triggering the input circuitry of the Arduino. It should be around 4 to 5V, and not higher than 5V (for a high). It also should not go negative.
Something like this will protect the input pin:

Warning - audio from an audio jack will be AC and it will go negative. Make sure you use a suitable input protection.

Amplification
After looking at Wikipedia - Line level it seems likely that the output from your phone will not be high enough (around 700 mV probably). Therefore a simple transistor amplifier will probably be required to raise it to a level that can be detected.
Inspired by this post on Electronics Stack Exchange, I made up a simple amplifier:

Testing out with around 500mV peak-to-peak input indicates that it successfully amplified it to 0 to 5V DC:

Alternative method with analog comparator
Based on suggestions by Chris Stratton, there is another way of doing this.
You can use the analog comparator to detect an analog signal passing a threshold, like this:

I have set up the voltage divider to trigger at 0.265V, so that a 500 mV signal should provide an acceptable triggering range.
As for the sketch, at these frequencies we can do something simpler than what I posted before:
volatile bool counting;
volatile unsigned long count;

ISR (ANALOG_COMP_vect)
  {
  if (counting)
    count++;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

unsigned long startTime;

void loop ()
  {

  if (!counting)
    {
    startTime = micros ();
    count = 0;
    counting = true;
    }
  else
    {
    // is a second up? (1000000 microseconds)
    if (micros () - startTime >= 1000000)
      {
      counting = false;
      Serial.print (count);
      Serial.println (F(" Hz."));
      }  // end of a second being up

    }  // end of if

  }  // end of loop

You don't need an amplifier, if you are going to do single-tresholding detection anyway, the ATmega has an analog comparator usable by the timer.  What you did miss is the DC blocking capacitor in your first circuit.  Choose one that makes the impedance high (especially in combination with any resistor) enough to use the internal protection diodes, rather than trying to find an external one that creates the right limitation.

@ChrisStratton :  Yes, good idea. I've edited with an alternative method along the lines of what you suggested.

I'm afraid you still don't quite have it. The diode remains a distraction and you need to bias to your threshold, which would ordinarily be placed somewhere more like half the operating voltage.

Well, @ChrisStratton, I would be pleased if you would post an answer explaining your solution in detail. Just saying that I have it wrong isn't helping me or anyone else, like the OP.

you need to bias to your threshold - I was assuming that the incoming signal was around 700mV (Line Level) - and indeed that worked in my test. Feel free to post other figures.

Nice description and quick prototyping!  I totally missed that the signal did not have any other background noise, it's just the 1kHz tone.

How to do this on a Attiny85? Code does not compile. I want to use an old phone with touchscreen that uses a (local) webpage as button interface and connected via audio to the Attiny85. Each button produces a sound (wave) at different Hz to be unique and to identify which button is pressed. Came along this article because there are not much articles about using (an old phone's) audio as interface to interact with a hardware project. It doesn't sound impossible, like your example describes. Possible to do this on Attiny? Will be great.

If your signal is a pure 1 kHz tone, then you should use Nick
Gammon's counting method, as it is the most straight-forward solution.
If, however, you are picking the signal through a microphone, chances
are you will also get some background noise, and this can make the
counting method unreliable.
In such a case, you will have to use some kind of digital filter to
extract the desired signal from the noise. I would recommend using
homodyne detection,
which is both simple and very robust against wide-spectrum noise: let
f = 1 kHz be the frequency you want to detect, and t
be the current time, then

compute cos(2 π f t ) and sin(2 π f t ): these two periodic signals,
in quadrature to one another, are called “the local oscillator”
multiply your signal independently by the above cos() and sin()
low-pass filter the two products, which gives you the
I and Q demodulated signals
compute the instantaneous power = I2 + Q2.

You know the phone is ringing when this power goes above some
experimentally-determined threshold.
I know all this sounds like heavy math, but it need not be:

All the computations are amenable to efficient fixed-point
implementations, and you can do the math in parallel with the
analog-to-digital conversion.
The scheme works even with crude approximations of the sin() and cos()
functions. Even square waves (sin() and cos() being always +1 or −1)
work quite decently.
The low-pass filter can be implemented as an
exponential moving
average,
which is only a bit shift, an add and a subtract.

I can try to write some sample code, but I would go through the trouble
only if there is interest. If your signal is so clean that Nick Gammon's
method works reliably, there probably is no point.

EDIT: I wrote a program to demonstrate this approach, just for the
fun. It's available as a GitHub gist:
homodyne.ino.
I am not copying the whole program here, just adding some explanations:
The first thing is to take care of the sampling frequency. Whenever one
wants to do signal processing, it is very desirable to sample at a fixed
and known frequency. This is next to impossible to achieve by looping
over analogRead(), because the CPU time needed to go through the loop
is hard to predict, as it can be influenced by interrupts and by
conditional branches. analogRead() is also highly inefficient, as it
locks the CPU in a busy loop while it waits for the analog-to-digital
converter (ADC) to do its job.
The solution is to put the ADC in the so called "free running mode". In
this mode, it starts a conversion as soon as the previous one is
finished, which gives a very steady sampling rate of 9.615 kHz (one
sample every 104 µs). The samples are handled by an interrupt
service routine called ISR(ADC_vect) which gets triggered every time a
sample is ready. This is also where all the signal processing is done.
Below is a detailed explanation of every line of code in the ISR:
int8_t sample = ADCH - 128;

Reading the ADC result is the first thing to do in the ISR. Since we do
not need the full 10 bit resolution, the ADC was configured to
left-adjust its result. Then we get an 8-bit result by just reading the
high byte of the ADC data register. We subtract 128 to remove the DC
offset and get a signed number in the range [−128 .. +127].
Next, we update the phase of our local oscillator:
static uint16_t phase;
phase += PHASE_INC;

We need not worry about possible overflows: since the phase is kept in
units of 1/216 cycles, the increment automatically works
modulo one cycle. The phase increment should theoretically be 6815.744,
which is rounded to 6816. This makes the local oscillator fast by
0.0376 Hz, which is negligible given the accuracy of the Arduino
clock. The phase could be kept in an 8-bit variable, but the rounding
error would then make the oscillator fast by 14 Hz, which can be
borderline unacceptable.
Next we need to build two square waves in quadrature, which will be used
as rough approximations of sin() and cos(). But since the most
significant bit of the phase is on during half of the cycle, it can be
used as one of our square waves. The other wave is obtained in a similar
way, after adding 1/4 cycle to the phase. So here is how we multiply our
sample by the square waves:
int8_t x = sample;
if (((phase>>8) + 0x00) & 0x80) x = -1 - x;
int8_t y = sample;
if (((phase>>8) + 0x40) & 0x80) y = -1 - y;

The expression phase>>8 is only meant to hint the compiler that it
needs only to consider the most significant byte of the phase. This
should normally not be needed, but I noticed that, without this hint,
gcc generates suboptimal code. The -1 in the above lines are for
avoiding a possible overflow.
Next comes the low-pass filter:
signal_I += x - (signal_I >> LOG_TAU);
signal_Q += y - (signal_Q >> LOG_TAU);

Where signal_I and signal_Q are volatile int16_t globals, and
LOG_TAU is 6. This filters with a time constant

τ = 64 × 104 µs = 6.656 ms

which translates to a −3 dB bandwidth of

Δf = 1/(2πτ) = 23.9 Hz.

which is fairly narrow for a 1 kHz signal. The significance of τ is
that, once the tone starts, it takes the filter about
2.3 τ ≈ 15 ms to reach 90% of its final output. Both
τ and Δf can be changed by simply changing LOG_TAU.
This ISR takes about 176 CPU cycles (11 µs, including the
4 cycles needed to put the CPU in interrupt mode) every
1664 cycles (104 µs). This amounts to about 10.6% of the
available CPU power. And since everything is done inside the ISR, the
program is free to do whatever else needs to be done while the data
acquisition and digital filtering happens in the background.
I tested the program by sending it a sine wave of 4.36 V
peak-to-peak amplitude. The reported power fluctuated quite a bit, but
here are the approximate average readings as a function of the input
frequency:
frequency  |  power
-----------+-------
   929 Hz  |   480
   976 Hz  |  2400
  1005 Hz  |  4600
  1028 Hz  |  2700
  1079 Hz  |   480


text:
Dot Matrix Display with Arduino UNO (PROBLEM)
I faced a problem in my graduation project and I hope you can help me to solve it :)

My project is connecting Arduino Uno to 16x32 Dot Matrix Display(DMD) and display messages on it from VB.net program. I wrote my VB.net program to convert the input text into 2D binary array. The number of columns depend on the text width.
as we know Arduino Uno SRAM is too small just 2 KBytes, so can't receive all the columns and display it.
I tried to receive 100 columns in the Arduino code and display it, then send star * to computer to receive the second 100 columns and display it and so on but it didn't work. I see the RX and TX of Arduino LEDs flicker but then nothing gets displayed on the DMD.
Can anyone tell me where is the error part in the code, or if you have another idea to solve this problem :)
VB.net Code for sending the 2D array ar(,)
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        SerialPort2.Open()
        Dim la As String
        If CheckBox1.Checked Then
            la = "arabic"
        Else
            la = "english"
        End If
        SerialPort2.Write("#" + cols.ToString + "#" + "*" + la + "*")
        Dim INDEX As Integer = 0

        While INDEX <= cols
            Dim see As String = SerialPort2.ReadLine().ToString()
            If see = "*" Then
                Dim BUFFER(16) As Byte
                For I = INDEX To INDEX + 100
                    If I < cols Then
                        For J = 0 To rows - 1
                            BUFFER(J) = ar(I, J)
                        Next
                        SerialPort2.Write(BUFFER, 0, 16)
                    End If
                Next
                INDEX += 100
            End If
        End While
        SerialPort2.Close()
End Sub

C++ Code for receiving 100 columns and display them:
#include <SPI.h>
#include <DMD2.h>

SoftDMD dmd(1,1);
void setup() {
  Serial.begin(9600);
  dmd.setBrightness(255);
  dmd.begin();
}
long Wid;
void loop() {
  if(Serial.available()){
    String st = String(Serial.readString());
    Wid = (st.substring(st.indexOf('#')+1, st.lastIndexOf('#'))).toInt();
    //String Language = st.substring(st.indexOf('*')+1, st.lastIndexOf('*'));
  }
  long ind = Wid ;
  while(ind >= 0 ){
    Serial.println("*");
    if(Serial.available()>1 ){
      boolean pixls[16][100];
      getArray(pixls);
      displayArray(pixls);
      ind-=100;
    }
    if(ind >=Wid){
      ind = wid ;
    }
  }
}

void getArray(boolean arr[16][100]){
  byte serialData[16];
  for(int k = 0 ; k < 100 ; k++){
    Serial.readBytes(serialData,16);
    for(int i = 0 ; i < 16 ; i++){
      arr[i][k]= serialData[i];
    }
  }
}

void displayArray(boolean arr[16][100]){
  for(int h = 0 ; h <= 100-33 ; h++){
    for (int i = 0 ,g=h; i < 32 ,g<h+32; i++ ,g++){
      for (int j = 0 ; j < 16 ; j++){
        dmd.setPixel(i,j,(arr[j][g] == 1) ? GRAPHICS_ON : GRAPHICS_OFF);
      }
    }
    delay(100);
  }
}

This VB code works for me when sending just 100 columns of the array:
SerialPort2.Open()

        Dim BUFFER(16) As Byte
        For J = 0 To 100
            For I = 0 To rows - 1
                BUFFER(I) = ar(J, I)
            Next
            SerialPort2.Write(BUFFER, 0, 16)
        Next
        SerialPort2.Close()

C++ code:
#include <SPI.h>
#include <DMD2.h>
SoftDMD dmd(1,1);

void setup() {
  Serial.begin(9600);
  dmd.setBrightness(255);
  dmd.begin();
}
void loop() {
    boolean pixls[16][100];
    for(int i=0 ;i<100 ; i++){
      for(int j=0 ;j<16 ; j++){
        pixls[j][i]=0;
      }
    }
    if(Serial.available()>0){
      getArray(pixls);
      for(int i=0 ; i<100 ; i++)
      {
        displayArray(pixls);
      }
    }
}
void getArray(boolean arr[16][100]){
  byte serialData[16];
  for(int k = 0 ; k < 100 ; k++){
    Serial.readBytes(serialData,16);
    for(int i = 0 ; i < 16 ; i++){
      arr[i][k]= serialData[i];
    }
  }
}

void displayArray(boolean arr[16][100]){
  for(int h = 0 ; h <= 100-33 ; h++){
    for (int i = 0 ,g=h; i < 32 ,g<h+32; i++ ,g++){
      for (int j = 0 ; j < 16 ; j++){
        dmd.setPixel(i,j,(arr[j][g] == 1) ? GRAPHICS_ON : GRAPHICS_OFF);
      }
    }
    delay(100);
  }
}

but it didn't work. - what happens? Does anything get displayed?

nothing get displayed but there is flicker in RX and TX of arduino leds

I make some edit on my post please read it again :)

I suggest some debugging displays. It seems weird to me to convert characters into pixels and send them one byte at a time from one processor to another. Can't you at least send as 8 bits in one byte? I'm not going to guess what is being generated on one end, and how that is being processed on the other. That is why you put debugging "prints" inside your code. To find out for yourself.

  boolean pixls[16][100];

You are running out of RAM, amongst other possible problems.
That array alone takes 1600 bytes out of 2048 on the Uno. Since you are using Serial that also takes:

34 bytes for the HardwareSerial instance (Serial)
64 bytes for the Serial transmit buffer
64 bytes for the Serial receive buffer
4 bytes for the Serial transmit buffer head and tail pointers
4 bytes for the Serial receive buffer head and tail pointers

That's another 170 bytes.
SoftDMD dmd(1,1);

I presume that also uses RAM.
You need to rework. You don't need to store 100 bytes before displaying. How about reading each byte and displaying it? That saves almost 1600 bytes.

i tried to receive just 100 columns and displaying them ,and it works well

@HaithamAL-Cigeary I suggest sending the ASCII text to the Arduino and then letting the font library within SoftDMD convert it to pixels.

You have likely run out of RAM.
The following use up large chunks of your SRAM:

pixls array = 1600 bytes
Serial = 170 bytes
DMD > 64 bytes

This is in addition to all your other variables and function calls.
The problem is that the compiler promotes boolean variables to bytes. So where you need 1600 pixels it takes 1600 bytes. Alternatively, you could pack 8 pixels into that byte. This method would only consume 200 bytes instead of 1600.
Also, I don't understand why you have a 16 by 100 array. From the code I can see that you are using a single DMD which has 32 pixels wide by 16 pixels high. Why send/buffer more pixels than needed? A single DMD would only need an array of 64 bytes.
The Arduino Uno only has 2KB of SRAM.
Solutions:

I suggest sending the ASCII text to the Arduino and then letting the font library within SoftDMD convert it to pixels. That is why you are using the DMD2 library.

However if you want to stick to the approach you have taken:

Pack 8 pixels into every byte in the array. This will save 1400 bytes of precious SRAM.
Only send one DMD word of data at a time. This will save 1536 bytes of precious SRAM.
You could use an Arduino with a greater amount of SRAM.

Arduino Mega  - 8KB SRAM
Arduino ZERO  - 32KB SRAM
Arduino Due   - 96KB SRAM
Arduino MKR 1000/1010/1400/ZERO - 32KB SRAM


text:
Motor shield causing problems with interrupts?
I am making a controller for a model railway turntable and I need to control a single DC motor and read a hall effect sensor. I have the hall effect sensor connected to pin 2 on my Uno (since 2/3 are the only pins that support interrupts) but whenever I turn the motor on it triggers the interrupt on pin 2 despite the fact that the motor PWM pin is on pin 11 and I have disconnected alternate PWM pin 3. This is with the official Arduino motor shield and an Uno.
I'm at a loss here, any ideas? I know it's not the motor triggering the hall effect sensor because I connected a resistor in place of the motor and it still happened.

How much power does the DC motor require? It sounds like if it is a reasonably sized motor, it may be drawing too much power when it is on. It is always a good idea to have motors connected up to an external power supply e.g. battery pack.

Ah forget that, just properly read your last sentence.

The motor is not actually powered from the Arduino, it's powered from an external 13.8v power supply capable of delivering 19A. (That PSU runs other things too but I can assure you it's not at capacity) I bent the "Vin" pin out of the way on the motor shield so I wouldn't run 13.8v into the Arduino, could that be causing problems?

How does the hall sensor work? Is it passive? Is it detecting something and hence triggering the interrupt? But wait, you say that it happens when you connect a resistor in place of the motor, but you originally say that the interrupt happens when you turn the motor on? Where are you connecting the other end of the resistor to, the ground pin?

The motor is connected via the "B" screw terminals on the motor shield. The PSU is connected via the "Vin" and "GND" terminals on the motor shield. When I connect the resistor, I simply connect it between the two "B" terminals, right where the motor normally is. It connects to a ground pin, but not the ground pin on the Arduino headers, the one on the 13.8v external PSU. Link to motor shield

Hmm hard to diagnose without seeing the setup tbh, sorry. One thing I would say is that 13.8v sounds high for the Arduino - the max is 12v as stated in the documentation with 1A limit from what I have read. I would strongly suggest you try a lower powered PSU. You may damage your board if it is connected directly, and that could also cause the problem you've stated.

actually on the motor shield the max current is 4A with an external psu

I will try it in a little bit, but if that is the problem I misunderstand how current flow works. The motor itself has a max rated current of 1a, and I have run it on a 1a fuse before and never blown the fuse. If the motor doesn't draw over 1a, won't that not damage anything? I'll try a lower amperage PSU just the same, I'm just wondering.

The screw terminals have a higher limit, but according to the shield docs, you may need to cut the Vin connect jumper on the back of the board to feed in more power

You may well be right, not sure! Just a suggestion as I can't think of anything else. Check the docs: https://www.arduino.cc/en/Main/ArduinoMotorShieldR3

@bladepanthera,  re “13.8v sounds high for the Arduino - the max is 12v as stated in the documentation with 1A limit”, see ArduinoBoardUno at arduino.cc.  Max is 20 V, not 12.  The range 7 V to 12 V is recommended rather than required.  13.8 V to VIN or the power jack on an Uno  is ok as long as current draw on the Uno isn't too high. (High draw at high voltage can overheat the Uno's 5 V voltage regulator.)  If motors are wired correctly, motor board current isn't relevant to Uno current except for however many milliamps the L298 logic takes.

@jwpat7 That's what I was thinking, and since the Uno is connected via USB for data anyway I was powering the Uno and 5v stuff off USB and the motor off the 13.8v supply. I just bent the VIN pin off to the side so it didn't connect. Could this be the problem? Do I need to also bend GND pins?

@jwpat7 I stand corrected. :) I don't see why the GND pins should be making any difference if the Vin is not in use, but I'm happy to be corrected about that, too.

The motor, driver board, and Uno grounds should be star connected to a common point so no motor currents go through the wire to the Uno ground.   The  motor shield probably more or less does that.   If you have a DSO you should be able to get a picture of whatever transient voltage noise is causing the interrupt.  I'd try putting a 330 uF cap from 5V to GND on the shield in case the problem is due to high current switching on the shield, and a 10 to 100 nF cap from GND to pin 2 in case EM noise is the problem.   How fast does your interrupt need to respond?


text:
Trying to verify that Arduino Pro Micro ISP is working
I'm trying to program an Arduino Pro Micro with another Arduino Pro Micro. The purpose is to verify that I can use this Pro Micro board reliably as an ISP to program another Arduino device that does not have a USB interface.
These are actually Pro Micro clones but they seem to work quite well using the Arduino Leonardo profile. I'm following this pinout.
Here is the photo of the setup:

The "red" Pro Micro is set up as ISP using the stock ArduinoISP sketch (didn't think anything needed changing). The "white" Pro Micro is the one I'm trying to program.
The pins are connected, 5V - 5V, GND - GND, MISO - MISO, MOSI - MOSI, SCLK - SCLK, Pin 10 - Pin 10 (reset? this might be wrong).
I've confirmed the ISP sketch is running by the green heartbeat LED. The three LEDs on the red board are connected to pins 7 (top), 8, 9 (bottom), with 9 being the heartbeat.
I loaded the Blink sketch and changed the LED pin to pin 9 since the default pin 14 on the white board is being used as the MISO pin for programming.
In the IDE, I set the board to Arduino Leonardo, port to the red board's port, programmer to "Arduino as ISP" and ran "Upload Using Programmer".
The only output I get is:
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

Since I'm really just beginning all of this, I'm a bit confused what might be wrong and what could be a next troubleshooting step. Any help appreciated.

"Pin 10 - Pin 10 (reset? this might be wrong)." yepp, should be Pin 10 - RST (on target).

As Mikael Patel notes, pin 10 on the programmer Pro Micro should run to RST on the target.
That might or might not fix the problem.  In some previous instances of the “Yikes! Invalid device signature” [1,2] bad breadboard connections turned out to be the problem.  I suggest you run a second (or even a third) set of jumpers in parallel with the first set.  Of course use matching colors to avoid confusion.

I've done that to no avail. Doesn't seem to make a difference.