text:
Multiple If statements
I am using following code for my arduino project in which i have to control a dc motor using arduino uno via text messages.
my question is that i have used multiple number of 'If' statements and only one else statement at the last, i compiled this code and gives no error, is it ok to use multiple If statements one after another without using else after each if?
#include <LiquidCrystal595.h>
#include <GSM.h>

GSM gsmAccess;
GSM_SMS sms;
char sendernumber[20];
int Enable_m=11;
int Control_2=12;
int Control_7=10;
LiquidCrystal595 lcd(7,8,9);
void setup()
{
   Serial.begin(9600);
   pinMode(Enable_m,OUTPUT);
   pinMode(Control_2,OUTPUT);
   pinMode(Control_7,OUTPUT);

   digitalWrite(Enable_m,LOW);
   digitalWrite(Control_2,LOW);
   digitalWrite(Control_7,LOW);

   lcd.begin(16,2);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Hello");
   lcd.setCursor(0,1);
   lcd.print("Everyone");
   delay(2000);

   while (!Serial)
      Serial.println("SMS Messages Receiver");
   boolean notConnected = true;
   while(notConnected)
   {
      if(gsmAccess.begin("0000")==GSM_READY)
         notConnected = false;
      else
      {
         Serial.println("Not connected");
         delay(1000);
      }
   }
   Serial.println("GSM initialized");
   Serial.println("Waiting for messages");
}

void loop() {
   // put your main code here, to run repeatedly:
   char c;
   int val=0;
   val=digitalRead(Enable_m);
   if (val==LOW){
      digitalWrite(Enable_m,HIGH);
   }
   if (sms.available())
   {
      Serial.println("Message received from:");
      sms.remoteNumber(sendernumber, 20);
      Serial.println(sendernumber);

      if(sms.peek()=='#')
      {
         Serial.println("Discarded SMS");
         sms.flush();
      }
      while(c=sms.read())
         if(c=='motoroff'){
            analogWrite(Enable_m, 0);
            digitalWrite(Control_2,LOW);
            digitalWrite(Control_7,LOW);

         }
      if(c=='motoronclockwise'){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='motoronanticlockwise'){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,HIGH);
         digitalWrite(Control_7,LOW);
      }
      if(c=='speedhalf'){
         analogWrite(Enable_m, 128);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='speedquarter'){
         analogWrite(Enable_m, 65);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='speed75'){
         analogWrite(Enable_m, 192);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else{
         digitalWrite(Enable_m,HIGH);
         Serial.print(c);
      }
      Serial.println("\nEND OF MESSAGE");
      sms.flush();
      Serial.println("MESSAGE DELETED");
   }

}

A 'list' of if statements should be implemented as a switch/case statement; this is used where a single variable has many possibilities, and allows a 'default' case which does what you think your final else statement does. However, as Majenko says, you can't directly compare strings as your are doing.

@CharlieHanson so i can replace the if's with labels and set the value of the variable equal to the incoming message?

#include <LiquidCrystal.h>
#include <GSM.h>

GSM gsmAccess;
GSM_SMS sms;
char sendernumber[20];
int Enable_m=11;
int Control_2=12;
int Control_7=10;
LiquidCrystal lcd(7,8,9,8,1,2,3,4,5,6);

void setup()
{
   Serial.begin(9600);
   pinMode(Enable_m,OUTPUT);
   pinMode(Control_2,OUTPUT);
   pinMode(Control_7,OUTPUT);

   digitalWrite(Enable_m,LOW);
   digitalWrite(Control_2,LOW);
   digitalWrite(Control_7,LOW);

   lcd.begin(16,2);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Hello");
   lcd.setCursor(0,1);
   lcd.print("Everyone");
   delay(2000);

   while (!Serial)
      Serial.println("SMS Messages Receiver");
   boolean notConnected = true;
   while(notConnected)
   {
      if(gsmAccess.begin("0000")==GSM_READY)
         notConnected = false;
      else
      {
         Serial.println("Not connected");
         delay(1000);
      }
   }
   Serial.println("GSM initialized");
   Serial.println("Waiting for messages");
}

void loop() {
   // put your main code here, to run repeatedly:

   // I chose 160 since that is max size for sms
   char message [160];
   // this fills message with null characters
   memset( message, '\0', sizeof(char)*160 );

   int val=0;
   val=digitalRead(Enable_m);
   if (val==LOW){
      digitalWrite(Enable_m,HIGH);
   }
   if (sms.available())
   {
      Serial.println("Message received from:");
      sms.remoteNumber(sendernumber, 20);
      Serial.println(sendernumber);

      // you used single qoutes properly here
      // single qoutes denote a char which is a single character
      if(sms.peek()=='#')
      {
         Serial.println("Discarded SMS");
         sms.flush();
      }

      // this will add the characters to messages[]
      for(int i = 0; message[i] = sms.read(); i++){}

      // I changed this to double qoutes since you need double
      // qoutes to denote a string literal
      if(strcmp(message, "motoroff") == 0){
         analogWrite(Enable_m, 0);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,LOW);
      }
      else if(strcmp(message, "motoronclockwise") == 0){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else if(strcmp(message, "motoronanticlockwise") == 0){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,HIGH);
         digitalWrite(Control_7,LOW);
      }
      else if(strcmp(message, "speedhalf") == 0){
         analogWrite(Enable_m, 128);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else if(strcmp(message, "speedquarter") == 0){
         analogWrite(Enable_m, 65);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else if(strcmp(message, "speed75") == 0){
         analogWrite(Enable_m, 192);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      // This else will only be executed if the previous if and else if statements are false
      else{
         digitalWrite(Enable_m,HIGH);
         Serial.print(message);
      }
      Serial.println("\nEND OF MESSAGE");
      sms.flush();
      Serial.println("MESSAGE DELETED");
   }

}

So I've made some edits to your code. For example this code 'motoronanticlockwise' isn't correct. Single quotes are used for char data types and double quotes are used for string literals. You should use double quotes since there are multiple characters "motoronanticlockwise". Also as Majenko said you would have to use strcmp() in order to compare c-strings
c-strings are char arrays that have a null terminator '\0'. Also strcmp() returns 0 if the two strings are equal.
Your last else statement will only executed if the previous if statement is false. It seems like you only want it to execute if all of the previous if statement are false. To do this you make the first if statement and then make a chain of if else statements followed by a single else statement. You can have a single if statement with no else or if else statements however, if you want else or if else statements then you need to have an if statement. I've made the necessarily edits to your code already.
Lastly, this part of the program is the biggest problem while(c=sms.read()) This is because sms.read() returns a char so you can only read the sms message one character at a time. To do this properly you should make a character array and store the values returned by sms.read() in it. This can be done like this
char message [160]; // I chose 160 since that is max size for sms
memset( message, '\0', sizeof(char)*160 ); // this fills message with null characters
// this will add the characters to messages[]
for(int i = 0; message[i] = sms.read(); i++){}

I am using a for loop to iterate through message[].
Try the above and get back to me if there are any problems with it.

I apologize for late reply, and thank you for your time to answer the question. I'll check the code on hardware and let you know. Again thanks for you help, I really appreciate that.

sketch_oct16a.ino: In function 'void loop()':
sketch_oct16a:81: error: 'messages' was not declared in this scope
sketch_oct16a:114: error: 'messsage' was not declared in this scope
what does this mean? i verified and this error came up

I screwed up, those are just typos. I edited the code in my answer.

Yeah i thought so, its OK now verified. cheers

Two things:

The else will only be subject to the last if being false, the rest of the if statements are completely separate and can affect the else in no way whatsoever.  To chain them you need if (...) { blah blah } else if (...) { blah blah } etc.
You cannot compare characters and strings like that (and in fact they're not even strings, they're lots of characters squeezed into a single character through the use of the wrong kind of quotes).

So basically no, your whole program there is completely wrong and won't do what you think it will and you need to completely re-thing how it works.
Some tips:

Use strcmp() to compare strings.
If reading strings from serial store them in character arrays not a single character.

You might find this useful:

http://hacking.majenko.co.uk/reading-serial-on-the-arduino
http://hacking.majenko.co.uk/the-evils-of-arduino-strings

So you are saying that i should create an array of strings and then using 'strcmp()' to compare them. Then how would i assign each string a seperate function?

No, I am saying each string should be an array of characters. Google for tutorials on "C strings".

then i have to define each array like i have at the beginning and just refer to it in the conditional statement?

Ask google to show you. It's better at it than me trying to teach you the basics in comments. There's literally a bazillion examples and tutorials out there. Go and read them.

i was going through that link it and its quite useful. thanks.

If you intend each if statement to be executed, regardless of the whether the prior one(s) did, then yes, they do not require else clauses.
If you mean to try each condition until you find one that is true, and execute that one and only that one, then the second and subsequent ifs need to be else ifs. The final one may be just an else, if you want a catch-all clause; or an else if if it is possible that none of the clauses might need to be run.
Update: To execute at most one clause, you need to use if, some else ifs, and maybe a final else.
If you're trying to match strings, you can use an array of strings or use literal strings as you've tried to do. Strings have to be enclosed in double-quotes (") however, not the single quotes you've used. And the variable char c; you tried to use to hold the SMS message is really only one character. You'll need to make it an array of characters such as char c[140+1];,  the size of the longest SMS message + one more for a  zero-character string-terminator. C doesn't directly compare strings as simple variables so == and != won't work here. You'll need to compare them with strcmp().

from all the conditions only one has to be true. so when the string is matched it should execute only that condition and wait for the next message to arrive.


text:
Arduino Nano, ICSP header and 595 Shift register
I'm trying to control a 4-digit 7 segment display with an Arduino Nano, but I'm getting something wrong. I'm using the ICSP header to interface with a 74HC595 Shift Register which is then connected to the display. I've tested and retested the connections and everything seems to be alright, however the shift register doesn't have the desired output, and I notice it only shifs one single bit when I press the reset button on the arduino board.
74HC595   |    A. Nano
DS     <-----> MOSI (ICSP)
SH_CP  <-----> SCK (ICSP)
ST_CP  <-----> D6
MR     <-----> 5V (ICSP)
OE     <-----> GND (ICSP)
VDD    <-----> 5V (ICSP)
GND    <-----> GND (ICSP)

My code:
//pin connected to STCP
const int latchPin = 6;
//pin connected to SHCP
const int clockPin = 17;
//pin connected to DS (MOSI)
const int dataPin = 11;

byte val=0;

void setup() {
  // put your setup code here, to run once:
  //SPI pins are output
  pinMode(latchPin,OUTPUT);
  pinMode(clockPin,OUTPUT);
  pinMode(dataPin,OUTPUT);

  pinMode(3,OUTPUT);
  updateRegister(0);

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(3,HIGH);
  for (int i=0; i<8; i++) {
    updateRegister();
    delay(500);
  }

}

void updateRegister() {
  //pull latch low to write new bits to the register
  digitalWrite(latchPin,LOW);
  //shift out the data
  shiftOut(dataPin,clockPin,LSBFIRST,val);
  //pull latch pin high so that the leds light up
  digitalWrite(latchPin,HIGH);
}

This site has a question and answer format. What is your question, exactly? (Note that questions generally end with a question mark). Please read How do I ask a good question?

Please post a schematic of your wiring. You say in the question that you are using the ICSP header, but then the code uses pins 6 and 17 which are not ICSP (or SPI) pins.

const int clockPin = 17;
I'm pretty sure that should be 13, not 17.

Yup, this was my mistake. http://christianto.tjahyadi.com/wp-content/uploads/2014/11/nano.jpg this image mislead me to believe SPI clock was at pin 17. With pin 13, the display is operating as it should.

It is extremely confusing to have a variable val and then use _val in your function but then:
  shiftOut(dataPin,clockPin,LSBFIRST,val);

As James pointed out, you are not sending the value passed to the function, to the shift register.
Also this is just going to give you a boolean:
 updateRegister(!i);

Why take "not i" there?

I suggest you use SPI and not muck around with shiftOut. I have a page about the 595 chip including example code. eg.
#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

I posted the code with some errors (I was paying with the varaibles trying to solve the problem). As it was it was bovisously not going to work, but that was not the cause of the problem. I tried that snippet with the SPI library, but the display/leds do not light up at all. Also, it just crossed my mind - could the problem be caused by calling shiftOut() on SPI pins?

What LEDs exactly?

could the problem be caused by calling shiftOut() on SPI pins? - No. If you don't call SPI.begin() then SPI is inactive.

The leds on the 7-segment display

Do you need to add the _  to the shiftOut(dataPin,clockPin,LSBFIRST,val); ?

James, you were right about the underscore, but the Stack Exchange system automatically flags very short answers. If you expand it out a bit more you are protected from this automated flagging. Welcome to Arduino Stack Exchange. :)

It was a mistake, I was tinkering with the code. I've updated the question, but I can say that was not the source of the problem.

Your updated code sends 0 to the shift register, so I'm not too surprised nothing lights up.

The 7-segment display has a common anode, sending a '0' to the shift register should light up all the segments (an '8'), since I'm pulling the anode up with 'digitalWrite(3,HIGH); '

source: Stack Exchange

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

authors: אורין אפשטיין

sort: votes


text:
Existence of a non blocking and task yield framework for Arduino programming
I've been playing around with Arduino and understand that the standard runtime provides a single thread essentially.
I was wondering if it is possible to write a thin layer (library) that allows one to write code that is non blocking and one where each task yields control manually which allows the master loop to implement some form of timesharing.
I'd appreciate any:

Comments on existing frameworks that can allow me to write my programs this way
Any comments on how hard implementing anything of this order of magnitude would be.

Similar to http://arduino.stackexchange.com/questions/286/how-can-i-create-multiple-running-threads

You are vaguely describing an RTOS, which while there are some out there that target Arduino, (IMHO) they aren't very practical except in a few narrow use cases.

I would recommend NilRTOS.
I like the fact that it's really minimal.
However, you might find that some libraries (which you would like to use) work in blocking mode and cannot be used with this RTOS, because they might do bad things (polling) or worse things (polling in interrupt context with other interrupts disabled).
But that will be the case regardless of the thread framework you choose.
You might want to try also femtoos.
I think that the code could be organized far better, which is one of the reasons I preferred NilRTOS.

My recommendation would be to simply code without needing blocking. I have examples here.
Petri Häkkinen coded a game - Toorum's Quest - without using any real-time library. That game (on a Uno) has multiple sprites, TV output and sound effects, all interleaved.
The basic technique is to know that you have multiple things you need to have done, from time to time, and check in the main loop if it is time to do one of them.
One issue with any sort of real-time library is, you only have limited resources. You need to be really aware, for example, of which bits of hardware are doing what (eg. timers, SPI, I2C, interrupt handlers, serial comms).
Even existing libraries suffer from the problem that one library may require (say) pin-change interrupts, and "requisition" the interrupt handlers needed for that, and another library also uses pin-change interrupts, and they cannot be linked together.

I do not see how the RTOS is a problem in the situation described. It's actually sort of typical (and, frankly, very annoying/disappointing) that 2 or more libraries contend the use of the same timer. I'd rather patch them, drop the meddling with the timer and let the RTOS call them when appropriate. If anything, this shows a shortcoming of the Arduino libraries, where there is no standardized way to do timed stuff and the author of each library is let alone to figure out what HW timer to use.

It's not a problem that has an easy solution. Things like pin-change interrupts, for example, used by SoftwareSerial. Once you add one of the interrupt handlers you are committed to handling 8 pins. And how do you handle when one library wants timer 2 for timing an event, and another one wants it to do PWM?

As I said: let the RTOS replace the direct use of the timer.
If a library just needs a periodic signal, most likely the RTOS can replace the timer handler with a thread. Same goes for PWM.
Of course it depends on the time resolution and precision required. But I think in most cases it would be sufficiently accurate.
Software Serial is something beyond redemption, as it busy loops in interrupt context. It's ok for a simple project, but in a serious application, I would definitely not use it, as the delay is not even fixed, but depends on the baud rate.

For the pin change interrupt, I think that's another short coming of the standard Arduino library. IMHO there should be a default, standard, way of running timed tasks and to get the OS to handle inputs/outputs, like providing the first/last time an input line changed or generate a pwm by sw on an arbitrary pin. I moved away from the Arduino standard libraries after noticing that thy make it harder to do apparently simple tasks.

That horse has probably well and truly left the stable by now. A lot of libraries assume you are only going to use their library (or at least not another one with conflicting requirements). To have imposed a RTOS during the early days of design would probably have been too hard, and now it is too late. The other issue is memory. To have multiple threads you need multiple stacks, and probably multiple heaps. It's going to get rather hard to manage all this when you only have 2 KB of RAM to start with.

True, the horse has left the stable and so have I left those libraries ;) But it is not a big deal, at least for my needs. In the end i'd rather spend time learning the AVR than trying to workaround limitations coming from sw that was in most cases designed to perform only 1 task.

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


text:
Compare the new sample in a high sampling rate datalogger
I am using sdFat library the analog bin logger example,
Github: SdFat/SdFat/examples/AnalogBinLogger/

The program is working fine and every thing but the thing is, this high speed datalogger uses interrupts and timers to make the ADC work at a pre-determined sampling frequency and it DOES NOT use the normal analogRead ()
What I want is, when the input of some analog pin is bellow a pre-determined value, I want to write HIGH or LOW to some digital pin,
my question is, how can I compare the new sample in the analog bin logger example as I simply want to compare the new sample as in:
if ( analogRead() < 256 ) {// do something}

knowing that there is no analogRead() in the program because it uses timers and interrupts.

In the function
ISR(ADC_vect) {

the variable d contains the current sample:
  // Read ADC data.
#if RECORD_EIGHT_BITS
  uint8_t d = ADCH;
#else  // RECORD_EIGHT_BITS
  // This will access ADCL first.
  uint16_t d = ADC;
#endif  // RECORD_EIGHT_BITS

So you can just "do something" depending on what is in d.  Of course, since this is a timer interrupt you have limited time to do anything, so you need to make sure that whatever you do is fast and efficient - so really you want to be using direct port access instead of digitalWrite().

this is perfect, thanks
but how to know which analog pin that this d value belongs to, because more than one channel are being used? @majenko

@SabirMoglad Try looking at adcindex.


text:
How do I receive more that 64 bytes with Arduino
I am using QtSerialPort to send and receive data from Arduino. I am sending more than 64 bytes (125, 220, more), I receive the data with Arduino, and trying to sending back the same data, but Arduino sending only 64 bytes in its response. Then I am thinking that the problem is with Arduino buffer. I am trying to clear the data but without result.
Here is my Arduino code:
void loop() {
    if (Serial.available() > 0) {
        int i = 0;
        delay(500);
        int size = Serial.available();
        while (i < size)
            buffer[i++] = Serial.read();

        Serial.print(buffer);
        //delay(500);
        int j = 0;
        while (j < size)
            buffer[j++] = '\0';
        //while (Serial.available()) Serial.read(); I tried it
        //Serial.flush();   Also tried it, but nothing.
    }
}

Remove the delay(500): during this delay, you are letting the internal buffer of Serial overflow. Instead of just wasting 500 ms, you should be copying the incoming data into your own buffer array as it comes.

Instead of blocking the loop for 500 ms, you should be actively
reading the data as it comes. Otherwise the internal buffer of the
Serial object will overflow after only 64 bytes are received.
Here is an example that copies the incoming bytes into a larger buffer
(256 bytes) and, upon receiving an end-of-line character, echoes
back the whole line.
void loop() {
    static char buffer[256];
    static size_t pos;              // position of next write

    while (Serial.available() && pos < sizeof buffer - 1) {

        // Read incoming byte.
        char c = Serial.read();
        buffer[pos++] = c;

        // Echo received message.
        if (c == '\n') {            // \n means "end of message"
            buffer[pos] = '\0';     // terminate the buffer
            Serial.print(buffer);   // send echo
            pos = 0;                // reset to start of buffer
        }
    }
}

after every read action the buffer consume one character and the buffer size is menor? So if I constantly send data to  Arduino and constantly read from buffer, the buffer never going to be on overloaded?

Did not really understand your question. There are two buffers: the one from the Serial object (64 bytes), and your application's buffer. Which one are you talking about? At 9600 bps, each byte takes about one millisecond, which is plenty. As long as loop() runs often enough (with no delay()), the Serial buffer is not going to overflow.

The final result was receive each byte one by one and removed any delay in the code. Thank you @Edgar Bonet


text:
Printing Serial Readings for 2+ Parallax Ping Sensors
trying print values for two sensors, one works the other is 0, any tips on how i can use more than one?
const int pingPin = 10;
const int pingPinz = 11;
unsigned int duration1, duration2, inches1, inches2;

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

void loop() {
  pinMode(pingPin, OUTPUT);          // Set pin to OUTPUT
  pinMode(pingPinz, OUTPUT);          // Set pin to OUTPUT
  digitalWrite(pingPin, LOW);        // Ensure pin is low
  digitalWrite(pingPinz, LOW);        // Ensure pin is low
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);       // Start ranging
  digitalWrite(pingPinz, HIGH);       // Start ranging
  delayMicroseconds(5);              //   with 5 microsecond burst
  digitalWrite(pingPin, LOW);        // End ranging
  digitalWrite(pingPinz, LOW);        // End ranging
  pinMode(pingPin, INPUT);           // Set pin to INPUT
  pinMode(pingPinz, INPUT);           // Set pin to INPUT
  duration1 = pulseIn(pingPin, HIGH); // Read echo pulse
  duration2 = pulseIn(pingPinz, HIGH); // Read echo pulse
  inches1 = duration1 / 74 ;        // Convert to inches
  inches2 = duration2 / 74 ;        // Convert to inches
  Serial.println(inches1);            // Display result
  Serial.println(inches2);            // Display result
  delay(200);                 // Short delay
}

Your problem is in how you are working with the two sensors. At the moment you are triggering both sensors together then waiting for the first one to echo back. Only when that has responded do you then wait for the second one to echo back, and that echo has been and gone already.
Imagine you have two tennis balls. You throw them both at different walls at the same time, then attempt to catch them both. While you are catching the first ball the second one bounces off the back of your head and rolls under the table. That's what's happening with your echos.
So instead you need to treat both sensors completely separately. Trigger the first, then get the response. Then trigger the second and get the response.


text:
UART Software Serial - Syncing two sensors to make a tx and rx beacon
Problem
I've been trying to a create a receiver and transmitter beacon for a following robot, but have not been able to sync my two SRF02s to one another.
Any advice?
Code
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

void SendCmd(unsigned char address,unsigned char cmd)
{
  mySerial.write(address);//set the address of SRF02(factory default is 0)
  mySerial.write(cmd);//send the command to SRF02
}
void setup(void)
{
  Serial.begin(9600);
  mySerial.begin(9600);
  Serial.println("SRF02 TEST!");
}
void loop(void)
{
  unsigned long t3;
  unsigned long t1=micros();//time tx command issued
  SendCmd(1, 0x5C);//send pulse with transmitter
  unsigned long t2=micros();//time rx command issued
  SendCmd(2, 0x5B);//listen for pulse returns results in microsconds

 while(mySerial.available() < 2)//if two bytes were received
  {}
    t3 = mySerial.read()<<8;//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
    t3 |= mySerial.read();// receive low byte as lower 8 bits
    unsigned long Tm = t3 + t2 - t1;//total amt of microseconds between pulse and reading
    unsigned long Dist = (Tm/29); //converting microseconds to cm
    Serial.print(t3); // print the reading
    Serial.println("cm");
    //Serial.print(tm);
    //Serial.println("ms");

  delay(250); // wait to read the output

}

Output#

Your distances seem implausible, so you need to investigate.  Try printing out the components of the delay, both measured on the Arduino and on the sensor.  Also consider that sound will travel a fair fraction of a meter during the time it takes to send the second command, and see if the software serial output routines buffer or block until the data is actually sent.  Preferably, for precise timing you should use discrete strobe signals and hardware timers, not serial commands and software.,

How far apart are your 2 SRF02's?  Also, when debugging print the data in a raw form as well as (or instead of) processed -- ie, print out t1, t2, t3 as well as Dist

theyre roughly 15 cm apart

I don't think what you are trying to do is possible with those modules.
I think what you are trying to do is transmit a 40KHz pulse on one module and find out when it arrives at the other module. Unfortunately that is not going to be possible with serially attached modules - simply because it takes longer to transfer the serial data than it does for the ultrasound pulse to travel between the two modules.  That's why you're seeing such big values - you're actually measuring the amount of time it takes to transfer the serial data, not the sound.
For those modules to work they have to transmit a pulse themselves and then listen for that pulse and they return the difference between those two events. The timing for that is all done internally to the module and the results are returned through serial. Trying to perform the individual operations through serial is just not going to happen.
A better solution would be to modify an HC-SR04 module.  De-solder the transmitter from the board and re-connect it with some wires - that is then your remote module. You can do the same with the receiver module if you want it remote from the board if you like.  Then you interface the HC-SR04 direct to the Arduino and use it as you normally would.

Edit:
Ok, so it seems there is a method of using them (AKA "Fake" sensing - idiotic name if ever there was one) that could be made to work if it's done precisely right.
However, doing it precisely right, as you have seen, is not easy.  Timing is critical. Timing of when you send instructions, and how you determine exactly when an instruction has been sent.
You would be much better off using a real hardware UART than software serial. That would mean upgrading your board to one with more than one hardware UART since you are using the only one the Uno has for your serial monitor.
I would also recommend not using the Arduino's Serial object(s) for this since they impose their own buffering and asynchronous transfer of data which will really really mess with your timing.  Instead you should manually manipulate the registers directly - that way you can know exactly when the final bit of the serial commands have reached the ultrasound module.
You should also send the command to the receiver first before the transmitter.  Did you know that at 9600 baud it takes about 2ms to transfer two bytes?  In that time sound will have travelled about 68cm.  If you start the receiver first then start the transmitter the receiver will be running when the sound wave reaches it, as opposed to when the sound wave is somewhere in the next room.  Then of course you have to take into account the time between starting the two properly, and that all comes back down to knowing your timing exactly.

So what you're saying is that I would have to create a continuously pulsing transmitter at 40KHz and use the receivers in their standard mode? If that is the case am I covering the transmitting transducers on the receiver modules, but still sending a pulse to time the events between sending and receiving?

Actually this is not true.  I suspect it as well, but a quick lookup of the parts suggests that bistatic operation is a supported usage mode.  I join your concern about the latency of serial communication, but while suboptimal there are perhaps ways of working around it, for example starting the receiver first and determining a (with care potentially fairly constant) serial message delay to subtract.

@ChrisStratton I see what the "Fake" mode does now. That's really an incredibly stupid thing to call it...! So yes, it could be possible if you do it absolutely perfectly correctly and time everything precisely. Far from ideal though, especially on an Arduino that has so many variables - you'd be best off a) using a hardware UART, and b) not using the Arduino's Serial object with its asynchronous transmission.

Probably better to use I2C instead of Serial. However, note that error due to Serial latency should be less than 70 cm (the distance sound travels in the time taken to transmit 2 Serial bytes at 9600 bps), but the data shown varies rather more than that; and anyhow, variability due to that latency ought to be negligible, so it seems to me Serial latency isn't likely to be the problem, but something else.

But if i want to make a wirelss receiver and transmitter beacon, I am not able to used I2C correct?

theyre roughly 15 cm apart

15cm substantially less than the time it takes to send the second device its command at 9600 baud (2 bytes, probably 20 bits counting framing, around 72 cm)
As a result you are likely missing the pulse, and perhaps catching some timeout, or even a cached response string from a next-to previous command which measured the previous pulse, including the time between pulses.
To operate that close, you will need to either use dedicated trigger/detect wires, or start the receiver before you transmit and try to subtract the delay from the time you started the receiver until the time when you transmit.
Beware that usage of software serial, as well as buffering of serial in general may introduce variable latency in your timestamping of the serial communications.  Ideally for something like this you would use a non-buffered implementation - the timing of serial data itself is potentially precise to a fraction of the baud rate, though we don't know how it is implemented on the sensor end.

`void setup() {
//Choose 9600 baudrate
Serial.begin(9600);
}
int x; //Byte
int n; //Number of available bytes
void loop() {
//Address
Serial.write(2);
//calls address of srf02 - 0x02
Serial.write(0x51);
//Send Pulse from 0x00 - no ranging takes place
n = Serial.available();
if(n > 0){
for (int i = 0 ; i < n; i++){
unsigned long x = Serial.read();
Serial.print(x,DEC);
}
Serial.println();
}
delay(1000);
}`   This is another code with just serial.writes. do you think i'm better off implementing something like this?


text:
XBEE S1 Wireless Connection
I have 2 Xbee S1 models, 2 Arduino Wireless Proto Shields, 2 Arduino Megas, and an Xbee Explorer and am trying to make one Arduino Trigger another Arduino to send a pulse, I have tried to set up many tutorials on youtube and digi, but still cannot get it to work.
Can someone walk me through the steps for setup?


text:
Declare for loop as an array of variables
My goal is to store the variable in the for loop as an array rather than as a single 'ultrasoundValue'. Can some one help me structure the code?
I have this code:
int ultraSoundSignalPins[] = {5,7};
int tx = 4;
char *pingString[] = {"Ping1 ","Ping2 "}; // just something to print to             indicate direction

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

void loop()
{

 unsigned long ultrasoundValue;
 for(int i=0; i < 2; i++)
 {
   ultrasoundValue = ping(i);
   Serial.print(pingString[i]);
   Serial.print(ultrasoundValue);
   Serial.print("cm, ");
   delay(500);

 }
}

//Ping function
unsigned long ping(int i)
{
 unsigned long echo;

 pinMode(ultraSoundSignalPins[i], OUTPUT); // Switch signalpin to output
 pinMode(tx, OUTPUT);
 digitalWrite(ultraSoundSignalPins[i], LOW); // Send low pulse
 digitalWrite(tx, LOW);
 delayMicroseconds(2); // Wait for 2 microseconds
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Send high pulse
 digitalWrite(tx, HIGH);
 delayMicroseconds(5); // Wait for 5 microseconds
 digitalWrite(ultraSoundSignalPins[i], LOW); // Holdoff
 pinMode(ultraSoundSignalPins[i], INPUT); // Switch signalpin to input
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Turn on 0pullup resistor
 echo = pulseIn(ultraSoundSignalPins[i], HIGH); //Listen for echo
 return (echo / 29.1); //convert to CM then to inches
}

You don't even have to add any lines, just modify a couple!
unsigned long ultrasoundValue [2]; //creates an array of unsigned longs of size 2

...and inside your for loop:
ultrasoundValue[i] = ping(i);

It appears you are acquiring 2 separate ultrasound values. If you'd like to store multiple sets of these 2 values, you could use a two-dimensional array:
unsigned long ultrasoundValue [10][2]; //an array of 10 pairs of long unsigned values

...and you could modify your for loop to have a pair of nested for loops:
 for (int i = 0; i < 10; i++)
 {
   for (int j = 0; j < 2; j++)
   {
      ultrasoundValue[i][j] = ping(j);
      //do whatever else
   }
 }

Make ultrasoundValue an array and use i as the index to it? Just like you have with all your other arrays?
You obviously know how to use arrays, since you have already been using them throughout your code.


text:
How do I print the reading serial data sending from Arduino
I am sending data to Arduino using QtSerialPort. When I read the data the ouput has several not printer characters. I am using a QTexEdit (in left hand) to insert the data to send and other (in right hand) to insert  the data to read.

You can see the receive data has some no printer character.
Workflow of sending and receiving data between QtSerialPort and Arduino
Sending Data with QtSerialPort
void MainWindow::sendData(){

    QString m_allData = m_sendEdit->toPlainText();
    int i = 0;
    int size = m_allData.size();

    QString line = "";
    int c = 0;
    while(i < size){
        line.append(m_allData[i]);
        if(c == 24){
            int sended = m_serialPort->write(line.toUtf8(), 24);
            m_serialPort->flush();
            line.clear();
            c = 0;
        }
        i++;
        c++;
    }
    if(c > 0){
        m_serialPort->write(line.toUtf8(), c);
    }
    m_serialPort->flush();
}

I want to send the data with a buffer size of 24 bytes.
Reading and Sending Data with Arduino
 void setup() {
    Serial.begin(9600);
 }

 void loop() {

    delay(1000);

    if (Serial.available() > 0){
        short i = 0;
        int size = Serial.available();
        String data = Serial.readString();
        Serial.print(data);
    }
 }

The Arduino code is simple.
Receiving Data with QtSerialPort
void MainWindow::readData(){
    int c = 0;
    char * dataBuffer;
    int size = m_serialPort->bytesAvailable();
    dataBuffer = new char[size];
    c = m_serialPort->read(dataBuffer, size);
    m_receiveEdit->setText(m_receiveEdit->toPlainText() + QString::fromUtf8(dataBuffer));
        delete dataBuffer;
}

I am trying to read the same data that I send to Arduino. What kind of convertion do I have to do?

There is no point in splitting your writes into 12-byte chunks. The serial port is slow, and your Qt code is fast, thus the first byte of the second chunk will come right after the last byte of the first chunk.

You have no warranty that Qt will receive the whole message in a single
chunk. It may receive "no se" as the first chunk, and then "q pasa" as
the second chunk. Since dataBuffer is dynamically allocated, it
initially contains garbage, and you are printing the part of this
garbage that you did not overwrite.
An easy fix would be to simply NULL-terminate the buffer:
dataBuffer = new char[size + 1];            // + 1 byte for '\0'
c = m_serialPort->read(dataBuffer, size);
dataBuffer[c] = '\0';                       // terminate the string

Ok, that was the problem. with dataBuffer['c'] = '\0' the output data is clean. Thank you @Edgar Bonet


text:
Client.connect galileo gen2 not working
I'm having a problem with the intel galileo gen2 ethernet. I am trying to get a webpage, but I can only connect to the ethernet, not the webpage.
I get this in the Serial monitor:

My code:
/*
  Web client

 This sketch connects to a website (http://www.google.com)
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe, based on work by Adrian McEwen

 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x98, 0x4f, 0xee, 0x01, 0x8d, 0xdf };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(216, 58, 217, 206); // numeric IP for Google (no DNS)
//char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress dns(192, 168, 1, 122);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    // wait for serial port to connect. Needed for Leonardo only
  }
  delay(5000);
  // start the Ethernet connection:

  Ethernet.begin(mac, ip, dns, gateway, subnet);
  Serial.println("connected to ethernet");
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  int ch = client.connect(server, 80);
  if (ch) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.print("connection failed, error code ");
    Serial.println(ch);
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

Any help is greatly appreciated.

6 months after figuring out the answer, I found this question again. I solved this question by adding system("ifup eth0") which completely solved the problem.


text:
Library to correct time for DST
I am using a Uno as a data logger with a DS1307 RTC and the following libraries Time.h DS1307RTC.h
The DS1307 does not have any support for DST and neither library includes Time Zone.
Are there any libraries which adjust for DST?

I used the Timezone module to correct my times for DST.
It took a little time to sort it out, so I though I would post the steps I followed.
Customise WriteRules for my Timezone.
I copied rule from WorldClock.
NOTE also need to modify Timezone in setup(void)
Run WriteRules.pde to write rules to EEPROM address 100
Run TimeRTCSet.pde to set RTC time to UTC.
Start Serial Monitor.
In Terminal send time to Arduino
date -u +T%s > /dev/tty.usbmodemFA131

Run HardwareRTC.pde to demonstrate time display in UTC & local
I modified my sketch by including the following code:-
#include <Timezone.h>    //https://github.com/JChristensen/Timezone
⋯
Timezone myTZ(100);       //assumes rules stored at EEPROM address 100
TimeChangeRule *tcr;        //pointer to the time change rule, use to get TZ abbrev
time_t utc, local;
⋯
utc = now();
local = myTZ.toLocal(utc, &tcr);

Do you have any idea how huge the DST database is? Work in UTC, and perform the conversion on a bigger machine.

@IgnacioVazquez-Abrams I am logging to FAT, and want to store file times in the usual format.

You could use the Timezone library.

The HardwareRTC appears to be what I am looking for. I will use WriteRules to store my time zone in EEPROM.


text:
Arduino Nano PWM frequency
I have been using an Arduino Nano as a PWM controller for a heating element.
I am currently using D11 (PB3). I could change, although all pins with PWM are in use, and would require a re-write and re-wire.
This produces a signal at ~490Hz, but I would like to experiment with changing this to a higher frequesncy.
I gather it its possible to vary the frequency by changing the divisor from its default 64.
My sketch uses Uses http://playground.arduino.cc/Main/SevenSegmentLibrary and calls millis() - will changing PWM divisor impact on either of these?
NOTE I have read the setPwmFrequency documentation, but find "disrupts the normal operation" unhelpful - I am actually after some explanation of the concrete effect. I only use millis() to time button presses and flash a LED, which are not time critical
Please keep in mind that changing the PWM frequency changes the Atmega's timers and disrupts the normal operation of many functions that rely on time (delay(), millis(), Servo library).
I have been doing some further study. http://playground.arduino.cc/Code/PwmFrequency states  Changes on pins 3, 5, 6, or 11 may cause the delay() and millis() functions to stop working.
Other references say 3, 11 use timer 2 so do they affect millis() or not as other references claim timer 0 is used for these.

Yes and no, depending on the pwm timer used.

I don't know where this misinformation comes from... The answer is
no, reconfiguring Timer 2 does not affect millis() nor
delay(), as these functions rely on Timer 0. AFAIK the Arduino core
does not use Timer 2 at all. But note that there may be other Arduino or
third party libraries that rely on Timer 2.
You can see here the source code of millis() and
delay().
As MITU RAJ correctly states in his answer, the PWM signal on pin 11 is
provided by Timer 2, so you can use it safely.

The misinformation comes from http://playground.arduino.cc/Code/PwmFrequency. I am sure I am not the only user to have been mislead. The other answer just published an extract of the misleading documentation.

Depends on the pin you used for the PWM.
Arduino UNO/NANO specs say following things:
The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
The base frequency for pins 5 and 6 is 62500 Hz.
The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64, 256, and 1024.
The divisors available on pins 3 and 11 are: 1, 8, 32, 64, 128, 256, and 1024.
PWM frequencies are tied together in pairs of pins. If one in a pair is changed, the other is also changed to match.
Pins 5 and 6 are paired on timer0.
Pins 9 and 10 are paired on timer1.
Pins 3 and 11 are paired on timer2.
Changes on pins 3, 5, 6, or 11 may cause the delay() and millis() functions to stop working. Other timing-related  functions may also be affected.

Since you're quoting the specs, it'd be nice if you could also link to them? :)

The answer is NO, changing the PWM divider for pin 11 will not affect the millis() function (nor delay()).

Explanation:
The Arduino Nano uses the ATMega328P microcontroller, same as the Arduino Uno.
Pin 11's PWM is controlled by Timer 2. By default Timer 2 has a prescale of 64 (ie. setting 0x04). The base frequency of Timer 2 is 31372.55 Hz resulting in a frequency of 490.2 Hz (ie. 31372.55/64 = 490.1961).
On the other hand, the microsecond timer (ie. the one used by millis(), micros(), delay() and delayMicroseconds()) is controlled by Timer 0.
So changing the prescaler of Timer 2 will not affect millis().
It will however change the PWM frequency of Pin 3.

Back to your question:
The possible PWM frequencies of Pin 11 (higher than 488 Hz) are:
31373 / 32 = 980.4 Hz
31373 / 8 = 3921.6 Hz
31373 / 1 = 31373 Hz
Where 32, 8, 1 are the prescaler.
Which equates to a setting value of 0x03, 0x02 & 0x01 respectively.
Add this line of code:
TCCR2B = TCCR2B & 0b11111000 | setting;

Where setting is the value of the setting for the respective prescaler.
============================================
|| Frequency [Hz] || Prescaler || Setting ||
============================================
|| 31373.55       || 1         || 0x01    ||
|| 3921.57        || 8         || 0x02    ||
|| 980.39         || 32        || 0x03    ||
|| 490.20         || 64        || 0x04    ||
|| 245.10         || 128       || 0x05    ||
|| 122.55         || 256       || 0x06    ||
|| 30.64          || 1024      || 0x07    ||
============================================

Source code: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c

Just nitpicking but... the timer's base frequency in phase correct PWM mode is F_CPU/510 (31373 Hz), not F_CPU/512: it takes 255 cycles to count from 0 to 255, then 255 more to count back to zero. C.f. the equation for the PWM frequency in the datasheet.

@EdgarBonet Good point. The answer has now been corrected.

would it be possible to go down a step slower to 15.31 HZ?

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


text:
Problem receiving CAN messages using arduino, MCP2515 CAN module and multiprotocol radio shield
I am using an arduino UNO and a Cooking Hacks CAN BUS module through a Cooking Hacks Multiprotocol radio shield. I plan to read the CAN messages through the car's OBD-II port. I have connected the components according to the tutorial and though there is no LED to indicate that the shield and CAN bus module are ON, I verified that they are indeed ON by using a multimeter. Also, when the reset button is pressed on either the shield or the CAN module, the arduino resets so I guess they are powered up. Coming to my problem, I uploaded the code and connected the setup to the OBD-II port and turned the ignition ON. I expected to see the CAN messages on the arduino serial monitor but I didn't see anything. I also took up this issue with the cooking hacks support team who told me that the libraries were updated and that I should use the updated ones. So I downloaded the revised libraries to use with my code but I am unable to upload the code itself to the arduino because of an error during compilation.
C:\Users\user\Documents\Arduino\libraries\arduinoCANBUS\arduinoCAN.cpp:26:49: fatal error: ../arduino-api/arduinoMultiprotocol.h: No such file or directory
The major difference as far as I can tell between the old and the new libraries is the addition of two lines in the arduinocan.cpp file :
include "../arduino-api/arduinoMultiprotocol.h"
include "../arduino-api/arduinoUtils.h"
Both of these are header files in another library that was included as part of the whole library that you can download from their website.
I realise I might have confused whoever's reading but please have a look at the arduino code. Hopefully, that should clear things up. Any help would be highly appreciated. Thanks.
Code:
    #include <arduinoCAN.h>
    #include <arduinoClasses.h>
    #include <arduinoMultiprotocol.h>
    #include <arduinoUART.h>
    #include <arduinoUtils.h>
    #include <Wire.h>
    #include <SPI.h>

    // Create an instance of the object
    CAN myCAN = CAN();

    // Setting up our devices and I/Os
    void setup() {
    // Using the Socket 0 onto which Can bus module is plugged in
    Utils.setONSocket0();
    Utils.setMUXSocket0();
    // Initializes the UART
    Serial.begin(115200);
    delay(100);

    myCAN.begin(500); // Start talking to the BUS. Speed= 500 Kbps
    }

    void loop() {
    // 1. Receive data

    if (myCAN.messageAvailable()) {
    // Read the last message received.
    myCAN.getMessage(&myCAN.messageRx);
    // Print in the serial monitor the received message
    myCAN.printMessage(&myCAN.messageRx);
     }
    }

EDIT: PROBLEM SOLVED!
Putting the header file's full path in the sketch did not solve it. The compiler still displayed the same error. I then made a backup copy of all the files containing the #include "arduinoMultiprotocol.h" statement and edited them to contain the full path. Initially, the error didn't change and I moved onto the next suggestions, all of which did not change the error. However, I went back to the edited files and replaced the backslash() with the slash(/). This time, the compiler did not throw the same error, instead saying it cannot find arduinoUtils.h.
So I proceeded to do the same thing with arduinoUtils.h, editing all the files containing it to mention the full path. And this time it worked and the sketch works as well. Thanks for your help!

We have a SE site specifically devoted to Arduino-specific issues. Migrating.

The compiler is saying it can't find the header files. The part of the path ../arduino-api/ is suspicious.
It may be because the header files are expected to be somewhere else, or their is a small error which has had a knock on effect.
1 - Find arduinoMultiprotocol.h
Put its full path into the include statement, e.g.
    #include "C:\Users\user\Documents\Arduino\libraries\arduinoCANBUS\wibble\arduinoMultiprotocol.h"

If that is still broken, but a new error is printed, copy the error. If the error doesn't change, then make a backup copy of every file you can find containing #include <arduinoMultiprotocol.h> and edit it to contain the full path. It looks like starting with arduinocan.cpp is a good place to start.
2 - If that doesn't fix the error, create an empty sketch, including all those headers, e.g.
    #include <arduinoCAN.h>
    #include <arduinoClasses.h>
    #include <arduinoMultiprotocol.h>
    #include <arduinoUART.h>
    #include <arduinoUtils.h>
    #include <Wire.h>
    #include <SPI.h>

    void setup() { }

    void loop() { }

Compile and copy the error message.
Move the #include <arduinoMultiprotocol.h> a bit later in the sequence of #includes. If the error changes copy that for later, and record which sequence changed it.
3 - Change #include <arduinoMultiprotocol.h> in that empty sketch
to the full path (as in step 1). If that doesn't fix it, copy that error message.
If you still need help, please update your question with the results of those tests.


text:
Casting a struct member between uint8_t and char, with regard to serial transfer
Im simply trying to pass my payload to another device that has the same architecture and struct. I'm using UART to transfer, and modeling the protocol from EasyTransfer.
When I call Serial.print((char*)mydata.data); in Transfer it prints Hello World as expected.
Calling that same line in Receive prints a '?' to console. This may be some background behavior with Arduino, or I'm just not casting/handling the pointers correctly. How can I get this print out to function properly?
Transfer Sketch
#include <EasyTransfer.h>

//create object
EasyTransfer TransferObject;

//Struct contents must be idential to struct from other board
#define PAYLOAD_SIZE 255
struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[PAYLOAD_SIZE];
};

//give a name to the group of data
SEND_DATA_STRUCTURE mydata;

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

  //#define details(name) (byte*)&name,sizeof(name)
  TransferObject.begin(details(mydata), &Serial);

  pinMode(13, OUTPUT);

  //initalize not so random number generator
  randomSeed(analogRead(0));

}

void loop()
{
  //mydata.blinks = random(5);
  //mydata.pause = random(5);

  //Create payload to transfer
  char* payload = "Hello World!";

  //Fill array with data
  strncpy((char *)mydata.data, payload, PAYLOAD_SIZE);

  //Print sample
  Serial.print((char*)mydata.data);

  //send the entire struct
  TransferObject.sendData();

  delay(5000);
}

Receive Sketch
    #include <EasyTransfer.h>

//create object
EasyTransfer TransferObject;

//Struct contents must be idential to struct from other board
#define PAYLOAD_SIZE 255
struct RECEIVE_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[PAYLOAD_SIZE];
};

//give a name to the group of data
RECEIVE_DATA_STRUCTURE mydata;

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

  //#define details(name) (byte*)&name,sizeof(name)
  TransferObject.begin(details(mydata), &Serial);

  pinMode(13, OUTPUT);

}

void loop()
{
  //check and see if a data packet has come in.
  if(TransferObject.receiveData())
  {
    Serial.print("active");
    //print data payload
    Serial.print((char*)mydata.data);
    }

  //you should make this delay shorter then your transmit delay or else messages could be lost
  delay(250);

This is an exerpt and variant from this library

You're actually falling into a common problem with pointers in structs.
This structure:
struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t *data;
};

contains three values: blinks, pause and a pointer to the data.
uint8_t *data;

That doesn't contain the data. That only contains the address that the data is stored at in memory.  When you transfer the struct it's that address that you are sending - then when the other end tries to print it all it can do is look at the address it's been told about and try and print whatever is in there - and that is complete garbage.
Instead of storing a pointer to the data you need to store the actual data itself. That means that you need to decide upon a maximum size for that data and pre-allocate the memory within the struct:
#define DATA_SIZE 40

struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[DATA_SIZE];
};

Now in order to get the data into that struct you need to fill that array with your payload. For strings the simplest way is:
strncpy((char *)mydata.data, payload, DATA_SIZE);

That will copy up to DATA_SIZE characters from payload into mydata.data.
Note that if payload contains more than DATA_SIZE-1 characters the data in mydata.data will not be NULL terminated. You can get round that by forcing NULL termination:
mydata.data[DATA_SIZE-1] = 0;

In your revised code your payload size is too big. The way the EasyTransfer library works is it has a single byte for the size of the payload. Your total payload size is PAYLOAD_SIZE + 2 ints - that is 255 + 2 + 2 = 259 bytes.  Placed into a single byte that gets truncated to 3. That means you are actually transferring one and a half integers and nothing else.
You need to ensure that your entire struct never exceeds 255 bytes. So you can have a maximum size of data, once you have taken your two integers into account (assuming 16-bit integers on an 8-bit Arduino), of 251 bytes.

Thanks Majenko! And how might I read the data post transfer? Serial.print((char*)mydata.data); shows no output on the recieving device

Did you replicate the same struct on the receiving end?

They appear to be the same, yeah. I can update that original post with my new code, if that helps.

Yes. Please do.

Okay, done. :-)

See my note at the end of my now modified answer.

I COMPLETELY overlooked that, thank you so much.


text:
Use Wii Remote and Arduino to emulate a keyboard for Windows 10?
Is it possible to use an Arduino to communicate with a Wii Remote, connect the Arduino to a Windows 10 computer, and have the Wii Remote inputs be translated into keyboard keys for Windows 10?
I've used several Wii Remote Windows 10 apps, such as WiiUSoft, but I find such programs very unreliable.
Thanks for any help.

To use a Wii Remote as a simulated keyboard for Windows 10.

Not easily with an Uno. It can be done if you change the USB interface firmware. A Leonardo would be better.

The Arduino Leonardo and Arduino Micro (as well as other third-party boards, such as the Teensy and the chipKIT Lenny) can be directly programmed to emulate a keyboard.  There are examples in the IDE that show how to do this.
It is possible with an Uno, but that requires replacing the firmware on the USB interface's ATMega32U4 chip with special HID firmware. This is a non-standard setup, though, and may make programming of the Arduino through the USB port impossible.  So I wouldn't recommend doing that, and would instead go for a board that can directly emulate a keyboard.
There are plenty of tutorials on the web for connecting a Wii Remote with an Arduino, (including a library), so couple that with the examples in the IDE and a suitable board and you are good to go.  From then on it's just a Simple Matter of Programming...


text:
Measure Vcc using 1.1V bandgap
For an battery driven application I want to measure the Vcc (using an Atmega 32u4). That is my code:
int readBandGap() {
  ADMUX = (B01 << REFS0)    // VCC
        | (0 << ADLAR)      // right-adjusted result
        | (B011110 << MUX0) // 1.1V
        ;
  // switch off any ADC conversion
  ADCSRA &= ~(1 << ADEN);
  // enable ADC
  ADCSRA |= 1 << ADEN;
  // start ADC
  ADCSRA |= 1 << ADSC;
  // wait until finished
  while (bit_is_set(ADCSRA, ADSC));
  // first read low, then high!
  uint8_t low = ADCL;
  uint8_t high = ADCH;
  // switch off any ADC conversion
  ADCSRA &= ~(1 << ADEN);
  return (high << 8) | low;
}

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

void loop() {
  int value = readBandGap();
  float vcc = 1.1 * 1023 / value;
  Serial.print(value);
  Serial.print("  ");
  Serial.println(vcc);

  delay(1000);
}

My Olimexino 32u4 board has the ability to switch the voltage between 5V and 3.3V. There are two strange things:

the first measurement is always significantly different than the later measurements
with 5V I'm getting 450, followed by ~367; with 3.3V I'm getting 422, followed by ~395. I would have expected a higher Vcc resulting in a lower measured value (bandgap should be measured compared to Vcc).

Any ideas what is wrong with my approach?

I have known good Vcc measuring code here: http://hacking.majenko.co.uk/making-accurate-adc-readings-on-arduino - You might like to compare it with your code - especially the bit that delays to allow Vref to settle.

I've tried that code now and readVcc always reports ~1100, no matter whether I'm using 3.3 or 5V. Maybe for the 32u4 some different flags have to be used.

Given that code was written for the 328P with fewer ADC inputs, yes, you probably need to adjust the MUX settings to get the right channel.

After tweaking a lot, I've now have found following code to work quite good.
float readVcc() {
  ADMUX = (B01 << REFS0)    // VCC
        | (0 << ADLAR)      // right-adjusted result
        | (B011110 << MUX0) // 1.1V
        ;
  // enable ADC
  ADCSRA |= (1 << ADEN);
  // seems necessary
  delay(2);
  // start ADC
  ADCSRA |= 1 << ADSC;
  // wait until finished
  while (bit_is_set(ADCSRA, ADSC));
  // first read low, then high!
  long value = ADCL;
  value |= ADCH << 8;
  return 1.1 / value * 1023;
}

The bandgap voltage reference needs some time to stabilize, after you enable it. See http://jeelabs.org/2012/05/12/improved-vcc-measurement/
Doing 3 dummy measurements, gives it enough time to do that.


text:
Arduino Mega read of serial encoder read at 1,024,000 baudrate?

Reading a 1.024m baud rate 77 bit stream from a serial encoder- begin.serial1(1024000); is accepted - but no idea if UART can actually run there.
In the screen grab, channel 7 is a 8 microsecond clock pulse generated by the Arduino, channel 6 is the encoder response - always begins 13 microseconds after rising edge of clock pulse, first part is always 10101101, after that it's pretty random as encoder rotates.
I tried unsuccessfully to read the pins at that speed, no way, then tried reading the repeating data at synchronous microseconds +1 to try reading one bit at a time through sequential 77 bit words while not rotating - but clocking varies in Arduino program by up to 8 microseconds over the 2 millisecond repeating patterns though.
I tried the serial read through serial1 port, getting some data, but random... with no terminator to rely on, wondering if anyone has a suggestion as to how to clear/load serial buffer after a long pause (long being almost two milliseconds) followed by the 10101101 that always starts the next read (but could possibly repeat inside of it).
I'm a newbie to these things, just tinkering around thought decoding a serial encoder would be fun... many many many hours later, have learned a bit about them and more so learned how little I know about them :)

I think the problem is that there is more to serial I/O than just bits coming in. Otherwise, if nothing was sending, you would always read 0 from the serial port. Serial has a start and stop bit, for example. I doubt you could use the hardware serial to read in random bits.
If you are going to do this in software, you will have less than 16 clock cycles per bit - enough time to run about 15 instructions. It is not impossible, but very difficult.
There are two ways to read the data in code.
Option 1: Disable interrupts, and hand-write assembler that takes exactly the right amount of time. If you branch, make sure all branches take the same amount of time. I think all assembler instructions on Atmel take 1 cycle. You will need to pad out your loop to a predictable size. At 1.024mhz, the clock will drift by 2.4%, which means you'll either have to supersample (e.g. take one sample every 12 instructions, then throw away the samples closest to the clock interval) or you'll have to make some loops longer than others. If you store 8 bits per byte (as opposed to having an array of 77 bytes, storing 1 bit in each, which would be quicker), then you might get away with making "move to next byte" a different length.  Try to measure each sample in the MIDDLE of the allowed period, or as close to it as you can. You may have to unroll your loops (i.e. instead of "repeat this 77 times", do "do it, do it again, do it again....).
Or you might be able to write an ISR - Your ISR would have to be very short, basically "write the current time to a pre-defined array". Now you have 15 instructions to get the data out, but padding it OUT isn't so critical. With this method, you will get one datapoint per CHANGE (rising or falling signal). I don't know if micros() would be quick enough. Then, once the read is complete, you can post-process the data at your leisure. The ISR will be called at the start of the clock cycle following the change in signal, so this is likely to be easier.
UPDATE:
Micros only has a resolution of 4 microseconds, so you will have to make your own "clock". The easiest way to do this, is to set a counter with about how long you think it will take (, then hand-code a loop to decrement this, until zero. As far as I can make out, the decrement loop should take 2 cycle (decrement the counter, if-not-zero jump back to decrement). So if you start it at 800, it should take 100ms to reach zero. Remember that the ISR will stop the counter for the duration, you will need to compensate. Make sure that this loop isn't optimized out! Your ISR will be: copy the (above) counter into an array, increment your array pointer by 1 (so next time you put it in a different slot in your array). After the counter reaches zero, disable your ISR, and find the difference between each number and the next; add a constant (worked out by trial and error), round to the nearest 8 (which should be pretty close). Divide by 8. The first result should be the delay to the start of the data (first 1); the second will be the number of consecutive 1's, then the number of consecutive 0's, etc.


text:
Getting the average of sound in last minute
I am reading sound input every 60 seconds and I would like to calculate the average of sound during that period using non-blocking code; what should I do to change the way that I calculate it in separated function as I need to do something else with other sensors.
int calculateSoundValue(){
    int average = analogRead(0);
    // loop to calculate the average simple formula sum div nbr of calculated times
    return average;
}

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

}
void loop() {
  // I donùt wanna calculate the average inside a loop but instead inside a function
  int value = calculateSoundValue();
  Serial.println(value);

  delay(600);
}

UPDATE
Is this what you mean ?
unsigned long previousMillis = 0;
const long interval = 6000;
int totalSamples = 0;
int count = 0

    int calculateSoundValue(){
        int sound = analogRead(0);
        totalSamples+= sound;
        count += 1;
        return totalSamples/count;
    }

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {

  unsigned long currentMillis = millis();
int totalSamples = 0;
int count = 0
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

  }
      int value = calculateSoundValue();
      Serial.println(value);
}

Do you know how average is calculated?

Do you know what sound is?

sleep(600) doesn't look like a minute, did you mean delay()? To do stuff with other sensors, you would have to have non-blocking code when you do the averaging on the reading.

@RSM Yes! that's the point behind my question; how can I make it non-blocking at the same time, I am doing a delay

@Avamander Harsh Answer!; Any way; in case you are familiar with arduino, you know that I meant how to make calculate the average on non-blocking way.

@user3378649 you didn't make it very clear that you wanted to make use of non-blocking code, so to a point it wasn't harsh, just practical and straight forward.

@user3378649 to make non-blocking code you can use the mill is() function, most suggest a look at the blink without delay example. Delay will block your code, I know timer interrupts still happen when a delay is running, so timer interrupts are what you can look into. Also 60*1000mS = 1 minute.

You don't need fancy software to tell you what the average sound over a minute will be... The answer is zero - or as near as makes no odds.

@RSM Please can you check the UPDATE, I tried to implement what you suggested; double check and enlighten us with your suggestions.

@Majenko I am trying to see whether there was a movement in the last minute or no; by using sound sensor

@RSM Then the average is not what you want - what you want to do is listen continuously and decide from moment to moment if there is sound above your trigger threshold or not and remember that fact - then once a minute look at what you have remembered and act on it.

@Majenko I don't audio stuff, but I agree with you on average being a waste of time, I was only thinking of the implementation methods. The OP might as well use a peak detector.

@RSM That may have been misdirected ;) It was supposed to be directed to the OP...

@Majenko its chilled :), any way it made me think further than the obvious, and the OP will have a pretty busy inbox now :)

@RSM It's the classic X-Y Problem - the OP thinks they know what they want and how to achieve it, but can't work out how to implement that method - however the underlying method, and their basic understanding of it all, is completely wrong, so even if they manage to implement it as they think it should be it still isn't going to work. They're basically asking the wrong question.

@user3378649: Looks like you do not know what sound is... It's not the average of the signal you analogRead(), it's the fluctuations of that signal above and below its average. The closest thing to “average of sound” you can get is the RMS of the AC part of the signal. You can compute that as low_pass(square(high_pass(signal))).

You want to find the average of doing an analogRead over a minute, is that it?
How about this?
unsigned long total;
unsigned int count;

unsigned long whenStarted;

const unsigned long INTERVAL = 60000;  // one minute

void setup ()
{
  Serial.begin (115200);
  Serial.println (F("Starting ..."));
  whenStarted = millis ();
}  // end of setup

void loop ()
{
  // one more sample
  total += analogRead (0);
  count++;

  if (millis () - whenStarted >= INTERVAL) // is a minute up?
    {
    Serial.print (F("Average = "));
    Serial.println (total / count);
    total = 0;
    count = 0;
    whenStarted = millis ();
    }
}  // end of loop

Thanks! can I put  total += analogRead (0); count++; on q function and replace it like I did

...but as already pointed out, averaging the readings won't accomplish anything useful

Thanks! can I put total += analogRead (0); count++; on q function and replace it like I did - I don't know what you mean by that.

I assume what you actually want is to measure sound intensity. This is
significantly more involved than just averaging the samples you read. I
have written a few weeks ago a program that does exactly that: it
measures the sound intensity and sends those measurements through the
serial port. It is a pretty short program (43 lines of code) you may be
able to adapt to your needs, so I am now sharing it as a GitHub gist:
sound-meter.ino.
In order for this not to be a link-only answer, I'll try to explain the
program's inner working, and go through the theory of measuring sound
intensity on an Arduino. But first let me put here a disclaimer: a
“real” sound level meter should have a frequency response that complies
with some standards, and it should be calibrated to absolute levels.
This program only provides uncalibrated readings with whatever frequency
response its analog hardware has.
Signal conditioning
Four measuring sound on an Arduino, you obviously need a microphone,
but you also need some kind of interface circuit between the microphone
and the Arduino. The purpose of the interface is to “condition the
signal”, i.e. to make sure the Arduino gets a voltage in the proper
range for it's analog-to-digital converter (ADC). It's typically an
op-amp based circuit that provides some amplification and also adds a DC
bias to avoid clipping the negative side of each oscillation. Ideally,
the DC bias should be around Vcc/2, i.e. 2.5 V on an Arduino Uno.
See this SparkFun microphone
breakout for an example on how
such a circuit may be built (click on “Schematic”).
ADC sampling
Once you have a properly conditioned analog signal, you have to sample
it fast enough to catch all its spectral content. The Nyquist–Shannon
sampling
theorem
tells us the sampling rate should be at least twice the highest
frequency in the signal. For audio signals, sampling rates of the order
of 8 kS/s (kilosamples per second) are typical of low quality,
telephone-like applications, whereas high quality audio would run at
44.1 to 48 kS/s.
The ADC of the Arduino Uno, in its default configuration, takes
104 µs to convert one sample. If you just call analogRead() in a
tight loop, this gives a sampling rate of about 9.6 kS/s, which is
fine for this kind of application, unless we have to measure noise above
4.8 kHz. The problem with this approach is that analogRead() is a
blocking function. Calling it in a tight loop means the program will
spend most of its time just waiting for the ADC. If you do anything else
in the loop, not only will the sampling rate be lowered, it will also
become unsteady, which is generally not desirable.
In order to avoid blocking the CPU, we have to forgo analogRead(), and
instead get our hands dirty with low-level configuration of the ADC. The
ADC of the Arduino Uno offers a so-called “free running mode”, which is
well suited for this kind of application. In this mode, the ADC starts a
new conversion as soon as the previous one is done, ensuring a very
consistent sampling rate of 9.6 kS/s. It can also trigger an
interrupt after each conversion, in order for the interrupt service
routine to retrieve and process the sample. See the datasheet of the
ATmega328P
for details on configuring the ADC.
Removal of the DC bias
Once we have the digitized samples, the first thing to do is to remove
the DC bias that was added by the interface circuit. If the bias is
stable and known (maybe determined by experiment), this only involves
subtracting a constant. If it is not known, it can be estimated by
running the samples through a digital low-pass filter with a cutoff
frequency below the range of interest. Subtracting the output of a
low-pass filter is essentially building a high-pass filter. As an
alternative, a numerical derivative (difference between consecutive
samples) can be used as a crude high-pass filter. This, however, will
bias the sensitivity of the detection towards the high end of the
spectrum. Depending on the noise you want to detect, and on the
background noise, this could be acceptable for your application.
In the program I am sharing, I assume the DC bias is known: it's the
dc_offset constant at the beginning of the program.
Instantaneous intensity
With the DC bias removed, the signal we have is a digital image of the
sound picked by the microphone. It could be tempting to just average it
as is. This, however, would just give zero, as the positive fluctuations
of the signal would cancel the negative ones.
The are several options to solve this problem. We could do a peak
detection instead of an average, or we could take the absolute value
before averaging. The most popular option is probably to compute the
squares of the samples. Since the square of a real number is always
positive, this avoids the averaging-out problem. But the square has also
a deeper physical meaning: it is proportional to the sound
intensity, i.e. the
energy carried by the sound wave.
Low-pass filter
The intensity computed above is a very fast varying quantity. If the
signal is a simple tone of constant frequency and volume, the
instantaneous intensity fluctuates between zero and some maximum at
twice the tone frequency. In order to recover the “constant volume”
property of the sound, we need to perform some sort of averaging or, in
other words, we need a low-pass filter.
There are many ways to implement a digital low-pass filter. The most
intuitive may be to group the samples into batches, and then compute the
average of each batch. However, this is neither the best nor the most
efficient to implement. When I need a quick and simple low pass filter,
I generally use an exponential moving
average.
This is the discrete-time equivalent of an analog RC filter, and it can
be implemented very efficiently by remembering the previous output and
updating it as
output += input - output / N;

where, for efficiency reasons, N should be a power of two. The filter's
time constant is N/fs, where fs is the sampling
frequency. In the program I use N = 256, which makes the
division virtually free. This gives a time constant of 26.6 ms. You
can tune the time constant to your needs simply by changing N, but make
sure it is still a power of two.
Decimation
If you only want to trigger an event when the sound intensity exceeds a
defined level, you may not need this. But if you have other processing
to do with those measurements, it is probably not useful to process more
than one intensity reading per time constant of the previous filter.
That's why the program has a decimation step. This is simply the ISR
periodically signaling the main program that an intensity reading is
available. Notice that, since the sample count is an 8-bit variable, it
automatically counts modulo 256. If you want to increase the decimation
factor, you should make sample_count wider and mask out the bits you
do not need.

The short answer is use millis() to keep track of time. You can also put all the time related stuff inside a class to have a nicely organized code. You can get more info about time management on the Arduino here. https://learn.adafruit.com/multi-tasking-the-arduino-part-1/ditch-the-delay

You probably mean micros(), not millis(): If you want to sample the ADC at rates relevant to audio signals, millis() will not provide fine enough resolution.


text:
Emergency! INO file disappeared on computer. Still on Arduino!
For some reason, my Arduino program has disappeared from my computer, and it was a really long, complex program. It is currently still on my arduino, and I HAVE to get it back. Please, someone help me. Arduino UNO, Macbook Pro.
Edit: Perhaps I wasn't clear. I need the INO file back FROM MY ARDUINO.

Time to fire up your undelete program...

Lesson learned: perform backups...

Your edit changes nothing. The .ino file is not on the Arduino.

To be specific, the .ino/.pde/.cpp/.h source code is not in the Arduino.  But a working binary built from it us, which can normally be copied off and flashed to other devices.  In some cases that might help, but it's a pain to modify or reverse engineer.

Perhaps a trip around Macbook advice on undeleting files would be more fruitful? "Ask Different" maybe? Does foremost work on MacBook?

Don't you have a thing called time machine on a macbook pro?

The .ino file is lost, however, your Arduino IDE uses your %temp% to store immediate data.
Look in %temp%, folders akin to build116193871148509168.tmp contain build files. The original ino is not there, but I remember the cpp files generated by IDE should be there.
Some info about how to find the temp on Mac: https://stackoverflow.com/questions/11607834/where-are-the-hex-files-compiled-by-arduino

I am on mac, so I went to /tmp, but no cpp files were there. Thanks for trying to help, though.

Surprisingly, when i look in my folders, the cpp is not always there. But when i searched for .cpp it found some. Dunno when the postprocessed cpp is stored there.

http://stackoverflow.com/questions/11607834/where-are-the-hex-files-compiled-by-arduino

Your INO file is not (ever) on your Arduino.
When you "upload your sketch" to the Arduino, it is first compiled. Your Arduino cannot interpret a sketch directly, and there are various processes which convert your sketch into machine code. This process is not practically reversible.


text:
Replacing the Voltage regulator of a fried Arduino
I accidentally fried my Arduino. I found this Instructable. The symptoms are the same. The board not powering on connecting USB source and the over current protector was heating up. So I removed the voltage regulator as mentioned in the Instructable. But the problem is the pins 1 and 2 of where the regulator used to be are still shorted out. That is even after removing the regulator, the pins seem to be somehow internally shorted. I tried checking the continuity on another working Arduino and found it to be not shorted. What seems to be the problem?

You should try running it off a separate 5V supply to see if the other parts are damaged as well.

@IgnacioVazquez-Abrams As I understand, the Vout of the regulator (i.e. 5V) pins are shorting, so it is impossible to connect external 5V to such a setup unless the short is resolved.

What board are you using? Mega like in the instructable? Try checking the caps. Are there any visible anomalies? Charred traces e.g.

I checked if the MCU was damaged by installing it on another board and found it to be not damaged - @EugeneSh. I am Using Arduino UNO not Mega. I found no visible damage.

I know it's an old thread, but others are likely to have this problem.  If you check the open source schematics, there are a couple of nearby capacitors that connect pin 1 (GND) to pin 2 (+5V) of the regulator.
I would check C2 and PC2 (top right of the diagram) as well as C1 (top left of schematic diagram), and any other components you can find that bridge the rails between +5V and ground.  Capacitors are more likely to fail shorted than many other components.  You will have to remove at least one pin of each capacitor to test it since you don't know where the short is, or you can simply remove capacitors until the short goes away.


text:
Detaching interrupts
I am using the following code to enable an interrupt for a pin:
*digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));  // enable pin
PCIFR  |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
PCICR  |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the group

But I can't disable it. I am trying with this code:
if (*digitalPinToPCMSK(pin) == 0)
*digitalPinToPCICR(pin) &= ~(1<<digitalPinToPCICRbit(pin));

but it isn't working.

What pin is it? Why not use attachInterrupt and detachInterrupt?

The code is inside a function. attachInterrupt only works for two pins.

Don't you mean:
  PCICR  &= ~bit (digitalPinToPCICRbit(pin));


text:
Not able to upload any code to Arduino Uno
NOTE: Using the Arduino Uno
I am WORKING on a project that I have to submit in a few days. My arduino was all set up and was working fine.
Project:Arduino controls a 9v motor depending on the command given. As the arduino only provides 5v , i added a 9v battery to it through a transistor
I decided to add new code into the arduino but when I tried it failed. I have uploaded code thousands of times before (successfully) all of a sudden the IDE keeps giving the following message

avrdude: ser_open(): can't open device "\.\COM3": Access is denied.

I have looked up for a lot of solutions on this forum and elsewhere. Here are the things I have tried so far:

Changing the COM port
Disabling all the other devices CONNECTED to COM
Tightening the CONNECTIONS
Re installing all the drivers and the IDE
Rebooting the system
Using another laptop to upload code

All the above have given me the same output for some reason. The built in LED light and the power LED switch on when the board is CONNECTED to a power source (my laptop). Could the board have been damaged by any chance ? How can I check if the board is spoilt ? Should I buy a new board ?

Have you tried this on another computer?

@AnnonomusPenguin yes

@AnnonomusPenguin I get the same error

Well, either your board is fried or you keep making the same mistake when installing the drivers on all of the computers. Have you tried reinstalling the Arduino bootloader, also?

According to this solution: http://www.instructables.com/id/How-to-upload-codes-to-Lilypad-Arduino-Without-FTD/ You may use your board instead of Lilypad on the link above, to program your board, you may make a connection the same in URL above. I guess this will solve your problem.

Could you please tell us how you exactly connected the battery to the UNO, a MS paint drawing would be enough.

@Avamander turns out the arduino was fried, got a replacement and it works well

I have a post Have I bricked my Arduino Uno? Problems with uploading to board - that describes various tests you can carry out to isolate where the problem is.

Have you tried changing the Microprocessor in the Arduino Uno?
An AtMega320P is much cheaper than new Arduino, and usually only the microprocessor gets spoilt, rest of the board remains intact.

Could be the OS not allowing the application to access the COM ports, there is a terminal command to give the Arduino IDE access to the specific COM port.

Remove all device connect to uno, and upload code to uno. Because,
your device like motor will confuse uno.
Check you usb to serial device.
Check your uno

All the connections are removed . Still does not work

How do I check if the uno is spoilt

Maybe change a uno? I meet the same stage when I try to connect a motor to micro pro. I fixed that by change a micro pro.

So basically I need to buy a new one?

yeah, I think so.

Check the device that the IDE says you're connected to.
http://forum.arduino.cc/index.php?topic=51489.0


text:
Circuit doesn't work when multimeter/current meter is attached
I'm working on a battery-powered data logger, using a bare Atmega 328. I'm using sleep between sensor readings, via the Narcoleptic library. Everything seems to work fine, until I connect my multimeter to check on the current.
The multimeter uses manual range-setting (i.e., not autoranging). If I set the multimeter to the 0-20 mA range, I can see that my idle current is about 0.250 mA, but the upper value is off-scale. If I try to get a reading on the 0-200 mA range, the circuit misbehaves, never goes into sleep, and doesn't record any data. The current stays constant somewhere around 14-20mA.
Do I need to do something special to accurately measure current in the range of 0.25-40+mA? Or do I need a different kind/quality of multimeter?
My multimeter is a $15 digital unit from Circuit Test, model DMR-1100A.

Multimeters have something called a "burden voltage". See this PDF: uCurrent - A professional precision current ... - EEVblog.
Also see Dave Jones' video: µCurrent
Meters measure current by dropping voltage over an internal resistor, and measuring the drop. By definition therefore, there is a voltage drop, which is the "burden voltage".

the circuit misbehaves, never goes into sleep, and doesn't record any data

If you put a voltmeter on the processor side of the ammeter you will probably find that the voltage going into your processor is somewhat less than you think. That would account for the misbehaving.
One possible approach is to crank up the voltage from your power source, checking the voltmeter to see that it reaches the expected voltage on the processor side of the ammeter, however in a circuit which might turn on and off (ie. sleep) this voltage might jump around (depending on the current) so this should be done with caution (to not exceed the maximum processor voltage).

Or do I need a different kind/quality of multimeter?

A higher quality meter may well help - watch that video and look at the PDF to see what I am talking about. My meters (which cost more than $15) don't have this problem to the same extent.

FWIW, I observe similar issues when trying to measure the current of an Arduino Mini Pro 3.3V using a probably cheap multimeter. When I set the range to 20 mA the display alternates between 0.5 and -0.5 mA depending on whether the device is in POWER-DOWN or in a mixture of IDLE/ACTIVE mode. When I set the range to 2000 µA the device shows very non-deterministic behavior. Apparently in that range, the voltage drop is too high then. I understand the voltage drop part, but I'm a bit surprised about the display alternating between positive/negative values.

If your tester has autorange function, you have to disable it, as it can interfere with normal operations by changing the internal shunt resistor.
Did you configure the meter as current meter, DC, connected in series between the power supply/battery and the rest of the circuit?
The tester might give a poor reading at low current values but it shouldn't interfere(much) with the circuit itself.

Yes, I set it to current meter, either the 0-20 or 0-200 range, it doesn't do autoranging. I insert it between the VCC of my USB/FTDI cable and the power bus of the breadboard. In the low range (0-20) the circuit works, so I'm reasonably confident I'm attaching & using it properly.


text:
Sending MIDI messages using PING ultrasonic sensor
I am working on a project that uses a potentiometer and an ultrasonic sensor to create MIDI signals. This is my first time working with an arduino. I took a class in C++, but am teaching myself some C in order to program the arduino. So far I have been looking at code that has been written, I've been trying to understand it and mess with it so that my arduino works. The first code creates notes, but I have no control over what notes play or when they play. The first code:
#include <SoftwareSerial.h>

int val;
int AnalogValue = 0;
byte note = 0;
SoftwareSerial midiSerial(2, 3);

void setup ()
{

  pinMode(Pingpin, OUTPUT);
  Serial.begin(9600);
  midiSerial.begin(31250);
}

void loop()
{
  val = 0;
  digitalWrite(Pingpin, LOW);
  delayMicroseconds(2);
  digitalWrite(Pingpin, HIGH);
  delayMicroseconds(5);
  digitalWrite(Pingpin, LOW);

  AnalogValue = analogRead(0);
  note = AnalogValue/8;

  pinMode(Pingpin, INPUT);
  val = digitalRead(Pingpin);
  while(val == LOW)
  {
    noteOn(val, note, 0x40);
  }
  while(val == HIGH)
  {
     noteOn(val, note, 0x40);

  }

}
void noteOn(byte cmd, byte data1, byte  data2)
{
    midiSerial.write(cmd);
   midiSerial.write(data1);
   midiSerial.write(data2);
}

The second code makes more sense to me, but I get no notes to play. I am lost, and can't seem to get the second code to work. Second code:
#include <SoftwareSerial.h>

int val;
int timecount;
int AnalogValue;
int ultrasoundValue;
const int Pingpin = 8;

byte note = 0;

SoftwareSerial midiSerial(2, 3);

void setup ()
{

  pinMode(Pingpin, OUTPUT);
  Serial.begin(9600);
  midiSerial.begin(31250);
}
void loop()
{
  AnalogValue = analogRead(0);
  note = AnalogValue/8;
  Serial.print(note,HEX);
  Serial.print("\t");

  timecount = 0;
  val = 0;
  digitalWrite(Pingpin, LOW);
  delayMicroseconds(2);
  digitalWrite(Pingpin, HIGH);
  delayMicroseconds(5);
  digitalWrite(Pingpin, LOW);

  pinMode(Pingpin, INPUT);
  val = digitalRead(Pingpin);
  while(val == LOW)
  {
   val = digitalRead(Pingpin);
  }

  while(val == HIGH)
  {
   val = digitalRead(Pingpin);
   timecount++;
  }

   ultrasoundValue = timecount;
   ultrasoundValue = ultrasoundValue - 14;
   ultrasoundValue = ultrasoundValue / 5;

  Serial.print(ultrasoundValue);

if(ultrasoundValue > 127)
 {

 }

else
  {

   noteOn(ultrasoundValue, note, 0x40);

  }

}
void noteOn(byte cmd, byte data1, byte  data2)
{
   midiSerial.write(cmd);
   midiSerial.write(data1);
   midiSerial.write(data2);
}

There is quite a bit that needs to be addressed for these programs to work, and I don't know too much about midi, but i'll use the arduino midi tutorial for info. http://arduino.cc/en/Tutorial/Midi?from=Tutorial.MIDI
The first code will take one measurement of an analog value, set it to note, make one digital reading of pingPin, set that to val, and then write noteOn() forever afterwards. The second code will continually make analog and Ping readings and then write those to serial if the ping reading is greater than 127.
Infinite loop aside, Your programs don't work largely because they send the sensor data in the wrong ways. The first byte sent to noteOn is a command byte, it should not contain sensor data. the arduino tutorial uses the command 0x90 to control the note being played on channel one. the second byte is the note and the third byte is velocity, which seems to work like volume.
to set the pitch and volume of channel one, you need to repeatedly send
noteOn( 0x90, note, volume);

If you want to play a note based on the analog readings that both of your codes set to "note" only when the ping value is larger than 127, you need something like this
if(ultrasoundValue > 127){
    noteOn(0x90, note, 0x45); //middle volume according to arduino tutorial
} else {
    noteOn(0x90, note, 0x00); //make the note silent by using 0 volume
}

if you instead wanted to control the pitch with the ultrasoundValue, you would need to scale the value to being within 0-255, and then use that as note instead of the analog reading. You can get much more complicated than this, but you will need to find a reference for the MIDI protocol you can use.

Thank you for the info, I was able to read more on MIDI. I have a good grasp on how these messages are composed. I still have not solved the main problem. I have a MIDI cable that flashes when MIDI signals are being sent. When I upload code #1 the light flashes, but when I make any adjustments to the code and upload the a modified version, the light stops blinking. I printed the value of UltrasoundValue and it is around 600, so the ping sensor is working. I don't know why it won't go into the "if" statement.

I recommend you start with the code from the arduino tutorial and then very slowly hack on that until it does what you need. Make changes one at a time so you can isolate which change makes the code stop working.


text:
Using 2 PING Senors at Once
I am trying to get values for two ping sensors, but am not getting any returns, can someone help me edit my code?
Code
void setup()
{
  Serial.begin(9600);
  pingRange(2);
  pingRange(3);
}

void loop(){
}

  long pingRange (int pingPin)

{
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  pinMode(pingPin, INPUT);
  return microsecondsToCentimeters(pulseIn(pingPin, HIGH));
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

There's one part of your code conspicuous by its absence:
pingRange(2);
pingRange(3);

You're calling the functions, but you're not doing anything with the returned value.  I think you meant to print that value to the serial interface...
Serial.println(pingRange(2));
Serial.println(pingRange(3));