Arduino Yun Disk Expander low memory but it looks like my memory is fine I can't quite understand this when I run arduino yun disk expander sketch with a sd card plugged in I get the the following message. You do not have enough flash memory need 1mb. I ssh into my arduino and I get this
Filesystem                Size      Used Available Use% Mounted on
rootfs                    6.9M    632.0K      6.3M   9% /
/dev/root                 7.5M      7.5M         0 100% /rom
tmpfs                     29.8M    148.0K     29.7M   0% /tmp
tmpfs                     512.0K       0    512.0K   0% /dev
/dev/mtdblock3            6.9M    632.0K      6.3M   9% /overlay
overlayfs:/overlay        6.9M    632.0K      6.3M   9% /
/dev/sda1                29.7G      2.4M     29.7G   0% /mnt/sda1

The only thing that is full is the /dev/root but the reading I have done through the posts here and online say that's fine. Why may this be I am quite confused???

I don't have a YUN or a lot of experience with OpenWRT, so I'm not sure I'm going to be of much help but, I'm guessing the error you're seeing is from this line of the sketch.
Excerpting that here:
Process awk;

awk.runShellCommand(F("df / | awk '/overlay/ {print $4}'"));
int output = awk.parseInt();
if (output < 1000) {
  Serial.println(F("\nYou don't have enough disk space to install the utility software. You need to free at least 1MB of Flash memory.\nRetry!"));
  halt();
}

So, it appears they are executing df / | awk '/overlay/ {print $4}' on the YUN.
They're using awk to extract the fourth column ($4) of the line containing overlay (/overlay/), which by the way is awfully hackish.
Given that they expect the result of awk.parseInt() to compare less than 1000 to mean you have less than 1 Mbyte available, it's fairly clear they expected this column to be reported in kilobytes.  And yet in your own df listing
overlayfs:/overlay        6.9M    632.0K      6.3M   9% /

the fourth column is 6.3M and the rest are choosing different units, what is sometimes called "human" output.  So, we know what they care about is the overlay mount point.  And that at the time someone tested this code it either they didn't try an SDCard of any size or the output of df was different back then, which is why parsing something like df isn't a good idea.
And that's about as far as I can take you with any real confidence.  I don't know how overlay is set up on a YUN.
I guess, if you wanted to "fix" the code with a minimal change, it would be to add -k to the df command-line to force kilobyte based output, assuming -k works on whatever df comes with YUN.  If you wanted to go a step further, I suppose you could use -P to get POSIX output from df, again assuming that's supported, and change the expected units in the sketch accordingly.  But if this is just for you, and you know overlay has more than 1 MB free, you could just as easily change the function so it cannot fail:
void haltIfInternalFlashIsFull() {
}

All that said, I wouldn't be surprised if you run into another problem just like this in another part of the sketch.


Is Arduino uno SPI comunication can be also master and slave in the same time? Is Arduino uno SPI comunication can be also master and slave in the same time?

OR master 2 slaves in the same time?

I want to recevice data from a sensor and display on OLED (all data transfer with SPI bus)

Can I master those two device (sensor & OLED) in the same time? (with SS pin to select slave )

OR Can I be both slave(recevices the data from sensor) and master (sent data to OLED) in the same time ?

What should I do ? and How can I do?

(I read the SPI example code on the Official website , but I still have no ideal about it)

You can have several devices on an SPI bus. Each must have a chip select. The Arduino SS pin (Uno pin 10) is often used for chip select. Chip select pins should then be in output mode.

Connect the sensor and display to the SPI bus (MOSI, MISO, SCK) and use a chip select pin for each.

A driver (library) for a device connect to the SPI bus will typically assert the chip select pin and transfer commands and data. The SPI transfer is both read and write at the same time.


Sensor/servo shield for Arduino Mega Is there Arduino shields with blocks of 4 pins that you can plug your servos into and use the fourth pin as signal pin to the Arduino Mega board?

Do you mean something like a sensor shield? They have three pins (Vcc, GND, signal), not four (because servos have three pins), but they are designed for connecting a large number of servos

These can be found easily and cheaply all over the internet.


Serial.flush() in arduino I am new to Arduino and I have the following:

int     delaynum;
char    cval[12];

void setup()
{
 Serial.begin(9600);
 Serial.print("Enter Number");
 Serial.flush();

 int i=0;
 while(i<12)
 {
  if(Serial.available()>0)
  {
    char ch=Serial.read();
    if(ch>='0'&&ch<='9')
    {
      cval[i]=ch;
      i++;
    }
    else
    {
      cval[i]=0;
      delaynum=atoi(cval);
      break;
    }
  }
 }
}
void loop()
{
   Serial.println(delaynum);
   exit(0);
}

The code output in virtual bread board:(i Entered 100)

But when i remove Serial.flush() The output like (i Entered 100)

I am Expecting the output:

Enter Number (I want to enter number 100 after the output)

100

Why the code not working ?

I am using Arduino IDE with virtual bread board(ATMega328p)

Not knowing what virtual breadboard does on a normal Arduino it would do the following:
Serial.flush() clears the buffer  and this needs some time normaly you wait minimum for around 100 ms to write/read to that buffer again. As your code runs in setup (so just once) the serial is not available as its still flushing and so your result.
As the name setup says this should only be used to setup HW/SW but not to run routines as you may get all sorts of weird results. If you use "\n" aka newline terminators in your communication you can go for them and flushing would be only necessary if the connection is interrupted and you have to resend data.
EDIT

Waits for the transmission of outgoing serial data to complete.

If you send a character, it is placed in a buffer for transmission. It takes time for each character to be sent because serial is slow. Once it is in the buffer, it will be sent automatically in the background while the program immediately moves on to the next statement. This is done so the program won't waste time waiting for characters to be sent.

flush() is a way to wait for it to be sent, instead of immediately moving on in the user program.

So after calling flush() you can be sure that all data has been sent, and the buffer is empty. So in your case where you placed it it makes no sense.


Always HIGHT line on Oscilloscope when UNO's Fast PWM TOP ICR1 I have been trying to get an answer my question for a 2 days already. It's good for knowledge collecting and playing with different things, but there haven't been a solution so far.
I'm trying to leverage the HXT500 Servo with the Fast PWM with a TOP ICR1
I'm using the DFRobot DFRduino UNO v3.0 (R3) analog of the Arduino UNO. Based on the Atmega 328P-PU
I have an Oscilloscope till 5 MHz as additional tool
Question

Why the Fast PWM, TOP ISC1 always has the HIGHT only on a oscilloscope
Why the Clock Prescaler doesn't work

My investigations & observations
I activated the PWM with TOP ICR1 but on my oscilloscope showed only a 5V straight line, I checked different diapasons (horizontal bases) (1a). Connected to pins 10 or 9. I assumed that my UNO works on 1 MHz (9.2.1 Default Clock Source on Page 37) and calculated ICR1, OCR1A:B for 0 and 180 degree.
     void setup() {
      // all as Ports (for outputs)
        DDRB=0xFF;
        DDRC=0xFF;
        DDRD=0xFF;

      // Table 16-4 on Page 141
      // Fast PWM TOP is ICR1
      TCCR1A|=(0<<WGM10)|(1<<WGM11);
      TCCR1B|=(1<<WGM13)|(1<<WGM12);
      ICR1=2499;

      // Table 16-2 on Page 140
      // Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at BOTTOM (non-inverting mode)
      TCCR1A|=(1<<COM1A1)|(1<<COM1B1);

      // Table 16-5 on Page 143
      // clkI/O/8
      TCCR1B|=(0<<CS12)|(1<<CS11)|(0<<CS10); // (2a)
    }

    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);
        // 90 degree
        OCR1A=299;
        OCR1B=299;
      delay(1000);
      digitalWrite(LED_BUILTIN, LOW);
        // 0 degree
        OCR1A=49;
        OCR1B=49;
      delay(1000);
    }

There I noticed the following issues:

I tried different Prescales - there weren't any differences (2a)
I tried 1 MHz, 8 MHz, 16 MHz - straight HIGHT line

What I have tried next:

To use an Example for Servo leveraging from Arduino IDE. It worked but as I understood it worked via Interrupts, not a Hardware solution
To use Fast PWM, 9 & 10-bit. (2a) Prescales didn't work - I had movement
To use Fast PWM, 8-bit (with code adjustment and wrong angles). (2a) Prescalers didn't work - I had movement

You might want to set the TCCR1A and TCCR1B registers to 0 before your code as the Arduino library sets the WGM10 bit. Or change the first |= to a =. By leaving the WGM10 bit set, you get fast PWM mode, with TOP set to OCR1A. Combined with your other code, this would result in both pins having a 100% duty cycle.
So use
TCCR1A=(0<<WGM10)|(1<<WGM11);
TCCR1B=(1<<WGM13)|(1<<WGM12);

or
TCCR1A=0;
TCCR1B=0;
TCCR1A|=(0<<WGM10)|(1<<WGM11);
TCCR1B|=(1<<WGM13)|(1<<WGM12);

Other than that, you code looks fine, and should give you a 800Hz signal.
PS "I assumed that my UNO works on 1 MHz"; no, the UNO runs at 16Mhz.


compare uint8_t to char array I am not actually using ad arduino but an atmel chip. but my question is c microprocessor related

I am reading an uart which returns data in the form uint8_t [100]
I can print the  return just fine, the return is "OK"

but when I try to use strcmp(read, "OK")
I do not get the expected value, I get a mismatch ( strcmp returns 13, not 0)

uint8_t  sigfox_rd_buf[100] = {0};
uint8_t sig_rd = 0;

io_sigfox->read(io_sigfox,&sig_rd, 1);
while(sig_rd != 10) // read until end char
 {
     sigfox_rd_buf[i] = sig_rd;
     i++;
     io_sigfox->read(io_sigfox,&sig_rd, 1);
 }
 if(strcmp((char *)sigfox_rd_buf,"OK") == 0 )
 {
  do_something()
 }
 else
{
complain();
}

and I always end up in complain for some reason.. please help!! :)

When using strcmp(), strings should be terminated with a NULL character.  Which, by the way, is a zero. Your code should work as is if you replace the Line Feed character (10 or 0x0a) with a NULL (0 or 0x00). That is assuming the string you are getting back is 0x4f, 0x4b & 0x0a.  Or you could play it safe and replace strcmp with strncmp.  Then explicitly state the number of characters to compare:

if(strncmp((char *)sigfox_rd_buf,"OK",2) == 0 )


How to retrieve the data type of a variable? I am using Arduino and I would like to know if there is a function that returns the data type of a variable. That is, I would like to run something as like the following:

// Note: 'typeof' is a sample function that should return the data type.
Serial.println(typeof(myVar));

In a typical C++ program, you would use the typeid operator, like this:

std::cout << typeid(myVar).name();

However, that requires a compiler feature called Runtime Type Information (RTTI). It's disabled in the Arduino IDE, presumably because it tends to increase the runtime memory requirements of the program.

You can get more information about the resource cost here: https://stackoverflow.com/questions/579887/how-expensive-is-rtti

Any fully-featured C++ compiler will definitely support RTTI though. If you want to try using a 3rd party IDE (such as Eclipse with the Arduino plugin) then you could easily enable it. It's probably not worth the hassle just for that though.

Alternative
A higher-performing (but less flexible) solution would be to use a traits class approach. This involves some funky template meta-programming:

// Generic catch-all implementation.
template <typename T_ty> struct TypeInfo { static const char * name; };
template <typename T_ty> const char * TypeInfo<T_ty>::name = "unknown";

// Handy macro to make querying stuff easier.
#define TYPE_NAME(var) TypeInfo< typeof(var) >::name

// Handy macro to make defining stuff easier.
#define MAKE_TYPE_INFO(type)  template <> const char * TypeInfo<type>::name = #type;

// Type-specific implementations.
MAKE_TYPE_INFO( int )
MAKE_TYPE_INFO( float )
MAKE_TYPE_INFO( short )

You can add MAKE_TYPE_INFO(..) lines for any type you want, including the names of custom classes. You could then use it like this:

int myVar = 17;
Serial.println( TYPE_NAME(myVar) );

Anything you don't define using MAKE_TYPE_INFO(..) will show up as "unknown".

That's some fairly advanced stuff in there, so I won't try to explain how it all works here. There are various tutorials on the web though about C++ template programming if you're interested.

EDIT: It's worth noting that the typeof operator isn't standard C++, but is supported by a few compilers, such as GCC. It's basically an older equivalent of decltype, which appears in the C++11 standard.


Can not print an element in an specific position in an arduino list I have been tying to print an element of a list with the same position as the number that it matches, but it does not seem to work and I can not figure out if I made some mistake, could someone please check it? Would really appreciate it

Here are the list declarations:

int names[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
char *users[10] = {"Josh", "John", "Frederic", "Mikael", "Anthony", "Charles", "Tom", "Chris", "Steve", "Mike" };

And this is what I am using to print the name I need:

if (attempt != FINGERPRINT_OK) return -1;
Serial.println ("Belongs to: ");
if(data.fingerID == names[n]) {
    Serial.print(users[n]);
}

Complete Code:

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3);
pinMode (12, OUTPUT);
pinMode (13, OUTPUT);

Adafruit_Fingerprint data = Adafruit_Fingerprint(&mySerial);

int names[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
char *users[10] = {"Josh", "John", "Frederic", "Mikael", "Anthony",
"Charles", "Tom", "Chris", "Steve", "Mike" };

void setup() {
  Serial.begin(9600);
  while (!Serial);
  data.begin(57600);
  if (data.verifyPassword()) {
    Serial.println("Verified connection");
}

  else {
    Serial.println("Unnable to verify connection, try again");
 while (1) { delay(2500); }
}

data.getTemplateCount();
Serial.print("Waiting for one of the:"); Serial.print(data.templateCount);
Serial.println("valid fingerprint");

int getFingerprintIDez();
uint8_t getFingerprintID();

void loop() {
for ( int i = 0; i <= 10; i++) {
 uint8_t attempt = data.getImage();
  switch (attempt) {
   case FINGERPRINT_OK:
   break;
 delay (2500);
}

attempt = data.image2Tz();
  switch (attempt) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
    break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
    return attempt;
  }

 attempt = data.fingerFastSearch();
   if (attempt == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
    digitalWrite (13, HIGH);
    delay(1250 );
    digitalWrite (13, LOW);
  }
   else if (attempt == FINGERPRINT_NOTFOUND) {
   Serial.println("Did not find a match");
   digitalWrite (12, HIGH);
   delay(1250 );
   digitalWrite (12, LOW);
   return attempt;
  }
Serial.print("Found ID #"); Serial.print(data.fingerID);
Serial.print(" with confidence of "); Serial.println(data.confidence);
return data.fingerID;

uint8_t attempt2 = data.getImage();
if (attempt2 != FINGERPRINT_OK) return -1;
 attempt2 = data.image2Tz();
if (attempt2 != FINGERPRINT_OK) return -1;
 attempt2 = data.fingerFastSearch();
if (attempt2 != FINGERPRINT_OK) return -1;
 Serial.println ("Presents: ");
if(data.fingerID == names[n]) {
    Serial.print(users[n]);
}
}
}

I am attempting that when a fingerprint is verified, the position that matches it out of all the stored fingerprints gets stored as n so I can later print the name asigned to that same position. Thanks

How about you completely delete

int names[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

and instead do:

if (attempt != FINGERPRINT_OK)
    return -1;

Serial.println ("Belongs to: ");
Serial.print(users[data.fingerID - 1]);


Accidentally shorted 5V to GND on Arduino Nano, can I reuse the ATmega328p? I've shorted 5V to GND and the Arduino Nano (CH340 clone) stopped working (power LED light is dimming). The board had a burning smell, and I also checked if other Arduini on the same USB port worked and they did, so I'm quite sure the Arduino is dead.

After the incident, I de-soldered the TQFP Atmega328p (plus the crystal) to reuse. I'm thinking that if it's only the external circuitry that's damaged, then the chip should be OK. Can I reuse the chip if I solder onto a new board? What components could have been damaged?

On a Arduino Nano, there is a diode that prevents an external 5V source from back feeding into the USB source. If your clone equivalent has that as well, I suspect that is the part that got fried.


Communication between Arduino and raspberry Pi So I am working on a ground surveillance robot using Arduino for coding the Gps, motors and ultrasonic sensors and coding in raspberry Pi for facial recognition but now what I want to do is when my robot has gotten to its final waypoint and has stopped it should excute the python file that does the facial recognition by calling it in the Arduino  sketch but I don't know how to do it would be nice if someone could please help me out I appreciate your help in advance thank you

You can't make the Arduino just run the Python script on the Pi. Instead you will have to run some software (probably of your own devising) on the Pi that listens for instructions from the Arduino.

The simplest way is probably to modify your existing Python script so that it runs all the time but sits idling waiting for instructions through the serial port (using pySerial). When it gets the instruction to perform the task you need it then goes off and runs the main bulk of its code. When that is done it can then return the results back through the serial port to the Arduino (if you need such results returning).

How you arrange those instructions to get it to do things is entirely up to you.


Calculate battery (18650 Li-ion) voltage using ESP8266-12E i am trying to calculate the battery voltage using ESP-12E module. I am using a voltage divider circuit to calculate the same. Here is how my circuit looks like:

And here is how my code looks like:
float volt =0.0;
float temp=0.0;
float r1=320000.0;
float r2=100000.0;

void setup(){
    Serial.begin(115200);
    Serial.println(String(VoltageCalculator()).c_str());
}

float VoltageCalculator(){
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
  Serial.println(analogRead(A0));
  for(int i = 0;i<=10; i++){
    total = total - readings[readIndex];
    // read from the sensor:
    readings[readIndex] = analogRead(A0);
    // add the reading to the total:
    total = total + readings[readIndex];
    // advance to the next position in the array:
    readIndex = readIndex + 1;

    // if we're at the end of the array...
    if (readIndex >= numReadings) {
      // ...wrap around to the beginning:
      readIndex = 0;
    }

    // calculate the average:
    float analogvalue = total / numReadings;

    //  int analogvalue = analogRead(A0);
    temp = (analogvalue * 3.3) / 1024.0;
    volt = temp / (r2/(r1+r2));
  }

  if(DEBUG_ENABLE){
    Serial.println();
    Serial.print("Actual Voltage : ");
    Serial.print(volt);
    Serial.println();
  }

  float volt_percent;

  if(volt == 3.1){
    volt_percent = 0;
  } else{
    float volt_diff = volt - 3.1;
    volt_percent = (volt_diff/1.1)*100;
    if(DEBUG_ENABLE){
      Serial.println();
      Serial.print("Voltage percentage : ");
      Serial.print(volt_percent);
      Serial.println();
    }
  }
  return volt_percent;
}

When i use this circuit with NodeMCU it works very fine, but when it comes to ESP-12E module it do not show the proper voltage. on Serial.println(analogRead(A0)); always shows 1024.
Any suggestions why this is happening and how can i do this to achieve the most accurate value?

Everything was correct and my circuit is also good. The only difference i found is to this below line:
temp = (analogvalue * 3.3) / 1024.0;
Which should be
temp = (analogvalue * 1.0) / 1024.0;
We are multiplying because we are referencing the voltage from voltage divider circuit as 1 volt.
After doing this, i am getting the exact values battery voltage which then i convert to percentage.
Thank you!


Demultiplexing Arduino with C++ code I have been working on a small project recently. I have a circuit like in the image below:

  Hardware Setup Demultiplexer IR Test

As you can see I have 8 IR LEDs, which are driven by an MC14051B Multiplexer/Demultiplexer. My goal is to select each IR led individually and send data over the selected IR LED. None of the other LEDs can send signals. Only one LED at a time can be sending IR codes.

  Hardware Setup Single IR Test

Below is the code I used to send the signal using the IR Library over one LED (no demultiplexer was used in this test).

// New function to send 'items' codes which are held in the array 'data'
void sendMulti (const uint8_t& items, const uint32_t* data) {
  for (int i = 0; i < 2; i++) {
    for (uint8_t itemIndex = 0; itemIndex < items; ++itemIndex) {
      irsend.sendNEC(data[itemIndex], 32);
      delay(1000);
    }
  }
  delay(5000); //5 second delay between each signal burst
}

void loop () {
  static const uint8_t MaxItems = 3;
  uint32_t  data[MaxItems] = {0x1067E21D,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x10676897,0x10676897,0x10676897,0x10676897,0x10676897,0x10676897,0x10678877,0x10676897,0x1067A857,0x1067A857,0x10678877,0x1067A857};
  sendMulti(MaxItems, data);
}

The Single IR Test was a success. However now I want to use the demultiplexer. Any advice or pointers will make me very happy.

The most important document you have to read is called a datasheet. Here you can find the MC14051's.

I assume you already know how a mux/demux work, so... Well, you have eight LEDs, one on X0, another on X1, ... up to X7. The one connected to the pin X, which is your A0 (the pin used on irsend, I assume) is indexed by the three inputs A, B and C.

On page 5 you see the truth table. According to that table, you have to write a 0 on inhibit, and the value on ABC. So, to select led on X0, you have to write 0 on pins 7, 8, 9 and 10. If you want to select led X1, 8 should go high. For led X7, 8, 9 and 10 should be 1, while 7 is low. And this is for all the combinations...


Unable to light up all the LEDS connected to Arduino using processing I have 3 LEDs connected to my arduino which are controlled via laptop key presses with processing.

While the LEDs are able to light up when the respective buttons are pressed, i am unable to light up all 3 LEDs simultaneously when i press all 3 keys at the same time. I am however able to light up 2 LEDs by pressing 2 buttons simultaneously.

All the LEDs light up when their respective buttons are pressed, so i know that it is not a defective LED and/or faulty connections/wiring at play but something else that is causing the issue.

My processing code:

import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(64);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write(1);
      println("red");
    }
    else if(key == 'y' || key == 'Y'){
      myPort.write(2);
      println("yellow");
    }
    else if(key == 'g' || key == 'G'){
      myPort.write(3);
      println("green");
    }
  }

}

void keyReleased(){
 if(key == 'r' || key == 'R'){
      myPort.write(4);
      println("red released");
    }
    else if(key == 'y' || key == 'Y'){
      myPort.write(5);
      println("yellow released");
    }
    else if(key == 'g' || key == 'G'){
      myPort.write(6);
      println("green released");
    }

  println("released");
}

My Arduino code:

int red = 7;
int yellow = 6;
int green = 5;

void setup(){
  Serial.begin(9600);
  pinMode(red,OUTPUT);
   pinMode(yellow,OUTPUT);
    pinMode(green,OUTPUT);
}

void loop(){

}

void serialEvent(){
    int input = Serial.read();
    if(input == 1){
      digitalWrite(red,HIGH);
    }
    else if(input == 2){
      digitalWrite(yellow,HIGH);
    }
    else if(input == 3){
      digitalWrite(green,HIGH);
    }
    else if(input == 4){
      digitalWrite(red,LOW);
    }
    else if(input == 5){
      digitalWrite(yellow,LOW);
    }
    else if(input == 6){
      digitalWrite(green,LOW);
    }
}

Things i've tried.

I've tried increasing the buffer size from 10(initially) to 64(in the code above)
I've tried increasing the baud rate from 9600 to 12000, just in case it was the serial information not being read fast enough.

None of the things i've tried, listed above, was above to solve my problem, and i dont see what could be causing the problem.

Any advice would be much appreciated.

I'm guessing it is a hardware issue as I discussed in the comments above.

I have just set up a breadboard and copied your code verbatim into the Arduino IDE and Processing (I edited the port index to use). It works as desired. Pressing R, G, or Y will turn on the respective LED and releasing it will turn it off.

I can press these three keys in any combination of none on, one only, any two, or all three, and the LED gives the expected result.

Keyboards were not initially designed to have multiple "main" keys pressed down at any one time, the exceptions to these being the modifier keys (Windows/Command, Option/Alt, Control and possibly some others (I'm thinking the older keyboards here that had "other" keys—Scroll Lock, Print Scr, etc—I'm really unsure).

It appears now, that some hardware and software may have overcome this. As I've said, your project works fine for me. Also, you could try three different keys, it could be a result of how the keys are scanned and you may stumble across three that don't interfere with each other.

As I've suggested in the comments to your question, modify the code to utilise the modifier keys instead, or use the keyboard keys as toggles (ie press once for on, press again to turn it off).


Using TIMER0_COMPB_vect I'm trying to understand how to fully use the COMPB vector ISR of Timer0 on the ATMega328 (standard Arduino core). I realize it will make delay() and millis() not work but that's ok by me. I've setup some test code that should output a 244Hz signal on D4 and 488Hz on D5 (note, this is running at 8MHz). But D5 (COMPB) is always what D4 (COMPA) is. Any thoughts? Code below:

#include <avr/interrupt.h>

volatile bool stateA = false;
ISR(TIMER0_COMPA_vect)
{
    if (stateA)
        PORTD |= _BV(PIND4);
    else
        PORTD &= ~(_BV(PIND4));

    stateA = !stateA;
}

volatile bool stateB = false;
ISR(TIMER0_COMPB_vect)
{
    if (stateB)
        PORTD |= _BV(PIND5);
    else
        PORTD &= ~(_BV(PIND5));

    stateB = !stateB;
}

void setup()
{
    DDRD |= _BV(PIND4) | _BV(PIND5);

    //set timer0 interrupt at 2kHz
    TCCR0A = 0;// set entire TCCR2A register to 0
    TCCR0B = 0;// same for TCCR2B
    TCNT0 = 0;//initialize counter value to 0
    // set compare match register for 2khz increments
    OCR0A = 255;//244Hz
    OCR0B = 127;//488Hz
    // turn on CTC mode
    TCCR0A |= (1 << WGM01);
    // Set CS01 and CS00 bits for 64 prescaler
    TCCR0B |= (1 << CS01) | (1 << CS00);
    // enable timer compare interrupt
    TIMSK0 |= (1 << OCIE0B) | (1 << OCIE0A);

    interrupts();

}

Update: After thinking about it, I'm realizing that it's not that I need two separate frequencies (though I just kinda wanted to know how, so this is good stuff) but I just need two separate interrupts, only using Timer0 (1 & 2 are already in use elsewhere). They can be the same frequency, most likely. I probably could put all the functionality I need in the same TIMER0_COMPA_vect, however I was trying to use that in a library I was writing and was trying to keep the functionality separate... this may not be possible.

Your code doesn't do what you think it does. The timer always runs at 244Hz, and OCR0B only matches twice per period, causing it to have the same frequency but a different phase. What you need to do is set OC0B on compare match and clear it in the overflow ISR. OCR0A you can simply set to toggle on match.

TCCR0A = _BV(COM0A0) | _BV(COM0B1) | _BV(COM0B0) | _BV(WGM01);
TIMSK0 |= _BV(OCIE0A);

 ...

ISR(TIMER0_COMPA_vect)
{
  PORTB &= ~_BV(PD5);
}

Also, OC0A is D6, not D4.


How to find if AC Appliance is on or off using ACS712 current Sensor I am trying to get the status of appliance using current sensor. My Circuit looks like below image. I don't want to measure current. I just want to know whether appliance is on or off.

I am getting following readings when power turned on and off, I don't see any difference, I am not able to figure out whether the bulb is on or off.

Please help me to know the status of appliance/bulb.

PS. Please find my code below:

/*
Measuring AC Current Using ACS712
www.circuits4you.com
*/
const int sensorIn = A0;
int mVperAmp = 185; // Use 100 for 20A Module and 66 for 30A Module

double Voltage = 0;
double VRMS = 0;
double AmpsRMS = 0;

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

void loop(){

 Voltage = getVPP();
 VRMS = (Voltage/2.0) *0.707;  //root 2 is 0.707
 AmpsRMS = (VRMS * 1000)/mVperAmp;
 Serial.print(AmpsRMS);
 Serial.println(" Amps RMS");
}

float getVPP()
{
  float result;
  int readValue;             // value read from the sensor
  int maxValue = 0;          // store max value here
  int minValue = 1024;       // store min value here

   uint32_t start_time = millis();
   while((millis()-start_time) < 1000)  // sample for 1 Sec
   {
       readValue = analogRead(sensorIn);
       // see if you have a new maxValue
       if (readValue > maxValue)
       {
            /*record the maximum sensor value*/
           maxValue = readValue;
       }
       if (readValue < minValue)
       {
           /*record the minimum sensor value*/
           minValue = readValue;
       }
   }

   // Subtract min from max
   result = ((maxValue - minValue) * 5.0)/1024.0;

   return result;
 }

The code looks like it would produce rather larger values than you are seeing, if it gets correct inputs from the sensor.  For that reason, you probably should carefully check your wiring.  Also, with a DVM, measure the sensor output voltage with the light on and with it off, to verify sensor operation.  If you measure ok sensor voltages but don't get good readings, your analog input pin may have a problem; you could try other analog input pins.

Note, when debugging an issue like this, it does not make sense to run a few numbers through five levels of processing before printing anything out.  You should at least add serial prints in getVPP(), and just before returning the result, print out result, maxValue, and minValue.

Note, fix the erroneous comment “//root 2 is 0.707”; the square root of 2 is about 1.414213562, while 1/√2 = (√2)/2 is about 0.707106781.


Fast PWM: Resolution in hertz I am trying to get a nice sounding varying PWM to DAC, and intend to use a Sallen Key as part of an active low pass filter.
I set the Fast PWM at a max of 255 (WGM1[0-3] = 5) and set/clear OC1A upon comparing with OCR1A (1<< COM1A1)
I also update the value of OCR1A in 64 distinct steps, changing those steps around 15'000 times a second to create a specific sinusoidal shape.
As the chip works at 16 Mega Hertz, does this mean that one cycle of PWM is 16'000'000/256= 62.5 Kilo Hertz? If not, what is its resolution
Thank you!

With the help of the comments, I decided to use variable PWM max values to match absolutely with the frequency. This resulted in a crispier sound that actually doesn't need the Sallen Key anymore.
For example, a low C natural, or 261.6Hz, updated 32 times for 8 full cycles of PWM give us, for a 16MHz chip, an period and amplitude of 238.
This means that having a prescaler of 8 (CS01), a period (OCR0A) AND a max potential duty cycle (ICR1) of 238, and going through 32 iterations of the sound sought for, I got the sound that I wanted and none of the wave groove that comes with a pulse duty cycle cut short.
Sure, it means less granularity when it comes to a Bb with a max duty cycle of 133, however it worked for me.


Is PulseIn fast enough for Quadcopter? I've been trying to use interrupts to control a quadrotor with a tx/rx to no success. I'm using an arduino mega as my control board. I have successfully read a singe channel using attach interrupt and PulseIn. I have also successfully read multiple channels with pulse but failed to do so with attach interrupt and pinchange int. Should I just go ahead and use PulseIn

You should avoid pulseIn for a quadcopter, the main reason being that pulseIn takes too long to execute.

pulseIn waits for a pulse to start, then waits until that pulse finishes, and then returns how long it took to finish. Standard RC signals pulse at 50-60Hz, with the "high" part of the signals being between 1 and 2 milliseconds. 60Hz is one pulse per 16 milliseconds or so.

What that amounts to is pulseIn taking at most 18 milliseconds, but never less that 1 millisecond to execute per channel. lets say you want to measure 4 channels (throttle, pitch, yaw, roll); the average time would be around 40 milliseconds.

In general 40 milliseconds isn't so long, but your quad will need to read the accelerometer and gyroscope and stabilize itself more often then that in the air. A loop that takes 40 ms is running at 25Hz, but the stabilize loop in all the quadcopter implementations I'm familiar with is run at 100Hz or higher (thats areoquad, multiWii, and ardupilot).

You should use interrupts to read the values, because interrupts are non blocking, and give higher quality readings. Some specialized quadcopter boards have other processors read the actual RC signals and send the result back to the main processor to cut down on the number of interrupts they have to use.

FYI, The standard servo output library sends new signals at 50Hz. Those open source quadcopters use their own implementations that run at higher output frequencies, since brushless ESCs support that. There is a pull request with code to add support for different refresh intervals to the arduino servo library here that I have tested; You could try appling it as a patch to your installation if the output rate gives you trouble down the road.


How do I make a atmega 32u4 mp3 player? Is there a way to use the atmega 32u4 breakout board to make a mp3 player without the mp3 shield?

You don't.

A basic ATmega lacks the computational (and perhaps memory also) resources for mp3 decoding.  And even if you do decode to a linear PCM format, you do not have a good way to output it.

You can playback linear PCM data by pulse width modulating a pin, but the limited clock rate will result in limited resolution, and thus poor fidelity.  You will also end up with a low sample rate, making it hard to avoid audible artifacts.

The situation can actually be somewhat better with an ATtiny85 - still no MP3 decoding of course, but you can clock the counter/time block at a higher rate and so playback PWM audio with higher fidelity, provided you are willing to tolerate the inaccuracy of the onboard clock oscillator that may shift your audio frequencies by a small amount.

If you want to do MP3, you will need either a more powerful processor (often no more expensive than the one you have, and typically cheaper as a module than anything "-duino"), or else a dedicated function chip to act as a coprocessor for that purpose.


Concatenation of non constant character array with a string I have an Arduino Duemilanove.

I read this page on string concatenation. Yet, it didn't include my case.

I have a non constant character array, that later gets a value.

char clat[11];
dtostrf(gps.location.lat(), 11, 6, clat);

I want to output this:

Latitude: 20.653425

So basically I want a final string that contains: "Latitude:" + the value of the nonconstant array.

Is it possible?

char clat[10+11+1] = "Latitude: ";
dtostrf(gps.location.lat(), 11, 6, clat+10);

Since you've named the buffer 'clat' I'm assuming it will always be used for latitude, so we've pre-initialized its size and contents, and we know where to begin the latitude value.

By the way, don't forget to size string buffers one more byte than the length of the maximum length string you intend to put in it.

Update 6/23/14:

From your other question and your comment to this answer, I'll revise my suggestion to this. The ..printf() functions are particularly easy to use, saves you (mis)counting buffer positions, and don't add much lot more code than the Serial() object already includes:

char outbuf[40+1];      // wider than nec, easier than counting
char clat[15+1]; clong[15+1]; // workspaces

sprintf(outbuf, "Latitude/Longitude: %s %s",
    dtostrf(gps.location.lat(), 10, 6, temp),
    dtostrf(gps.location.lng(), 10, 6, temp) );

This works because dtostrf() returns the address of the buffer you gave it; sprintf then takes that string (two of them in this case) when building your final output string.

The printf() functions are often deprecated for embedded systems. They're large (but see my comment about that above); and they're non-reentrant, so don't do that! In these low-end systems we don't often multi-thread anyway - just be aware of that if you do. And even if you have to remove them later and go back to printing piece by piece, they can save you a lot of headaches during development.

Here's another way that avoids both printf and the 32 bytes of work buffers:

char outbuf[40+1];

 strcpy(outbuf, "Latitude/Longitude: ");
 dtostrf(gps.location.lat(), 12, 6, outbuf+strlen(outbuf));
 dtostrf(gps.location.lng(), 12, 6, outbuf+strlen(outbuf));

We can't initialize outbuf unless it is 1) static, and 2) not going to be used more than once, since its initial conditions won't be the same the second time around. I've increased the field-widths of dostrf() to be sure the outputs of the won't be run-together for large values.


Arduino 101 I/O voltage levels As per the Arduino 101 schematic.

The Arduino 101 has level shifters (TI make LSF0108) connected to the I/O ports I guess these are to make them Arduino compatible(5V) since the Intel Curie Module is 3.3V rated.

I have 2 doubts regarding this

The level shifters are also connected to the analog pins so I was wondering how do these shifters pass through analog signals?
I have some 3.3V sensors that I want to interface to the Arduino 101 via I2C. My question is can I use 3.3V levels at the I/O ports or am I restricted to 5V?

TIA

An Exploring the I/O Performance of the Arduino 101 webpage by Dan Watson has a number of relevant comments:

  The board uses three Texas Instruments LSF0108 level translators to accommodate all of the I/O lines (including the analog inputs). This is an interesting part. It's not really a level "shifter", and it's not a buffer. The Curie is still sourcing and sinking current to the pins, but the voltage levels are clamped at 3.3V on the Curie's side of the chip. In this regard it's kind of like a fancy analog switch. The on resistance of each signal path is in the neighborhood of 10 ohms.

Somewhat later in the article:

  Analog Input Linearity:  Next I tested the analog inputs. I was curious if the level translators affect the accuracy of the readings. I applied a DC voltage on pin A5, starting at 0V and increasing to 3.3V in 100 mV steps. At each step, I recorded the 10-bit analog-to-digital (ADC) readings reported by the Arduino 101. I then created a graph of the data, which is shown [on the webpage]. As you can see, the results are pretty linear across the entire input range. Spot-checking a few values, I found that there might have been a +20mV bias on the readings at the top end of the scale.

To summarize:  As a consequence of being like an analog switch, the LSF0108 allows the Curie's analog input pins to accept analog inputs, and apparently it works ok.

Regarding the second question, whether 3.3 V levels are ok at the I/O ports, I think they are.  See the article mentioned above for more comments.  Here is one that may be relevant:

  Digital Input Logic Transitions:
  I applied a DC voltage to pin D7 and varied it up and down while the Arduino 101 reported the logic state in the serial monitor. This was done in order to discover the logic transition levels. Going from high to low, it returned a low state after crossing 1.26V. Going from low to high, however, the transition occurred at 1.55V.

Edit 1:  Regarding two questions in a comment...

  What is the function of the level translators.. do they actually map the 0 to 5V levels to 0 to 3.3V on the curie side. ?

See the LSF0108 datasheet.  The LSF0108 has eight A, B pairs: (A1,B1);  (A2,B2); ... (A8,B8).  If you drive Ai low, Bi goes low too; and vice versa, if you drive Bi low, Ai goes low too.  That translates low to low. If neither side is driven low, connected inputs can pull up to an individual-pullup level but not higher than a reference level (VREFA or VREFB).  This translates high to high.

  If I give a 0 to 5V analog voltage at the headers will the 3.3V to 5V level part of the signal be lost, I mean does the board only take care of the 0 to 3.3V part of the signal and the adc will give max counts at 3.3V?

It should be 'lost', because as noted in the Curie datasheet's Table 2-5. ADC - DC I/O specifications, the AIN Full-scale input range is ≤ ADC_3P3_VCC and ≤ AON_IO_VCC.  (The latter voltage is 1.8 or 3.3 V.)  I'm not clear on why the LSF0108 doesn't interfere with ADC measurements.  Maybe the switches operate in a linear mode when pullups are turned off?


Hardware Serial connection for Arduino Mega 2560 NEO GY-GPSMV2 GPS module My project is Vehicle Tracking System, One of my module is GPS module (Neo GY-GPSMV2). I can successfully see the GPS coordinates via Software Serial. But what I want is that my Arduino should not be connected to my laptop. So I should use Hardware Serial (correct me if I'm wrong). But I read some blogs that I should use resistors to avoid damage to m GPS module if I will use Hardware Serial. I searched for the wiring of it then I see this.  (Please remind that I'm using Mega so please just focus on the wiring). So I bought a 10k and 4.7k resistors. My question is how can I appl this on an actual wiring? should I split the wire? or what?

Most importantly, I want to point out that a Mega has 4 HardwareSerial ports: Serial, Serial1, Serial2 and Serial3.  There is no reason to use an inefficient software serial port library.  Software serial libraries use the processor to handle each bit transition, so they use much more CPU time.

SoftwareSerial is particularly inefficient, because it disables interrupts for the entire time that a character is being sent or received, and it can't do both at the same time.  This will interfere with your sketch or other libraries.  This answer lists the various serial port choices.

To answer your question:

  ... how can I apply this on an actual wiring? should I split the wire? or what?

Yes, 3 things get connected together at two places.  Most people use breadboards for prototyping.  Stick two wire ends (a "split" wire) and one end of a resistor into a common row of the breadboard, connecting them electrically.

But for a permanent solution, you should solder two separate wires and one end of the resistor together.  A small piece of perfboard can help secure the wires and discrete components.  It's a little kludgey, but you can strip the insulation from the middle of one piece of wire (don't split the wire) and solder one end of the resistor to it.

BTW, I always recommend real level-shifter modules that use FETs.  They're fast, so you can also use them for SPI interfaces, like an SD card, and they're bi-directional (5V to or from 3.3V).  And they're cheap.  You would just solder individual wires from the Arduino and the GPS device to various through holes in the module PCB.

The picture in your post shows a direct connection between the GPS transmit pin and the Arduino receive pin.  While this will not damage either pin, the GPS transmit voltage is not quite within the range specified for the Arduino receive pin.

Note the use of the word "specified".  If you read the specifications for the two devices, you will see that a logic 1 out of the GPS pin (called VOH) is slightly under the minimum acceptable voltage for the logic 1 input to an Arduino pin (called VIH).

You can also use discrete components to "step-up" the GPS TX voltage up a little.  You can google for many different solutions.  Hackaday has a nice summary.  MicroChip AppNote DS41285A has many suggestions.  Again, I would strongly suggest using a level-shifting module.

Many people report using a direct connection without problems.  It is possible that:

the actual devices have a higher VOH and/or lower VIH, or
the data is received with various amounts of errors, and the GPS parsing library (or sketch) ignores the errors.  Take a look at my NeoGPS library.  It is the fastest, smallest, most accurate and most reliable GPS library.  It can help you detect (and reject) bad data.


how to use AckPayload correctly i'm trying to send String from an Arduino(Uno) using the Serial. to an another Arduino(Uno). using nRF24l01+. and I'm using the library RF24.h
the String is sended correctly but I have some problems with the acknowledgement.

This is my Rx code.

#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
const uint64_t pipe[1]= {0xF0F0F0F0E1LL};
RF24 radio(9,10);
char buf[32]= "";
char false_buf[32]= "MKJK212U1H7";
void setup()
{
  Serial.begin(115200);
  radio.begin();
  radio.setChannel(0x35);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  radio.openReadingPipe(1,pipe[0]);
  radio.startListening();
  radio.setRetries(1,15);
  radio.writeAckPayload( 1, false_buf, sizeof(false_buf) );
}
void loop()
{
int OkMsg;
  while(!radio.available()){};
  if ( radio.available() > 0) {
    radio.read(&buf,sizeof(buf) );
    Serial.println(buf);
    radio.writeAckPayload( 1, buf, sizeof(false_buf) );
      while(!radio.available()){};
  if ( radio.available() > 0) {
    radio.read(&OkMsg,sizeof(OkMsg) );
    Serial.println(OkMsg);
    if(OkMsg == 1){Serial.println("OkMsg's true!");}
    else {Serial.println("OkMsg's false!");}
    }}
  }

and this is my Tx code

#include <SPI.h>
#include <RF24.h>
#include <nRF24L01.h>
RF24 radio(9, 10); // CE, CSN

const uint64_t pipe[1]= {0xF0F0F0F0E1LL};

char CharToSend[32]= "" ;
char Ack[32]= "" ;
String inputString = "";
String Allconfiguration = "";
boolean stringComplete = false;
char  inChar;
boolean isConnected = false;
int OkMsg = 0;

void setup()
{
  SPI.begin();
  Serial.begin(115200);
  RadioSetupTransmiter();
}

void loop()
{
  if(stringComplete)
  {
         if(Allconfiguration.startsWith("\n")){Allconfiguration.remove(0,1);}
     Allconfiguration.remove(Allconfiguration.length());
    inputString = "";
    Serial.print("Allconfiguration : ");
     Serial.println(Allconfiguration);
    int counter = 0;
    for(int i=0; i<Allconfiguration.length(); i++)
    {
      if((Allconfiguration[i] == '\n')&&(i!=Allconfiguration.length()))
      {
        int pre_counter = counter;
        counter = i+1;
        inputString = Allconfiguration.substring(pre_counter, counter);
        if(inputString[0]!='$'){inputString.toCharArray(CharToSend,32);}

        if(radio.write(&CharToSend, sizeof(CharToSend)))
        {CheckData();
       Serial.print("inputString : ");
         Serial.print(CharToSend);}
      }
       if(i == Allconfiguration.length()){
        const char EndChar[2] = "$";

       }
        inputString = "";
    }
    Allconfiguration = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
  char inChar = (char)Serial.read();
    Allconfiguration +=inChar;
     if (inChar == '$'){stringComplete = true;
    }
    }
}

void RadioSetupTransmiter(){  radio.begin();

  radio.setChannel(0x35);
  delay(100);
  radio.setAutoAck( true ) ;
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  // radio.printDetails();

  radio.stopListening();
  radio.openWritingPipe(pipe[0]);

  radio.setRetries(1, 15);
 }

void CheckData(){
  int OkMsg = 0;
    while (!radio.isAckPayloadAvailable()){};
      if(radio.isAckPayloadAvailable())
      {
       radio.read(&Ack,sizeof(Ack));
       //Serial.println(Ack);
       if(strcmp(CharToSend,Ack) == 0){
        OkMsg = 1  ;
        Serial.println("AckRecived");
        radio.write(&OkMsg,sizeof(OkMsg));}
    }
}

I have not used the RF24 libary, but below are the register settings that should be written during void setup() to use the ACK_PAYLOAD functionality (N.B. nRF24L01+ only, does not exist on nRF24L01.  Check you are using the right version of the radio!)

TX:

0x00 CONFIG = PTX mode
0x0B RX_PW_P0 = Number of data bytes in pipe 0
0x1C DYNPD = 0x01. Enable dynamic payload on pipe 0 (set DPL_P0 bit)
0x1D FEATURE = 0x06 (set bits EN_DPL and EN_ACK_PAY).

RX

0x00 CONFIG = PRX mode
0x0B RX_PW_P0 = Number of data bytes in pipe 0
0x1C DYNPD = 0x01. Enable dynamic payload on pipe 0 (set DPL_P0 bit)
0x1D FEATURE = 0x06 (set bits EN_DPL and EN_ACK_PAY).
Finally, load an initial payload using the W_ACK_PAYLOAD instruction 0xA8, i.e. SPI.transfer(0xA8); SPI.transfer(payload);.


Avrdude verification error after months of successful use I have a 2560 that I've been working with for a while (over a year for sure), programming it with an avrisp mk2. No issue this whole time, then suddenly, a couple of days ago it starts failing with

avrdude: verification error, first mismatch at byte 0x0002
         0x01 != 0x95
avrdude: verification error; content mismatch

And very obviously not flashing (there's logic that blinks the LED on boot, and the LED isn't blinking anymore).

The first time this happened, the board appeared completely dead - the programmer wouldn't recognize it, and refused to flash it. After a few days and magic it started recognizing it again, and going through the motions of flashing my firmware, but the verification error persists. The location of the error hasn't changed, nor has the two values (0x01 vs 0x95).

Any ideas what this could be?

Still don't know why, but now have a fix. Re-running the 'Burn bootloader' command from Arduino allowed me to then burn my firmware. Not sure if the issue is with fuses somehow being changed, or what, but this seems to have fixed the issue.

One more fun fact - I tried the same thing on a brand new Mega - same effect. First trying to burn my firmware resulted in a verification error (at a slightly different address), then burned bootloader and re-burned my firmware successfully. Wondering if an update to boards.txt or avrdude came through and changed something.


Arduino Hardware serial library with rts/cts flow control support Does there exist (any user developed etc.) version of the Hardware UART serial library that has support for RTS/CTS based flow control?
More interested in the Tx side (Arduino sends data, while the peripheral can back-pressure). The library should enable the Arduino to stop transmitting within 1 character of seeing a 'not ready' indication from the peripheral.

Thank you.

I am not aware of any such library. You could try to implement one
yourself, and maybe share it with the community. :-)

If you take this route, you will have to copy the file
HardwareSerial.cpp from the Arduino core, make your
changes there, and have your version replace the one from the core. Here
are some ideas that may help to get you started:

Wire the 'ready' signal from the device to an interrupt-capable pin of
the Arduino.
Inside the interrupt handler:

when 'ready' is deasserted, disable the UDRE interrupt by issuing
cbi(*_ucsrb, UDRIE0)
when ready is asserted, enable it again, but only if the output
buffer is not empty:
if (_tx_buffer_head != _tx_buffer_tail) sbi(*_ucsrb, UDRIE0);

Patch HardwareSerial::write() to enable the interrupt only if
'ready' is asserted.
Note that the UDRE IRQ can be explicitly called
by HardwareSerial::flush()
and by HardwareSerial::write() if interrupts are globally
disabled. You will have to condition this on the 'ready' signal.
Note also that HardwareSerial::write() can write directly to the
UART if the buffer is empty. This also has to be
conditioned on the 'ready' signal.


Arduino Mega 2560 with SIM808 module I have a SIM808 module like this: https://www.banggood.com/SIM808-Module-GPS-GSM-GPRS-Quad-band-Development-Board-For-Arduino-p-1063106.html

The output header has 5 pins: GND/RX/GND/TX/VCC and I connected them as:

GND/VCC to a LiPo battery, 7.4V@1000mAh

RX->pin 14 (written on it TX3)

GND->to arduino GND

TX->pin 15 (written on it RX3)

and uploaded this code

#include <SoftwareSerial.h>

SoftwareSerial GSMSerial(15,14);    // RX, TX

void setup()
{

  GSMSerial.begin(19200);
  Serial.begin(19200);
  Serial.println("START");
}

void loop()
{
  if(Serial.available())
    GSMSerial.print((char)Serial.read());
  else  if(GSMSerial.available())
    Serial.print((char)GSMSerial.read());
}

But I'm not getting anything on it (when sending "AT" or anything else).

Any help is appreciated.

Thank you!

Don't use SoftwareSerial on the HardwareSerial pins.  Instead of this:

#include <SoftwareSerial.h>
SoftwareSerial GSMSerial(15,14);    // RX, TX

Just do this:

#define GSMSerial Serial3


Wiring light sensor OPB704WZ to Arduino Due I would like to create a tachometer with the light sensor OPB704WZ.

I followed this schema https://tonyrobotdt081.wordpress.com/2014/04/10/report-on-the-light-sensor-opb704wz/ on a bread board (for now), and tried to measure the voltage difference on the signal pin (green on the schema).

Problem is, I don't see a clear difference between a white surface and a black one; It does change if I put the sensor closer or further away, but that's about all I can see.

Is there something else I need to add to my wiring to make the difference between high and low depending on the luminosity more obvious? I know others have been able to use this sensor for the same purpose.

You expect that the white surface to reflect the infrared light and the black surface does not.

Your theory is correct; white surfaces should reflect pretty much all light and the black surface should absorb all light.

The problem is that the black surface is reflecting enough light to turn the photo-transistor on.

The theory is correct but in the real world this is not perfect. For example a white surface is not completely white. Likewise no black surface is completely black.

We also know that a mirror is much better at reflecting light than a white surface. The black surface could be shiny. I am looking at my shiny black monitor stand, and even though it is black I can still see the reflection of the window.

I suggest trying with a number of black surfaces (such as paint, card, cloth) and finding the one that works best. I would imagine that chalk board paint would work well at absorbing and diffusing the infrared light. Also experiment with the distance away from the surface. You may have to move it further away from the surface.

If I am imagining your tachometer right, your sensor will see a reflective surface and then it will see empty space (and then repeat). This should work fine. Give it a try.


Need Help with Switch Case commands/receiver and lcd screen project? I am doing a project with a receiver and transmitter and i am trying to get a message to print onto the screen. If anybody has any experience with this could you please help! I am trying to use a switch case command and it's not working.
Edit:

`

#include <LiquidCrystal.h>
#include <VirtualWire.h>
LiquidCrystal lcd(12, 8, 5, 4, 3, 2);
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
void setup()
{
  Serial.begin(9600);
  Serial.println("Device is ready");

  // Initialize the IO and ISR
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  lcd.begin(16, 2);

  // Print a message to the LCD.
}

void loop()
{
  if (vw_get_message(message, &messageLength)) // Non-blocking
  {
    switch(message[1])
    {
    case 0:
      lcd.setCursor(0, 1);
      lcd.print("O.O");
      break;
    case 1 :
      lcd.setCursor(0, 1);
      lcd.print("Hi! :)");
      break;
    }
    {
      Serial.print("Received: ");
      for (int i = 0; i < messageLength; i++)
      {
        Serial.write(message[i]);
      }
      Serial.println();
    }
  }
}

Too many pieces of the puzzle are missing for us to venture a guess on what is going wrong:

The output you get (both in the LCD and the serial console)
The message sent

One thing that strikes me as a potential problem is the

switch(message[1])

line. If you want to check the first character received, it should be

switch(message[0])

That said, it would perhaps help you if you tried to split the program into pieces and make sure each one works before advancing to the next. Are you sure the LCD pin connections and initialisation line match? (I know from experience it is very easy to mess up and put the pin numbers in the wrong order). It would help to put the following code right after the lcd.begin line (in your setup() function):

  lcd.setCursor(0, 0);
  lcd.print("Initialised!");

Now if this line doesn't display correctly, you will know it is the lcd connection/initialisation code that is at fault. Otherwise, you will concentrate on your communication code.

Give us more information and we 'll be able to help more.


Arduino Nano use SPI pins as I/O pins? and still be able to do ISP? I wonder if can use the Arduino Nano SPI-pins(MOSI,MISO & SCK) as I/O pins in a sketch? and still be able to program over ISP?

Of course I will physical disconnect the Arduino from any other hardware before programming.

Yes, you can use SPI in your sketch just as you like. The programming over ISP is triggered by resetting the microcontroller. That means, that when trying to program over ISP your sketch (which configures the SPI hardware for use) doesn't run. The programming is starting at a stage, before the sketch runs, thus the sketch cannot interfere.

By the way: The same is correct for programming over Serial, though for a different reason. Programming over Serial is done by the bootloader, which runs before your sketch.


Advisability of Using Bit Fields in Structs I have to track a large amount of data (for an Arduino) in a program while taking care of a fair amount of other business.

I started with a struct like this:

struct MyStruct
{
   // note: these names might as well be foo bar baz
   uint8_t color;
   boolean state;
   uint8_t area;
   uint8_t number;
   uint8_t len;
};

I have an array of 800 of these. At 5 bytes each, that's 4Kb, or half the ram on the Arduino Mega.

I changed to a struct like this:

struct MyStruct
{
   uint8_t color : 3; // max value 7
   // uint8_t state : 1; *** moved, thanks Ignacio ***
   uint8_t area : 5; // m.v. 31
   uint8_t number;
   uint8_t len : 5; // m.v. 31
   uint8_t state : 1; // m.v. 1
};

I understand this reduces the size of each instance to 3 bytes, for a total of 2.4Kb in my array.

I have read that in some implementations / chipsets using bit fields in structs can lead to less efficient execution. Obviously this is a more efficient use of memory, but my question is:

How does the Arduino handle bit fields? Will it be better, worse, or negligibly different in terms or speed when iterating through an array of bit field structs? Is there a good way to test this?

What you are facing is the classic time-memory tradeoff.  The bit fields will be smaller in memory,  but will take more time to operate on.  You can count that no matter what processor, the bit fields will be slower.

You use the word efficient, but that word has no certain meaning without a metric for what is good or bad.  When you only have 8 k of RAM, using memory is bad, time may be cheap.  If you have real time constraints, then using time is bad and memory may be cheap.  In general, you can only buy your way out of this tradeoff.  In other words, when you find both time and memory bad, spend cash and use a bigger chip.  There is no single answer for what is good or bad.  This is part of why there are so many choices for microcontrollers, people fit the chip to the application and application to the chip.

Populating the bits of a bit field will be slower than filling of complete bytes.  Take for example

x = 5;
...
asimplestruct.len = x;
// vs
abitfield.len = x;

The first simple case will just:

load value of x to a register
store it to the byte for len

The second does something like:

loads the current value of abitfield
loads a mask
clears the bits for len
loads current value of x
loads a mask
clears off unused bits of x
shifts the bits of x
or's x with the abitfield
stores the current value back to memory

If all your operations are packing data into the bit field, or unpacking out of the bitfield, you should expect slower execution.  Bit fields are a type of compression - they cost ticks.

But moving around bit fields will be faster because there are less bytes to load and store.  If you where sorting this array, the smaller byte count could be an advantage.  If you where transferring them over a serial port, the compressed size of the bitfield might be a winner.

So with respect to your question:

  Is there a good way to test this?

The only good way to test this is to write test cases for both approaches using a pattern that closely matches your application.  It really matters what mix of operations you perform to decide whether the difference is negligible or significant.

When doing this sort of optimization experiment, definitely use source control on your project.  You can create a local GIT or Mercurial repository with just a few clicks.  Keeping a chain of checkpoints allows you to tear up your code exploring the effects of different implementations.  If you take a wrong turn, the repository allows you to simply go back to the last good point and try another path.

(Side note:  This time memory tradeoff exists in the opposite direction also.  If you look through the compiler options for desktop class processors, you will find something called structure packing.  This option allow you to add blank bytes between single byte fields such that they stay aligned at word or double word boundaries.  This may seem crazy to throw away RAM on purpose, but on processors with 16 or 32 bit wide registers and buses, so called word or dword aligned memory operations can be faster than byte wise operations.)


How can the Arduino check if it is connected to a PC and the PC is on? I have been searching around the Internet to find if there is a way to check whether an Arduino is connected to a PC or not.

For example: if my PC is turned on, the Arduino will listen to any serial commands it receives, BUT if my PC is turned off, the Arduino will receive some random characters.

How can the Arduino check if it is connected to PC and the PC is on?

As suggested by Paul & Gerben, you could check the 5V USB line to see if it has a voltage or not.

I am assuming from your question that the Arduino is not powered from the USB line. I am also assuming that the USB port is not powered when the PC is turned off.

All you have to do is connect VUSB to a digital input through a resistor like so:

Alternatively, you could have the computer send a pre-determined message telling the Arduino that its alive.

If the Arduino receives this message then it lights up the LED on pin 13. If the Arduino hasn't received the "I'm alive" message for a while (ie. a timeout) it then turns off the LED.

A simple PC program could be written to automate this task.


can I program a nano over SPI with another nano? I'm fairly new to arduino, but I want to program a nano over SPI to skip the bootloader. I know I can program the nano with an uno as a programmer to do this, but I don't have an uno, but I do have a couple of nanos. Can I set up one as a programmer, connect it to another over SPI, and program the 2nd?

Yes, you can. They use ATmega328 / Atmega328P microcontrollers, which are basically the same.

(The differencies of those microcontrollers are about Brown Out Detection - how they could be set to react on too low voltage. No problem in nearly any Arduino operation.)

The boards differ mainly in the board size and places for pins.


Arduino Micro and MPU-9150 I'm trying to connect an Arduino Micro to MPU-9150 using the  MPU6050_DMP6 example.
It runs for couple of seconds then the board Hangs, I sometimes see the "FIFO overflow" message.
The same code runs well when i connect the MPU-9150 to Arduino UNO and Arduino Duemilanove.
I tried to lower the serial baud rate but no success with that. I even tried connecting an external 12V to the Micro but it's the same.

should I lower the i2c clock (not sure how to do it)?

another interesting thing i have noticed is that with the Duemilanove i can use a longer line for the i2c (5m of cat5e), with the Uno it only works with less then 2m cables, can anyone tell why?

I have seen a lot of variations with the 6050.  Code I know works fine for me, will not run on someone else's system.  Code fixes suggested by others has zero effect for me.  My understanding is the DMP code is a reverse engineered sample that the manufacturer will not release actual documentation on. So it is a gamble to begin with.

That being said, I usually reset the FIFO buffer after every read.  I get an occasional over flow (1-2 per minute) with a lot of other code running at the same time, and NOT using interrupts.  The resulting AHRS data is reliable and solid (UNO) at default rate (100hz).  Ive lowered the AHRS rate (you have to modify data tables in a .H file) and I get the same error rate, it seems to have no effect.

As far as line lengths go, it is I2C. It is some magical combination of wire size and length, internal pull up resistors plus external ones.  I have usually heard people have success adding some pull-up resistors  I2C is a ground sink signal - so it doesn't care if it is 5 volts or 3.3 - only that everything on the bus be the same.  Obviously you will do better at 5V on a longer line vs 3.3V.  Some will argue the pull ups need to be at termination, some say it doesn't matter. I don't know anything other than the spec is very hard to understand and I have not had problems, especially the kind that require some of the elaborate schemes some people come up with (replacing caps and resistors).

Anyhow, 2 meters would seem to be pushing an Integrated circuit to Integrated circuit spec beyond what it was intended for, communication within a board. You might get it to work, but you also might rethink it.


If value in serial begin is greater than that of delay in arduino, does delay time matters? I think if the value inside Serial.begin() is greater than the value inside delay(),then delay will not take the next step as soon as the next input is there ... So , the delay() function is insignificant...no?

The parameter to Serial.begin(speed) is the BAUD rate, or the speed characters are read (and written) from (to) the serial line.  The parameter in delay(time) is the number is milliseconds that the system will wait for.

I think what you may have noticed is that by experimenting with the Baud and delay parameters you notice that you are receiving characters slower and faster.
The faster the serial line the more data you will receive, but the longer the delay the more the data will be slowed down, because the receive buffer will become full.

If the delay is very small (<50) then yes it will appear insignificant.
Try Serial.begin(9600) and delay(30000). This will show how significant the delay is :)


Arduino UNO button LED brightness vary I am using an Arduino UNO and I am trying to vary the brightness by steps by 0.5 volts till it gets to a max of 5.0 V using buttonA and decrease the brightness of the LED by 0.5 volts with buttonB. The Problem I have is that when I push buttonA the LED steps it's voltage by 0.5V all the way to 5.0V and with buttonB its steps down to 0. I would like to have the LED step each time I press the button not all at once. Here is my code that I have so far can someone help me with telling the Arduino to Step each time a button is pressed. CODE IS DIFFERENT from another post I did

HERE is my code:

int ledPin = 9; // must be a PWM digital pin
int buttonApin = A2; //buttonA to analog 2
int buttonBpin = A1; // buttonB to analog 1
int maxBright = 255; // between 0 and 255
int ms = 1500;    // delay in milliseconds
int buttonPushCounterA = 0; //counter for the number of button presses
int buttonStateA = 0; // current state of the button
int lastButtonStateA = 0; // previous state of the button
int buttonPushCounterB = 0; //counter for the number of button presses
int buttonStateB = 0; // current state of the button
int lastButtonStateB = 0; // previous state of the button

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
}

void loop()
{
  if (digitalRead(buttonApin) == LOW) //if buttonA is pushed
   {
      buttonStateA = digitalRead(buttonApin);

     if (buttonStateA != lastButtonStateA)
     {
        if(buttonStateA == LOW)
     {
        buttonPushCounterA++;
     }
    }

// fade from min to max in increments of 25.5 points: basically (0.5 volts)
for (float n = 0; n <= maxBright; n +=25.5)
{
 // sets the value (range from 0 to 255):
 analogWrite(ledPin,n);
 delay(ms);
}
  }

  if (digitalRead(buttonBpin) == LOW) //if buttonB is pushed
  {
     buttonStateB = digitalRead(buttonBpin);

       if (buttonStateB != lastButtonStateB)
         {
            if(buttonStateB == LOW)
              {
                buttonPushCounterB--;
              }
         }

     // fade from max to min in increments of 25.5 points: basically (0.5 volts)
     for (float n = maxBright; n >= 0; n -= 25.5)
    {
     // sets the value (range from 0 to 255):
     analogWrite(ledPin, n);
     delay(ms);
    }
  }

  lastButtonStateA = buttonStateA;
  lastButtonStateB = buttonStateB;
 }

One problem in your original code is that you are only storing the current state of the buttons if they are pressed.  The next problem is that you are looping through all your brightness values when a button is pressed giving you your "fades all the way up in one go" problem.

This would be my replacement for your loop() code:

loop()
{
    int currentButtonStateA = digitalRead(buttonApin);
    if (currentButtonStateA != lastButtonStateA && currentButtonStateA == LOW)
    {
        currentBrightness += BRIGHTNESS_INCREMENT;  // BRIGHTNESS_INCREMENT is defined at the top of the file with #define BRIGHTNESS_INCREMENT 25
        if (currentBrightness > MAX_BRIGHTNESS)     // MAX_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 255
        {
            currentBrightness = MAX_BRIGHTNESS;
        }
    }
    lastButtonStateA = currentButtonStateA;

    int currentButtonStateB = digitalRead(buttonBpin);
    if (currentButtonStateB != lastButtonStateB && currentButtonStateB == LOW)
    {
        currentBrightness -= BRIGHTNESS_INCREMENT;
        if (currentBrightness < MIN_BRIGHTNESS)     // MIN_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 0
        {
            currentBrightness = MIN_BRIGHTNESS;
        }
    }
    lastButtonStateB = currentButtonStateB;

    analogWrite(ledPin, currentBrightness);
}

Hopefully this is pretty self explanatory.  The current button A state is read and stored in a local variable.  If it is different to the previous state and it is low, the current brightness is incremented and capped at a maximum value.  Next the current button state is stored as the previous state ready for the next run through the loop.

Similar actions are performed for the B button, but with a decrement rather than an increment.  Finally the LED brightness is set regardless of whether any buttons have been pressed.

You do not need to store your current button states (buttonStateA) or your counts for the number of button presses (buttonPushCounterA - which you never referenced anyway) or your ms value so could get rid of those global variables.  You need a new global variable at the top of your file for currentBrightness (int currentBrightness = 0;).

You have used variables to store various non-changing numeric values, such as "maxBright = 255;" which is good practise, but is better (particularly with Arduino development) to use #define macros instead, such as "#define MAX_BRIGHTNESS 255".

The reason for this is that variables take up memory when the code is running - something that an Arduino Uno doesn't have a lot of, whereas a #define takes up no memory - the compiler uses it as a "search and replace" before compiling your code.


How to remove any previous program from Arduino? I have a Arduino UNO and I want to remove the previously uploaded code....how to do that?

Just upload a new one. I frequently "blank" an arduino when I'm done with it by uploading "Blink.ino" from the examples included with the IDE. (The only reason I've had to remove old code is to avoid an issue where I might later wire up the Arduino in a way that is dangerously incompatible with the old code running on it.)


Converting Arduino UNO's analog pins to digital I/O I am working on an Arduino UNO Project and running out of digital pins.

Can I convert the six analog pins to digital I/O and use them to drive servos?

Please suggest me a method

A0 through A5 already have GPIO capability; treat them as you would any other non-PWM pin.

A6 and A7, found in similar boards that use a SMD package, do not have any GPIO capability whatsoever and can only be used for analog input.


Can I connect my Arduino Uno to a power source and a battery at the same time? My aim is to be able to power my Arduino while there is a power supply and if there isn't the Arduino automatically switches over to the battery. The components connected to the Arduino are pir sensor, smoke sensor, SIM 800L, temperature sensor, 6v relay.

Yes, to my knowledge this is done automatically, and there is no harm when connecting the Arduino to two power sources. When I power my Arduino I have it connected to my computer and the wall. So theoretically, if the electricity in the wall stopped coming, it would start taking power from the computer. Same works for battery.


20x4 LCD shows up as 20x2 I need help with my LCD. I have a 20x4 LCD and it shows up as 20x2. The LCD address said "// Set the LCD address to 0x27 for a 16 chars and 2 line display". I changed it which says "// Set the LCD address to 0x27 for a 20 chars and 4 line display" and uploaded it, thinking it would show up as 20x4 as it should. But it didn't work:

Nori, just ignore every code that's after the //, they are just comments and the compiler will just discard them.

Look at the LCD rear, you should see your I2C chip, search google typing
["chip's code"  20x4 arduino]. You'll see which I2C address you most likely need to use. For instance, the PCF8574 has addresses fromm 0x20 to 0x27, the PCF8574A has addresses from 0x38 to 0x3F...

Without this info you are only shooting blindfolded, the 0x27 it's only the "standard" address of the most common PCF8574 module but there are plenty of modules.

Another way to find the address is to upload this code, it's an I2C scanner that will write on the serial monitor any I2C device that replies a "ping" signal.

If you find the address and still it doesn't work or if you can't find the address, check and double and triple check the wiring, especially the false contact.


Not receiving the complete messange sent by SIM900 I need help with SIM900 and Arduino Mega. I do not receive the complete message that I send from my phone. (Arduino Mega _ SIM900 _ Alimentation 9V/2A)

Message sent:

1234567891234567890

Message received:

12345678912

String Char;
void setup() {
  Serial.begin(9600);
  Serial2.begin(9600);

}

void loop() {
  while (Serial2.available()) {
    Char += (char)Serial2.read();
  }
  Serial.println(Char);
  delay(1000);
}

change the test sketch to

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

void loop() {
  if (Serial2.available()) {
    char c = Serial2.read();
    Serial.write(c);
  }
}

or use the SerialPassthrough sketch from examples

or

void setup() {
  Serial.begin(9600);
  Serial2.begin(9600);
  Serial2.setTimeout(100);
}

void loop() {
  if (Serial2.available()) {
    String s = Serial2.readString();
    Serial.println(s);
  }
}


How to calculate the time it takes before the water valve stops dispensing water in an Automatic Water level controller? I am making a project about an automated water level controller using ultrasonic, potentiometer and Arduino board. I need a mathematical calculation on how it works. So here's a simple scenario:

I have an open top cylindrical container with a radius of 7cm. The ultrasonic sensed that the half height of the container, which is 15cm, is filled with water. At the bottom part of it, a tube with a radius of 1cm is connected alongside with the water valve. How can I calculate the time needed for the water valve to stop dispensing water if I set the potentiometer to keep the level of water at 9cm only? Can you give me a mathematical formula??

I really need a help, please. Any answer will be highly appreciated. Thank you in advance.

The concept you have is more complicated than you can imagine. But to answer your question (which is not so arduino-based), the mathematical formula you looking for is Torricelli's Law.

My suggestion for you is design a system which use a feedback concept instead


op amp circuit single sourced from arduino power Getting an audio signal from a 3.5mm jack amplified (non-inverted) and fed into analog in pin on a Mega 2560. I am having problems using a potentiometer as a variable resistor to adjust gain. I'm also getting a lot of noise (+/-10 units on the 0-1023 scale)

Circuit:
- The audio is from a mono 3.5mm jack, playing from my laptop (with audio split to my speakers).
- Audio goes through an op amp TL071, single sourced shared with arduino 5V
- The potentiometer is wired with 2 pins as a variable resistor. The pins are connected to ground and the inverting input (VCC-)
- Output signal from the op-amp is biased by 2.5V and seems to work fine.

I'm closely following the instructions here (https://www.instructables.com/id/Arduino-Audio-Input/) but with a TL071 op amp as a single sourced from the Arduino 5V power supply.

The potentiometer doesn't seem to make much difference; I can even unplug it and I still get some readings on A0. I'm misunderstanding how to 'rewire' the op-amp for a single supply, but I can't figure out what else I can do.

The TLO series don't work with 5v supply. They have also a reversal phase : that meens, when used in follower, it's output will go high when intut is lower than 3v...
One can use an old LM324 or LM358, but output is not going up to VCC...
OPA140 is a correct choice.
Also, may be a link capacitor of 100µF between input and potentiometer is necessary : this avoids amplification of DC, gives a centered output, and will reduce noise due to DC paht in potentiometer.


How does if(serial) work, a c++ question The Arduino documentation says if(Serial) always returns 1, except for the case where Leonardo USB serial connection delays becoming ready.

(Leonardo has two USB IDs, and switches between them for boot loader and Serial USB.  After boot loader finishes and kicks off the program, it takes a while for the USB master (e.g. your PC) to process the disconnect of the boot loader USB device and the connection of the Serial USB device.  Thus the need for a wait.)

Now "Serial" is a static external instantiation of the Serial_ class (defined as extern Serial_ Serial;).

The c++ rules, as I understand them, do not allow a constructor to return a value, nor may the class name (which is also the constructor name) be used as a member (function) name in the class.

"Serial" cannot be defined in class Serial_, or the if(Serial) syntax would have to be if(Serial.Serial).

"Serial" cannot be defined outside the class Serial_, or it will conflict with (i.e. hide) the definition of Serial as an instantiation of Serial_.

So how does the Arduino IDE do it?

All I can think of is that the magic pre-scanner does something...  But what exactly, pray tell?

It's not the constructor that's returning the value, it's the bool operator:

Uno:

HardwareSerial::operator bool() {
    return true;
}

Leonardo:

Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

When you use the object in a setting where a boolean value is expected of it (e.g., if, while etc.) the bool() operator is called (if it exists) and that value is used.

More specifically, the bool() operator is called when the object is being cast to a bool type, either implicitly (as in if...) or explicitly (as in ... = (bool)Serial;).

More on C++ class operators here: http://en.cppreference.com/w/cpp/language/operators


How to get the overall average of the data received I have an arduino uno with two sensors. Voltage and current sensors. I need to get the average value of voltage and current each time the data is received. But i don't know how to add up the current and previous values and divide it to how many values that it has received.

Can someone help me, please? I need it for my project

This is the code i have made

void setup(){
Serial.begin(9600);
}
void loop(){
    int n=5;
    float sum=0;
    float ave=0;
    for(int x=0;x<n;x++){
        float volt=analogRead(A0);
        float voltage = map(volt,0,1023,0,2500);
        voltage/=100;
        Serial.print("Voltage: ");
        Serial.print(voltage,2);
       sum=sum+voltage;
       }
ave=sum/n;
Serial.print("Average: ");
Serial.print(average,2);
delay(3000);
}

But this only takes the average of 5 datas. I want to get the average of all data received.

void setup(){
Serial.begin(9600);
}
void loop(){
    static unsigned long count=0;
    static float sum=0;
    float ave=0;
    int volt=analogRead(A0);
    float voltage = map(volt,0,1023,0,2500) / 100.0;
    Serial.print("Voltage: ");
    Serial.print(voltage,2);
    sum=sum+voltage;
    count++;
    ave=sum/count;
    Serial.print("  Average: ");
    Serial.println(ave,2);
    delay(3000);
}

This runs quite a while. The average is restarted only with a Reset of your arduino.

Alternatively, you might want to learn about a moving average (aka low pass filter)


DC Motor's don't stop immediately Functionality

I have written this code below for a buggy to continue moving forward until there is an obstacle which is <= 25cm both motors should stop.

Result

both motors stop when there is an obstacle which is <=25cm but the motors happen not to stop immediately when it comes across the obstacle please do find my code below is there something wrong with my code and how can I make it much better.

Code

#define PING_PIN  12  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
#define PING_MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

//initializing left DC Motor
const int in_1 = 2; // initializing the IN1 to Pin 2
const int in_2 = 3; //initializing the IN2 to Pin 3
const int EnA = 4;  //initializing pin 4 as pwm

////initializing Right DC Motor
const int in_3 =5;  // initializing the IN3 to Pin 5
const int in_4 = 6; // initializing the IN4 to Pin 6
const int EnB = 7;  //initializing pin 7 as pwm

// initialzing Ultrasonic sesor (Front view)
const int trigPin = 8;
const int echoPin = 9;

//For providing logic to L298 IC to choose the direction of the DC motor
void setup()
{
    /// initialize serial communication:
    Serial.begin(9600);
    pinMode(EnA,OUTPUT);   //we have to set PWM pin as output
    pinMode(in_1,OUTPUT);  //Logic pins are also set as output
    pinMode(in_2,OUTPUT);
    pinMode(EnB,OUTPUT);   //we have to set PWM pin as output
    pinMode(in_3,OUTPUT);  //Logic pins are also set as output
    pinMode(in_4,OUTPUT);

    //--------------------------------------------------------------
    // Reading the signal from the sensor: a HIGH pulse
    //-----------------------------------------------------------------
    pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)
    pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)
    //pinMode(trigPin2, OUTPUT);// set the trig pin to output (Send sound waves)
    //pinMode(echoPin2, INPUT);// set the echo pin to input (recieve sound waves)
}

void loop()
{
    int duration, Distance; // start the scan
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2); // delays are required for a succesful sensor operation.
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10); //this delay is required as well!
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    //---------------------------------------
    // convert the time into a distance
    //---------------------------------------
    Distance = (duration/2)/29.1;
    Serial.print(Distance);
    Serial.print("cm");
    Serial.println();
    delay(1000);
    if (Distance <= 25)
    {
        //Stopping Right and Left Motors
        digitalWrite(in_1,HIGH);
        digitalWrite(in_2,HIGH);
        digitalWrite(in_3,HIGH);
        digitalWrite(in_4,HIGH);
    }
    else {
        //Moving both Motors in a Foward motion - IN_1 = LOW , IN_2 = HIGH, IN_3 = LOW , IN_4 = HIGH
        digitalWrite(in_1,HIGH);
        digitalWrite(in_2,LOW);
        analogWrite(EnA,200); // Enablling the Right motor @ speed of 200
        digitalWrite(in_3,HIGH);
        digitalWrite(in_4,LOW);
        analogWrite(EnB,200);// Enablling the Left motor @ speed of 200
    }
}

As already stated, your problem is in the use of delay(), which
blocks the program until the delay is over. When your program needs to
be responsive, you have to write everything in a non-bloking manner.
The basics of non-blocking management of time are covered in the
Blink Without Delay Arduino
tutorial, which I
strongly encourage you to read. Applying the technique of the tutorial
to your printing of the distance gives something like this:

static uint32_t last_time_printed;
uint32_t now = millis();
if (now - last_time_printed >= 1000) {
    Serial.println(Distance);
    last_time_printed = now;
}

I think the code is quite straightforward: you record the last time you
printed the value and, if it has been one second since last time, you
print it again.

You also have some other blocking calls in the section where you operate
the sonar. I would not worry too much about delayMicroseconds(): these
are really tiny delays, and your robot does not need to be that
responsive. I would worry about pulseIn() though: this function blocks
until it sees the end of the pulse, or until it reaches a timeout. The
default timeout is one second, which is way too large for this
application. Instead of relying on the default, you should specify a
timeout as a third parameter, as in

duration = pulseIn(echoPin, HIGH, 50000);  // timeout: 50 ms

This would limit the range to about 8 m, which I think should be
more than enough.

Reading the sonar pulse in a completely non-blocking fashion is
possible, by using either an input capture unit or an interrupt, but I
guess it is not worth the trouble, as your robot can probably cope well
with being blocked for 50 ms.


Where in datasheet is the warning about unreliability of reading PINxn? I use atmega32u4 (but believe it applies to all models). Here is the datasheet.

Consider the following C program (I use AVR-GCC 5.4.0):

#include <avr/io.h>
int main(void)
{
  PORTB |= 1 << PB5; /* pullup */
  DDRB |= 1 << PB0; /* LED */
  if (!(PINB & 1 << PB5))
    PORTB |= 1 << PB0; /* turn on LED */
  while (1) ;
}

There are two situations:

connect a 10cm wire to PB5 pin (the other end of the wire is in the air): the result is that sometimes after poweron the led is on, sometimes the led is not on.
do not connect anything to PB5 pin: the result is that after poweron led is never on.

I have a standard setup. Nothing tricky. If it does not work reliably, this gotcha MUST be documented in datasheet. This setup is supposed to deal with a stupid button. But sometimes it detects a keypress while there is no keypress.

The question is: where in datasheet there is a warning about this gotcha?
And did somebody come across such case, or I'm the first in the world?

EDIT See also this question.

did somebody come across such case, or I'm the first in the world?

You are not the first. I recently got bitten by the very same issue.

However, unless you are close to an unusually strong radio source, I do
not think it has anything to do with electromagnetic interference. In my
experience, the internal pullup is perfectly reliable for reading
switches and push buttons, even on a breadboard with jumper wires acting
as antennas. If you use pinMode() and digitalRead() instead of
direct port access, you too will find the internal pullup is perfectly
fine.

Before I give you the answer (suspense...), let's look closely at what
your code does. The disassembly looks like this:

main:
    sbi  PORTB, PB5 ; turn on pullup on PB5
    sbi  DDRB,  PB0 ; set LED pin as output
    sbis PINB,  PB5 ; read PB5, if it is LOW then:
    sbi  PORTB, PB0 ;   turn on LED
0:  rjmp 0b         ; hang in an infinite loop

In the situation when the LED turns on, every instruction there executes
in two CPU cycles, save for sbis, which takes a single cycle in this
case. Now, let's look at the timings, and specifically at the states of
the pullup and the input circuitry during each of the first seven CPU
cycles:

cycle   instruction   pullup latch PINB5
----------------------------------------
   1   sbi PORTB, PB5   off    X     X
   2      cont.         off    X     X
   3   sbi DDRB,  PB0   on     X     X
   4      cont.         on    LOW    X
   5   sbis PINB, PB5   on     X    LOW
   6   sbi PORTB, PB0   on     X     X
   7      cont.         on     X     X

In the table above, “X” means “don't care”. Each instruction takes
effect at the beginning of the next CPU cycle, when the clock's rising
edge commits the result of the instruction to the affected flip-flops.
That's why the pullup turns on only at the beginning of cycle 3.
Now, since the pin did read LOW, that means the PB5 flip-flop was LOW
while the CPU was reading it, during cycle 5. This in turn means
that the synchronizing latch before that flip-flop was LOW during
cycle 4.

Your expectation was for the pin to read HIGH. So let's see: how fast
should the pin voltage have risen in order for the pin to indeed read
HIGH? Since the input latch is transparent during the first half of each
cycle, this means that the voltage should raise past the Schmitt
trigger's threshold during cycle 3 and the first half cycle 4.
So the rise time should be less than 1.5 cycles. Or rather
1.5 cycles minus the combined propagation delay of the PORTB5
flip-flop and the logic that controls the pullup from that flip-flop's
output. Probably around 90 ns. That's short!

By now you have probably guessed: the culprit is not electromagnetic
interference, it's stray capacitance. A simple calculation will show you
that about three picofarads is enough to produce the effect you are
seeing. This is the kind of stray capacitance you will find everywhere,
even between the PCB traces of your Arduino board. Note that
electromagnetic noise can add some unpredictability to what you see, as
the pin is susceptible to it when it's completely floating, i.e.
before you turn on the pullup, which makes the initial voltage (at the
beginning of cycle 3) unpredictable. But once the pullup is on and
the pin has settled, you won't care about noise anymore, unless it's
unusually strong.

The solution to your problem is simply to wait for the pullup to charge
the stray capacitance. A microsecond delay should be enough to fix the
issue. Alternatively, use the Arduino functions instead of direct port
access: they are so slow that you will not need any extra delay.

  where in datasheet there is a warning about this gotcha?

In section 18.2.4 – Reading the Pin Value: “[The synchronizing latch] is
needed to avoid metastability if the physical pin changes value near the
edge of the internal clock, but it also introduces a delay.”
(emphasis mine).

Edit: In a previous version of this answer, I incorrectly stated
that sbi is a single cycle instruction, which required the voltage to
rise in half a cycle instead of 1.5 cycles. The corrected timing is
still short enough for stray capacitance to be a valid explanation of
the observed behavior.

In summary:

The stray capacitance attached to the pin, together with the pullup
resistor, for an RC circuit.
As the pin is initially floating, it's initial voltage is
unpredictable.
When the pullup is turned on, the voltage starts to rise from whatever
initial value it had to 5 V.
After some time, which can be typically of the order of the RC time
constant, the input Schmitt trigger turns HIGH.
After some extra delay introduced by the synchronizer, the PINxn
flip-flop turns HIGH.
If the CPU reads the PINx register before that happens, it gets a LOW
reading.


Python - Arduino communication not reliable I'm trying to establish basic communication between python and my arduino due. I have managed to get a message sent to the arduino and sent back, but the code that achieves this task does not give consistent results. I'm running python 3.5 with pyserial 3.3.

My Arduino Code:

String incoming;

void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incoming = Serial.readStringUntil('\n');

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incoming);
        }
}

My Python Code

import serial

arduinoSerialData = serial.Serial("COM5",9600,timeout=1)

print("Initial in waiting:")
print(arduinoSerialData.in_waiting)
print("Initial out waiting:")
print(arduinoSerialData.out_waiting)

while (arduinoSerialData.in_waiting>0):
    garbage = arduinoSerialData.readline()
    print(garbage)

nummessages =0

while (nummessages<5):
    if (arduinoSerialData.in_waiting>0):
        myData = arduinoSerialData.readline()
        myData = myData.decode('utf-8')
        myData = myData.strip()
        print("The Arduino says:")
        print(myData)
        nummessages=nummessages+1
    elif(arduinoSerialData.out_waiting>0):
        pass
    else:
        arduinoSerialData.write(b'Hello Arduino!\n')

while (arduinoSerialData.in_waiting>0):
    garbage = arduinoSerialData.readline()
    print(garbage)

print("In Waiting: ")
print(arduinoSerialData.in_waiting)
print("Out Waiting: ")
print(arduinoSerialData.out_waiting)
arduinoSerialData.close()

These print statements are largely my failed attempt to diagnose the problem. The "garbage" loops were my attempt to make sure conditions were as identical as possible when the python code starts up. If I start the arduino program running and then call this python program from my command line I get inconsistent results. Sometimes my first call to the python "works" and then others won't, sometime it works several times in a row, and that first line out output where it says "The Arduino Says: I" will have a varying amounts of the "I Received: Hello Arduino" message the arduino was supposed to send. Any Ideas what could be causing this lack of consistency? If I try starting the python code first, the arduino can't even start up.

In case other people run into similar issues, I'll lay out what I've found today.

-The inconsistent output was due to the fact that when you open a serial connection with python, it resets the Arduino and so python can send signals without the arduino having finished its setup() function. If I put in a 1 second delay on the python side, inconsistency stops and I no longer run into byte errors at all. I'm looking into alternative means of preventing this reset since the time delay is a deal-breaker for me.

UPDATE:
Replacing

arduinoSerialData("COM5",9600,timeout=1)

with

arduinoSerialData = serial.Serial()
arduinoSerialData.port = "COM5"
arduinoSerialData.baudrate = 9600
arduinoSerialData.timeout = 1
arduinoSerialData.setDTR(False)
#arduinoSerialData.setRTS(False)
arduinoSerialData.open()

seems to bypass the reset. I included both the setDTR and SetRTS functions here because although setDTR works for DUE, it seems some other Arduino boards need setRTS instead.

-The decode() function has a keyword argument called errors, which can be set to "ignore" if you want the code to just ignore things that can't be interpreted in your desired format. With just this keyword setup, I never got errors but output was inconsistent due to reset.