text:
Setting reading frequency SCT013 current sensor code using Arduino Uno
I found this code below for the Arduino platform to obtain current measurements from the SCT013 sensor, and I am wondering how can I define the 'delay' or 'frequency' of my readings? I'd be looking for 200Hz.
Code:
//
#include "EmonLib.h"                   // Include Emon Library
EnergyMonitor emon1;                   // Create an instance

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

  emon1.current(5, 60);             // Current: input pin, calibration.
  //calibration is explained bellow
}

void loop()
{
  double Irms = emon1.calcIrms(1480);  // Calculate Irms only

  Serial.print(Irms*230.0);        // Apparent power
  Serial.print(" ");
  Serial.println(Irms);            // Irms
}
//

That is a very strange question to ask. What do you want to achieve ? Have you heard about the XY-problem ? http://xyproblem.info/ If I remember it correctly, the EmonLib samples at a higher frequency and returns the average. Why do you want 200 samples per second from a 50Hz or 60Hz signal ?

You already asked the question with a current sensor: https://arduino.stackexchange.com/questions/45293/3-ac-current-sensors-using-one-arduino-uno-board-measuring-at-200hz

you skip reading when the last read is less than 1000/200 = 5ms ago.
unsigned long lastRead;

void loop()
{
   unsigned long currentMillis = millis();
   if(currentMillis - lastRead >= 5){

      double Irms = emon1.calcIrms(1480);  // Calculate Irms only

      Serial.print(Irms*230.0);        // Apparent power
      Serial.print(" ");
      Serial.println(Irms);            // Irms
      lastRead = currentMillis;
    }

}

If you want a 200Hz sample rate this code doesn't work for you.
With this line:
double Irms = emon1.calcIrms(1480); you take 1480 samples as fast as Arduino can.
If you want 200Hz sample rate, read analog ping every 5ms using millis() function. And when you have enough samples you can calculate the rms current https://en.wikipedia.org/wiki/Root_mean_square
This is an example code:
unsigned int sample_time = 0;
int readings[200];  //num samples 200
int i = 0;

setup() {
}

loop() {
    if (millis() - sample_time > 5){
        readings[i] = readAnalog(A0);
        i++;
        sample_time = millis();
    }
    if (i > 200)
         Caculate_Irms();
         i = 0;
}


text:
Problem with LCD
I'm working on this piano project. When I push a button one of the led light is suppose to turn on and a tone comes out of the piezo. The LCD screen is suppose to print out a sentence but I can't get it to work.
Here is a picture of the board ( everything works except the LCD) I think the problems lies in the power supply but I'm not sure. This is the first time I use a big breadboard.
Here is my code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(13,12,11,10,9,8);

int p1 = 1;
int p2 = 2;
int p3 = 3;
int p4 = 4;

int C,D,E,F;
int buzz = 5;

void setup()
{
   lcd.begin(16, 2);

  lcd.print("hello, world!");

  Serial.begin(9600);
  pinMode(p1,INPUT);
  pinMode(p2,INPUT);
  pinMode(p3,INPUT);
  pinMode(p4,INPUT);

}

void loop()
{

  lcd.setCursor(0, 1);

  lcd.print(millis() / 1000);

  C = digitalRead(p1);
  D = digitalRead(p2);
  E = digitalRead(p3);
  F = digitalRead(p4);

  if(C == 1){

    tone(buzz,523);
  }else if(D == 1){
    tone(buzz,587);
  }else if(E == 1){
    tone(buzz,659);
  }else if(F == 1){
    tone(buzz,698);

  }else{
    noTone(buzz);
  }
  delay(50);
}

the power rails are separated in the middle of the breadboard. bridge them with jumper wires

According to the picture, RS and E are connected to pin 8 and 9. According to your sketch, RS and E are connected to 13 and 12.

Did you set the contrast correctly (using the potentiometer)?

The LCD is not powered, there are 2 separated power rails... use a wire to connect both rails.

Where do I put the wires?

You need to use a wire to connect the 2 rails. Right where is the bigger separation.

the power rails are separated in the middle of the breadboard. bridge them with jumper wires

source: Stack Exchange

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

sort: votes


text:
automated parking system (sir sensor+ stepper motor)
my project about automated system I am using stepper motor to open and close the gate
I want my code be like when the gate opened it stays 5 seconds
then check the sensor, if there is a motion the gate should not close and stay open, when there is no motion the gate should close
if the gate is closing and there is a motion, motion should interrupt closing the gate and reopening the gate
I am using Arduino uno
the code is :
#include <RH_ASK.h>//include radioHead ASK library
#include <SPI.h> // include dependant SPI libray
#include <Stepper.h> // Include the Arduino Stepper.h library:
// Define number of steps per rotation:

RH_ASK rf_driver; // create ASK object
int ledon = 13;
int ledoff = 5;
int sensor = 3;

const int stepsPerRevolution = 2048;// Define number of steps per rotation:

// Wiring:
// Pin 8 to IN1 on the ULN2003 driver
// Pin 9 to IN2 on the ULN2003 driver
// Pin 10 to IN3 on the ULN2003 driver
// Pin 11 to IN4 on the ULN2003 driver
// Create stepper object called 'myStepper', note the pin order:
Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {

  rf_driver.init(); //initialize ASK object

  // Begin Serial communication at a baud rate of 9600:
  Serial.begin(9600);

  // Set the speed to 5 rpm:
  myStepper.setSpeed(5);
  pinMode(ledon, OUTPUT);
  pinMode(ledoff, OUTPUT);

}

void loop() {

  //set buffer to size of expected message
  //uint8_t buf[8];
  // uint8_t buflen =sizeof(buf);

  //check if recevied packet is correct size
  //  if (rf_driver.recv(buf,&buflen))
  //{
  // int i;
  // message received with valid checksum
  // Serial.print("id: ");
  // Serial.println((char*)buf);
  // String userid =(char*)buf;
  // Serial.println(userid);

  // }

  //delay(5000);

  // uint8_t buf2[8];
  // uint8_t buflen2 = sizeof(buf2);

  // if (rf_driver.recv(buf,&buflen))

  // {

  //  int i;
  // message received with valid checksum
  // Serial.print("password: ");
  // Serial.println((char*)buf);
  // String password = (char*)buf;
  //  Serial.println(password);

  // }
  // delay(5000);

  String pass = "1234";
  String id = "A00036757";

  if (pass == "1234" ) {
    Serial.print("car exists");
    digitalWrite(ledon, HIGH);
    delay(300);
    myStepper.step(stepsPerRevolution / 3); //clockwise -OPEN GATE
    delay(10000);

    //if(digitalRead(sensor) == HIGH){
    delay(500);
  }

  if (digitalRead(sensor) == LOW) {

    digitalWrite(ledon, LOW);
    delay(300);

    digitalWrite(ledoff, HIGH);
    delay(300);
    myStepper.step(-stepsPerRevolution / 3); // CLOSE AFTER 5s COUNTERCLOCKWISE -  close gate
    digitalWrite(ledoff, LOW);
  }
  else {
    Serial.print("NO CAR");
  }

When you use delay(), your code stops and dont check anything at all until the delay is over, if you want to check for sensors during a timer, you have to use millis()
There is a lot of documentation and tutorials you can find to replace delay with millis when you know what you are searching for

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


text:
Adding an Arduino variant into ~/sketchbook and using it from a Makefile
I have a pins_arduino.h file for a given Arduino variant, installed in ~/sketchbook/hardware/attiny/variants/tiny14/pins_arduino.h. The IDE has no problem picking it up if I set the right board type. However, if I use a Makefile like this:
BOARDS_TXT      = $(HOME)/sketchbook/hardware/attiny/boards-cli.txt
BOARD_TAG       = attiny44-8

include /usr/share/arduino/Arduino.mk

then running make fails to compile it because of a missing pins_arduino.h. Moving the tiny14 directory to /usr/share/arduino/hardware/arduino/variants  fixes the problem, but I don't want to pollute my system directory (and also, it sounds fragile if I ever remove/replace my Arduino software distribution).
How do I get the CLI Make toolchain to pick up my pins_arduino.h file from my ~/sketchbook?

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


text:
Powering multiple servos on external battery
I am working on a project with my school's 3D Printing Club where we are making a humanoid robot and I am attempting to wire the arm at the moment, and program the hands to translate text to sign language. The portion of the arm I am currently working with uses six TowerPro 5010 servos, one for each finger, and another for the wrist, and I am controlling it with an Arduino Uno. I have a 9v wall plug that I am powering the Arduino with, and a 4xAA battery pack (wired in series for 6v, last measured at 5.7) that I would like to use for the servos.
Initially, I wired the servo ground pins to the Arduino GND output, and the servo power pins to the battery pack's 6v output, I connected the ground on the battery to the ground on the Arduino, and I attached the servo motors to their IO pins. This approach worked perfectly for two servos, barely for three, and not at all for four. Even with most of the motors staying still (I was only moving one at a time with three and four servos, but I can move two simultaneously no problem with nothing else connected). Not sure how to describe the load on them quantitatively, but they are pulling on fishing line that has a good deal of resistance, but nothing excessive, or near their limits.
I have been googling around for hours, and I found some tutorials where a similar battery was powering eight servos at a time, and so I am unsure why mine was cutting out so soon.
I tried to reduce the load of the servos, but nothing I tried worked. At one point I tried wiring the servos on a shift register to only power the ones I needed, but then I realized this was a dumb idea because my shift register would never be able to output enough current to power even one servo. I have some 5v voltage regulators, but I don't think they will help since the servo takes from 4v to 6v, and I looked through all my transistors, but they are all designed for very small currents. I have a relay which should be able to switch that voltage that voltage easily, but only one of them. If possible I would like to try and do this without purchasing any additional components such as motor controllers or specialized batteries, but I understand that if I need to I need to.
If anyone has any advice on how to proceed I would greatly appreciate it. Thanks.

If you dont mind to use a bit of space for a dedicated board that controls your servo and power them, I would suggest to use http://www.adafruit.com/product/815 which is very good.
Your issue might become a power draining where the batteries cant keep up to give enough amper to use 3 or 4 servos at the same time.
I am not sure what kind of batteries you are using, probably not rechargeable ones but I would suggest to get an ampermeter to get the real draining on your circuit.
After that you will understand a bit better what is going on and why this issue is happening on your configuration.
I cant find the power consummation of this servo so I Cant give much more information.

I have a multimeter, but measuring current through a servo is difficult because it is non constant. Also I fear the autorange feature on my multimeter may be making it too slow to react to the changes. Do you have any advice on measuring this?

Also the batteries are four standard alkaline AAs wired in series.

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


text:
Is there any way to download a sketch from an Arduino?
I made a sketch, but then I lost it. However, I uploaded it to the Arduino before losing it. Is there any way I can get it back?

http://electronics.stackexchange.com/questions/28211/backup-avr-with-avrdude but as others say, this only spits out .hex files, not the originating C source.

Cross site dupe: http://reverseengineering.stackexchange.com/q/125/189

It should be possible as long as the security bit isn't set. This question was asked on EE a while back.
Is it possible to extract code from an arduino board?
But you won't get the Arduino code you wrote back. The code is compiled into assembly and you'll have to convert that back to C yourself.

Reading back the raw hex:  http://forum.arduino.cc/index.php?topic=6150.0  and Automatic Disassembly:  http://forum.arduino.cc/index.php/topic,46843.0.html

This answer doesn't directly answer the question, but still will result in the same end result.
The Arduino IDE uses temporary directories to store build files, including the original sketch as well as the HEX and intermediate files.
On a Mac, these are in /var/folders by default, and on a Windows machine they are in …\Local Settings\Temp\ (which depending on the version of Windows could be in several places).
I've found that especially in Windows, these build files don't get deleted when you close the sketch or IDE, so they may exist on your machine for far longer than you would think.
Also, by default, Crashplan, Backblaze and Time Machine back-up these locations, so even if they have been deleted, they may still be in a backup.
The advantage here is that you will recover C code rather than ASM.

This is the best solution IMHO. Very creative, too...

You may find this in /tmp/ directories on Linux (and even Mac). c.f. https://www.arduino.cc/en/Hacking/BuildProcess

Comment echo from the accepted answer:  Reading back the raw hex:  http://forum.arduino.cc/index.php?topic=6150.0  and Automatic Disassembly:  http://forum.arduino.cc/index.php/topic,46843.0.html

I assumed you checked the trash. I use Linux mint and my last program was here: "/tmp/arduino_build_699749/preproc/ctags_target_for_gcc_minus_e.cpp" That was the original source file I compiled a few days back. Note I have not compiled anything since. I found the original /tmp/arduino_build_699749/sketch/myfile.ino.ccp. This probably will not help you but it probably help others. Remember go after it before compiling anything else.

You can download the hex dump of the file, but there is no easy way to get all the C++ code and comments. If you can understand assembly, you could recreate the program, but that would take a while. There are dissasemblers available for some devices, i don't know about arduino.

There are no disassemblers for arduino, because it is not a MCU type. There are multiple ATmega disassemblers (google atmega disassembler).

If you have the arduino envitonment, you already have avr-objdump as it comes with avr-gcc.

Reading back the raw hex:  http://forum.arduino.cc/index.php?topic=6150.0  and Automatic Disassembly:  http://forum.arduino.cc/index.php/topic,46843.0.html

I think there is another way to do this, without extracting the code from the Arduino board. Remenber the date you create the sketch, and look for it in  C:\Users\User\AppData\Local\Temp\
(For example : C:\Users\User\AppData\Local\Temp\untitled4390292704786567977.tmp\sketch_jan19a ). You could find your unsaved code unless it was deleted by some "freeing space program".
Good luck!

Unless your objective is to simply copy the identical code to another device, the simple answer is: no
As has been pointed out in other answers, you can turn the hex code on the device back into assembler code.
For example (once you have copied the code from the device back onto your disk):
avr-objdump -j .sec1 -d -m avr5 yourFileHere.hex

Run on one of the bootloader files I get these results (in part):
00007e00 <.sec1>:
    7e00:       11 24           eor     r1, r1
    7e02:       84 b7           in      r24, 0x34       ; 52
    7e04:       14 be           out     0x34, r1        ; 52
    7e06:       81 ff           sbrs    r24, 1
    7e08:       f0 d0           rcall   .+480           ;  0x7fea
    7e0a:       85 e0           ldi     r24, 0x05       ; 5
    7e0c:       80 93 81 00     sts     0x0081, r24
    7e10:       82 e0           ldi     r24, 0x02       ; 2
    7e12:       80 93 c0 00     sts     0x00C0, r24
    7e16:       88 e1           ldi     r24, 0x18       ; 24
    7e18:       80 93 c1 00     sts     0x00C1, r24
    7e1c:       86 e0           ldi     r24, 0x06       ; 6
    7e1e:       80 93 c2 00     sts     0x00C2, r24
    7e22:       80 e1           ldi     r24, 0x10       ; 16
    7e24:       80 93 c4 00     sts     0x00C4, r24
    7e28:       8e e0           ldi     r24, 0x0E       ; 14
    7e2a:       c9 d0           rcall   .+402           ;  0x7fbe
    7e2c:       25 9a           sbi     0x04, 5 ; 4

As you can see, not particularly helpful for reproducing what your sketch did. There are likely to be one of two scenarios:

Your sketch was short, in which case you might, after weeks of work, turn the assembler code back into C
Your sketch was long, in which case it would be virtually impossible to turn it back into C

In the "short sketch" case, you are better off just rewriting from scratch. That would be faster, almost certainly. In the "long sketch" case - it just isn't worth it. None of the variable names are preserved, and the way the compiler optimizes code, even the structure of the code would be hard to determine.

Download:
avrdude \
    -c <programmer type> \
    -P <connection port> \
    -b <override RS-232 baudrate> \
    -p <partno, AVR device> \
    -U <memtype>:r:file_name[:format]

Upload:
Use w (write) instead of r (read) for the -U option.
More details at manual - avrdude Option-Descriptions.

Example:
Download UNO v3 (ATmega328) flash ROM (bootloader) given port /dev/ttyACM0 as Intel HEX:
avrdude -c arduino -P /dev/ttyACM0 -b 115200 -p m328p -U flash:r:SaveFlash.hex:i

If used directly from from the arduino IDE archive also add:
-C path-to/arduino-V/hardware/tools/avr/etc/avrdude.conf

Another approach might be to treat the program onboard the Arduino as a black-box exercise. That is, run the program and take careful notes of what happens (via Serial Monitor or whatever). If, in fact there is any output that you can observe, make it a task to create your own new code to emulate what the program DOES. This won't be productive unless the original programmer liberally included Serial.print() statements throughout the code, something I STRONGLY RECOMMEND as a programming habit to develop. Doing so, facilitates just the exercise I am suggesting. (Ask me why I developed that habit for everything I have coded for the past 30 years.)
Unfortunately, most people sprinkle a few comments here and there, which is helpful 5 years later if you have the source code. Personally, I comment EVERY LINE of source code. But comments in the source don't help later in this sort of situation, as the compiler doesn't put them in the machine code it generates. (Perhaps that might be a valuable option for the compiler. Yes, it takes bytes, but how valuable might it be years later for an important project?)
My two cents worth, which probably is worth the price the reader of this post paid to see it!


text:
Can I get a Datetime object from a unix timestamp?
Is there a way to get a DateTime object from a unix timestamp and hour offset? I want to be able to print a formatted string, for example Wed Apr 02 17:15:06 2014.
I have:

A unix timestamp: 1396451852.
An offset from my hour zone, +1 hour.

Note: I get the timestamp from an internet service and want to make the conversion in the Arduino.

To clarify: You have a unix time-stamp on your arduino and you want to make the conversion there? Could the supplier of the timestamp instead provide the formatted string?

Yes! i get this unix time-stamp from internet.

The seconds since (UNIX) epoch relies on a database.

New editions of the database and code are published as changes warrant, usually several times per year.

Your options can:

Reduce the timezone database to the timezone you are actually interested in;
Don't forget about daylight savings time for you specific timezone;
The leap years are well known too and reasonably easy to program;
The leap seconds are decided upon usually only couple months before they are introduced and therefore cannot be accounted for in an algorithm.

Conclusion

So can you convert epoch to a time/date format? Yes.
Will it be accurate? It'll drift away over time (months or years)

Advise
If you retrieve epoch from an Internet service, why not use (another?) webserver that has the full timezone database available to convert it to accurate date/time, or 'synchronize' against every once in a while?

+1 For letting me know that leap seconds exist AND for the great answer.

The Arduino Time Library looks like it can do it. Or have a look at the strftime() function from unix and unix-oid environments. There is source to strftime() here. It's pretty large but you can probably cut it down considerably to just the format parts you need.


text:
Is it bad to leave my Arduino UNO on uninterruped?
I'm developing a project (Data logger) that requires that the Arduino remains on for several weeks.
Is it okay to leave it on for about 6 weeks? Do I need to frequently reset it?

Should be just fine. Just like you can keep your PC on for 6 weeks (webservers are on 24/7). If your code is correct it shouldn't need any resets (watchdog timers will enable you to detect if the code is hanging).

This question has a very broad answer. As it depends upon your implementation of both hardware and software.
In very short -
That all depends on your code. The hardware should be able to be left on indefinitely, assuming it is all within spec's. Assuming that, then the biggest concern is the code running on it. Where largest problem of concern is running out of resources. Such as memory. If your code as a memory leak then it will be a problem. Or if there is a bug in the code that can cause it to get stuck. The later can be addressed by employing the WatchDog, which will reset (loose all data) if the code gets unexpectedly stuck.


text:
Selecting a MOSFET Shield
Im building an electrical system for my EBike.  My bike has 2 power sources, one is the 48 volt battery, the other is a 12 power converter coming off the battery pack.  I need an arduino shield that has 4 switching channels.  2 that can take in the 48 volt and switch it on and off, and two that can take in the 12 volt and switch it on and off.  Something that can take the 12 volt to power the arduino uno would be nice but I can find a chip to do that if necessary.
Since these are lights, normally off would be more more efficient but with the power consumption we are talking about, i can probably run the battery all day to the point of dry and the fets eat all of 50 feet worth of power staying closed.
Does anyone know of anything like that?  I found several shields out there like this but all of them seem to be setup to take 1 voltage input and switch it between the 4 or 6 fets on the board, not different voltages per fet and since I'm a programmer, not an EE so I have trouble reading the schematics.
Because my grounds have to be tied, its easier to switch the positive on and off than the negative.

You can make your own. Buy a protoshield and 4 fets (and a few resistors).
You can also use the shield you linked to, by not using the + terminals on the board. Just connect the + of the lights directly to the battery and only the - of the light to the shield.
The Uno can be powered by up-to 20V, so you can connect it directly to the battery.


text:
Saving data in a globally declared float array
I'm trying to send 60 float values via serial. Numbers are provided by an accelerometer and saved in a 240 bytes-long array. The array is sent to a function and these values are then copied in a structure.
The problem
The content of the array is still correct when the function is called. Then, when I copy it in the structure, something wrong happens and data are modified after the 26th float.
Where does the modification of an array of floats take place?
void sendBuffAcc(float a[])
{
  int stepCont = 1;

  // Prints the content of the globally defined array buffXAccToSend
  Serial.println();
  for (int i=0;i<sizeBuffAcc;i++)
  {
    Serial.print("val: ");
    Serial.print(i);
    Serial.print("    ");
    Serial.println(buffXAccToSend[i]);
  }
  Serial.println();

  MyShortCommand * pMyCmdShort = (MyShortCommand *)(&bufferAcc[sizeof(MyControlHdr)]);

  for (int i=0;i<sizeBuffAcc;i++)
  {
    Serial.print("val: ");
    Serial.print(i);
    Serial.print("| Global Array:");
    Serial.println(buffXAccToSend[i]);

    numFilterValuesToSend++;

    pMyCmdShort->cmd = accValuesID;
    pMyCmdShort->param1 = a[i];
    pMyCmdShort->param2 = 0;
    pMyCmdShort->param3 = 0;
    pMyCmdShort->param4 = 0;

    Serial.print("|   Param: ");
    Serial.print(pMyCmdShort->param1);
    Serial.print("|   Array:");
    Serial.println(a[i]);

    // Move the pointer to save data in next positions
    pMyCmdShort++;
  }
  stepCont++;
 }
 storeAccData = false;
 contBuffAcc=1;
}

First, the content of the global array buffXAccToSend is printed via serial, then the i-th elements of a[i] and the value assigned to the pMyCmdShort->param1. This is the output:
val: 0    -0.00
val: 1    -0.00
val: 2    0.01
val: 3    -0.01
val: 4    0.04
val: 5    0.00
val: 6    0.01
val: 7    0.03
val: 8    0.01
val: 9    -0.00
val: 10    0.00
val: 11    -0.01
val: 12    -0.00
val: 13    0.01
val: 14    -0.02
val: 15    0.03
val: 16    0.00
val: 17    0.02
val: 18    -0.01
val: 19    0.00
val: 20    0.00
val: 21    -0.00
val: 22    -0.01
val: 23    -0.01
val: 24    0.01
val: 25    0.01
val: 26    -0.00
val: 27    0.03
val: 28    -0.01
val: 29    -0.00
val: 30    0.04
val: 31    -0.01
val: 32    0.01

val: 0| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 1| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 2| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 3| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 4| Global Array: 0.02|  Param: 0.02|  Array: 0.02
val: 5| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 6| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 7| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 8| Global Array: 0.04|  Param: 0.04|  Array: 0.04
val: 9| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 10| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 11| Global Array: -0.00|  Param: -0.00|  Array: -0.00
val: 12| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 13| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 14| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 15| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 16| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 17| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 18| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 19| Global Array: 0.03|  Param: 0.03|  Array: 0.03
val: 20| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 21| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 22| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 23| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 24| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 25| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 26| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 27| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 28| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 29| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 30| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 31| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 32| Global Array: 0.00|  Param: 0.00|  Array: 0.00

This is the output of avr-size:
   text    data     bss     dec     hex
  55828    3906    2978   62712    f4f8

Is it a memory related problem?

What does avr-size say about the final executable?

@IgnacioVazquez-Abrams Please see the output of the command

Are you doing any dynamic memory allocations? can you post the full code?

Please post a Minimal, Complete, and Verifiable example. Not seeing the data declarations, nor the value of sizeBuffAcc it is impossible to tell what the issue is.

The ATmega328P has 2kiB of SRAM. Your program uses almost 3kiB. Move strings and constant values into flash.

Thanks for the suggestion but I'm using the Mega 2560 which has 8KB of SRAM.

I will modify the sketch with PROGMEM as you suggested.


text:
arduino program got error expected //primary-expression before ')' token error: //expected ';' before '}' token E
#include "pulse-sensor-arduino.h"
#include "Arduino.h"
#define PulseSensorbegin

int pulsePin = 0;
int blinkPin = 13;
int fadePin = 5;
int fadeRate = 0;
volatile int BPM;
volatile int Signal;
volatile int IBI = 600;

volatile boolean QS = false;

void setup(){

  pinMode(blinkPin,OUTPUT);
  pinMode(fadePin,OUTPUT);
  Serial.begin(115200);

  PulseSensorbegin();

}

void loop() {

   sendDataToProcessing('S', Signal);
   if (QS == true)
   {
       fadeRate = 255;
       sendDataToProcessing('B',BPM);
       sendDataToProcessing('Q',IBI);
       QS = false;
   }

   ledFadeToBeat();

   delay(5000);
}

void ledFadeToBeat(){

    fadeRate -= 15;
    fadeRate = constrain(fadeRate,0,255);
    analogWrite(fadePin,fadeRate);
  }

void sendDataToProcessing(char symbol, int data ){

    Serial.print(symbol);
    Serial.println(data);
  }

/// my  ccp program
#include "pulse-sensor-arduino.h"

volatile int rate[10];
volatile unsigned long sampleCounter = 0;
volatile unsigned long lastBeatTime = 0;
volatile int P =512;
volatile int T = 512;
volatile int thresh = 512;
volatile int amp = 100;
volatile boolean firstBeat = true;
volatile boolean secondBeat = false;
volatile boolean Pulse = false;
volatile int pulsePin;

volatile int PulseSensor::IBI = 600;
volatile int PulseSensor::BPM;
volatile int PulseSensor::Signal;
volatile boolean PulseSensor::QS = false;
void PulseSensor::begin(int pPin)
{
  pinMode(pulsePin, INPUT);
  pulsePin = pPin;

  TCCR1A = 0x00;
  TCCR1B = 0x0C;
  OCR1A = 0x7C;
  TIMSK1 = 0x02;
  sei();
}

ISR(TIMER1_COMPA_vect)

{
  cli();
  PulseSensor::Signal = analogRead(pulsePin);
  sampleCounter += 2;
  int N = sampleCounter - lastBeatTime;

  if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3)
{
    if (PulseSensor::Signal < T){
      T = PulseSensor::Signal;
    }
  }

  if(PulseSensor::Signal > thresh && PulseSensor::Signal > P)
{
    P = PulseSensor::Signal;
  }

  if (N > 250){
    if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
    {
      Pulse = true;
      PulseSensor::IBI = sampleCounter - lastBeatTime;
      lastBeatTime = sampleCounter;

      if(secondBeat){
        secondBeat = false;
        for(int i=0; i<=9; i++){
          rate[i] = PulseSensor::IBI;
        }
      }

      if(firstBeat){
        firstBeat = false;
        secondBeat = true;
        sei();
        return;
      }

      word runningTotal = 0;

      for(int i=0; i<=8; i++){
        rate[i] = rate[i+1];
        runningTotal += rate[i];
      }

      rate[9] = PulseSensor::IBI;
      runningTotal += rate[9];
      runningTotal /= 10;
      PulseSensor::BPM = 60000/runningTotal;
      PulseSensor::QS = true;
    }
  }

  if (PulseSensor::Signal < thresh && Pulse == true){
    Pulse = false;
    amp = P - T;
    thresh = amp/2 + T;
    P = thresh;
    T = thresh;
  }

  if (N > 2500){
    thresh = 512;
    P = 512;
    T = 512;
    lastBeatTime = sampleCounter;
    firstBeat = true;
    secondBeat = false;
  }

  sei();
}

//my header programing
#ifndef PULSE_SENSOR_ARDUINO_H
#define PULSE_SENSOR_ARDUINO_H

#include "Arduino.h"

class PulseSensor
{
public:
  static void begin(int pulsePin);

  static volatile int BPM;
  static volatile int Signal;
  static volatile int IBI;
  static volatile boolean QS;
};

#endif

"Data dump" is a bad way to ask questions. Telling us where you got the error message and what you have done to try to fix it would be a good start.

i got the error on PulseSensorbegin(); in the void setup()
i got an error message like this ///expected primary-expression before ')' token Error compiling

I noted that "ifndef" should be "#ifndef" then realised that the editor "eats" the "#" symbol and that it IS in your  code.

Presumably PulseSensorbegin() is actually meant to be PulseSensor::begin()?

yes i am calling the function of void PulseSensor::begin(int pPin) @PeterR.Bloomfield

@KarthiKeyan The line in setup() which says PulseSensorbegin() isn't doing that though. It's probably actually causing your error because it's missing the scope operator (::).

anyone to help out this. Arduino program that will flash an led two times ( with a delay in between). the led to flash only when a dedicated push button switch is pressed. if the button is not pressed, the led should be ON

At the top of your program you have this:
#define PulseSensorbegin

which defines PulseSensorbegin as nothing
Then later you have:
PulseSensorbegin();

which the pre-processor turns into:
();

which is where the error is occurring.


text:
Attiny85 and 433Mhz RF
I have this cheap RF link that I had working with the Arduni UNO, but I wanted to make it smaller and ATTiny85 should do the trick. The RF module is connected (data pin) to PB3 on the ATTiny.
But I am having some problems. It does not work, and I don't know why. My code:
#include <SoftwareSerial.h>

// PINS
#define SERIAL_TX PB3

SoftwareSerial mySerial(-1, SERIAL_TX);

void setup() {
  pinMode(SERIAL_TX, OUTPUT);
  mySerial.begin( 1200 );
}

void loop() {

  mySerial.write(0xAA);
  mySerial.write(0xAA);
  mySerial.write(0xAA);

  delay(1000);
}

The code you presented does not fit for working with the RF 433Mhz. I'm not sure what you think this code should do, but this is not the way to go with a 433Mhz transmitter.
I would suggest using a dedicated library for transmitting information using the 433. There are many libraries out there for doing that; two popular libraries would be the ManchesterRF and the VirtualWire, both includes code samples.
For example, sending data with ManchesterRF:
#include "ManchesterRF.h" //https://github.com/cano64/ManchesterRF

#define TX_PIN 3 //any pin can transmit
#define LED_PIN 13

ManchesterRF rf(MAN_4800); //link speed, try also MAN_300, MAN_600, MAN_1200, MAN_2400, MAN_4800, MAN_9600, MAN_19200, MAN_38400

uint8_t data = 0;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  rf.TXInit(TX_PIN);
}

void loop() {

  rf.transmitByte(++data, data*data);
  digitalWrite(LED_PIN, digitalRead(LED_PIN)); //blink the LED on receive
  delay(100);
}

In addition, there are many other blogs around going step-by-step how to use 433Mhz Tx/Rx with ATtiny85, google is your friend :)

Hi Omer, thanks for your reply! I tried the Manchester, but it outputs error when I try to compile it: "Manchester library doesnt support your microcontroller"

see this project as an example for working with Manchester and ATTiny85: http://m.instructables.com/id/Attiny85-RF-Transmitter-to-Arduino-Uno-Receiver-Ma/

I've just deployed the code on my UNO (I was using it as a programmer for the ATTiny85) and on the UNO i works like a charm. I've my own dataprotocol, so the problem here is getting the ATTiny to do serial with the SoftwareSerial on PB3.

In that case, I suggest you edit your question strictly to SoftwareSerial, or ask another question. My answer apply to 433Mhz and ATtiny which I've done many times before.


text:
Are there any reasons to pick Nano over Micro?
Nano is from 2008, and micro from 2012. Micro seems better on every parameter, in particular in having a better (I think) microcontroller, ATMega32u4, over ATMega328P.
However, all the shops I've checked out, both local and online, sell the Nano, and only some sell Micro. And Nano is always more expensive than Micro. E.g. at RS-Online 26GBP for Nano (link) and 16GBP for Micro (link).
Why do many shops only sell the inferior product?
Why is the older and less capable Nano more expensive?
Why would anyone buy the Nano over the Micro?

And why can I tag my question with "arduino-nano", but not with "arduino-micro"?

To create a tag, you'll need a reputation of at least 150.

Actually I know, but thanks :) What I meant is, obviously people on this site are asking questions more questions about Nano than about Micro. Obviously it could be because it has been around for longer, but still surprising to me, when Micro seems better in every aspect, and cheaper too.

It seems like there are lots of Nano clones, eg 6euros at DX.com. And I haven't seen any Micro clones. So if using clones, Nano is in fact much cheaper.

Look on ePrey. There are plenty of 5V Micro clones, cheaper than Nano clones. In fact, you have to go through about 100 Micro clones until you find a Nano clone (if you sort by lowest price), and maybe 80 5 volt Micros until you find a 3.3 volt Micro...

The main difference between the ATmega32u4 and the ATmega328P is that the 32u4 has onboard USB. When ATmega328P are used in an Arduino they are often coupled with an FTDI USB to serial chip. The FTDI chip is about $5 so this may be where the extra cost comes in.
Having the USB chip separate is actually not a bad thing:

The Atmega328P consumes less power than the ATmega32u4
FTDI chips are common, so the drivers are on most computers, whereas the 32u4 requires an .inf file to be loaded on Windows.
The FTDI chip uses the FTDI vendor and product ID and thus can be used in large-quantity commercial projects whereas the ATmega32u4 would require purchase of a vendor id and product id from the USB group. (My conclusion after reading around the net a bit, please correct if wrong).

I'd buy the NANO and STEER CLEAR of the micro with that 32u4 chip. The good ol' 328p chip also has a FTDI chip to handle USB to serial while the other chip handles it on its own. The problem is that the Micro's bootloader ONLY allows trying to program it with USB and requires a special driver. With Linux, only a few select versions have the needed driver. If your Linux version doesn't have the driver, you're out of luck. In that case, take it back or donate it to a hackerspace. You will NEVER make it work.
I was at the arduino.cc site about this and tried everything only to get increasingly annoyed about that lemon of a card. You know it's time to give up when you get flamed.

Nice to know about the Linux problems. I have programmed both Micro and Nano from Ubuntu without problems, but maybe I've been lucky this far.

However, if you need a 3 Volt device then you are obliged to go for a Micro, rather than a Nano.

It depends on what's your focus on. From pure microcontroller view, the 328P compared to the 32u4

is 4MHz faster
has two Touch Channels more
has picoPower technology
has an RTC
has a lower minimum supply voltage

If one or more of these features are essential for your project, the Nano may be the better choice.
Regarding the price:
I'm not sure if it can have such a high influence, but there may have been a technology shrink. That's why a modern 32bit micro is cheaper than an old-fashioned 8 or 16bit micro, at least in B2B pricing.

According to http://arduino.cc/en/Products.Compare, they are both 16MHz.

I'm not sure I understand what you mean by "technology shrink", could you explain?

The Arduino boards may both have a 16MHz oscillator populated, however the AtMega328P itself can be driven at up to 20MHz, according to Atmel's product comparison page. "Technology shrink" means a change in the production process to smaller silicon structures. For example, the Freescale S12 (16bit CPU) was built using 180nm process,  Renesas uses a 40nm process for the new RH850 (32bit CPU). Smaller structure = less silicon (plus other benefits). That's one reason why the RH850 is cheaper than the S12, but has much more features.


text:
SoftwareSerial Struggles
Just trying to understand and use the SoftwareSerial
I want to connect a WiFi Module (ESP8266)
If I send an AT command to the module I would like to print a response on my pc screen in the serial monitor
Some example code it tried
   SoftwareSerial dbgSerial(10, 11); // RX, TX
   void setup()
   {
     // Open serial communications and wait for port to open:
     Serial.begin(57600);
     Serial.setTimeout(5000);
     dbgSerial.begin(9600); //can't be faster than 19200 for softserial
     dbgSerial.println("ESP8266 Demo");
     //test if the module is ready
     Serial.println("AT+RST");
     delay(1000);
     if(Serial.find("ready"))
     {
       dbgSerial.println("Module is ready");

I would like to receive ready in the serial

Looks like you are swapping the use of Serial and dbgSerial. I think you mean to use Serial to print to the computer and dbgSerial to communicate with your module. Serial.println should display the message in the terminal on your computer.


text:
Is it possible to use ESP8266 modules interchangeably?
I discovered that there are multiple types & versions of ESP8266 modules.
I'm wondering:

Build my application around one type (eg ESP-03) and in future swap the module with another (ESP-07), continuing to use the same library and code?

Given the lack of information online, I couldn't find an answer for this online.

yes they are interchangeable since they all use the same chip (esp 8266). However the pin outs of the different modules can (and will be) laid out different. So you have to watch out that your wires are connected to the correct pads on the module.
Also mind that different esp8266 modules can be (stock) loaded with different firmware. If you are using the AT firmware in your current arduino project it can be necessary to flash your new esp8266 module with the same firmware. If you are not sure how to do this you might have a look to the esp8266 forum

Hi @kaspertaeymans, thanks for the answer. Can you please clarify one thing: If I want to connect an esp8266 to an Arduino to have the Arduino communicate with the home wifi (and the internet through it), do I need to have a special firmware on Arduino? Second Q: Is this hard to achieve? I'm not interesting in hacking the ESP to use it on its own with Lua code or anything. Also: What's the name of what I want to do? Is it "AT mode"? Thanks very much!

hi, I suggest reading some tutorials about arduino programming. If you encounter problems you'll always can post an new question to SE.

yup, started doing it and it is fantastic! learned a lot. thanks!

Well...
Yes, but... mostly only if you are using the simple serial lines(rx and tx) to communicate with it and only using the AT flash image.
Just as a for-instance:
The ESP8266-01 and ESP8266-02 have three and two IO pins (respectively) that are reprogrammable.
The ESP8266-03 has seven IO pins.
The others have different amounts of pins found on this page:
http://hackerspace.pbworks.com/w/page/88183850/ESP8266
So if the program you use to flash the module uses more pins then you have to use the module that has the proper amount of IO pins or rewrite the flash image.
Instructions for compiling a toolchain to write and flash your own flash images to the ESP8266-XX module are found on this page:
https://github.com/esp8266/esp8266-wiki/wiki/Hardware_versions

thanks @isme! my main motive is to use the esp8266 to act as a "bridge", to send and receive data to/from Arduino.


text:
Most power efficient way to constantly save 2 kilobytes of data per second
I would like to constantly save data coming from sensors (for an activity tracker) while consuming as less battery as possible (I'd like to have a 4/5 days autonomy on a 3000 mAh battery) but I can't find the best way to save about 2 kBytes/s on a memory large enough to contain several days of data.
Sensors would be read at a rate of 20 times per second and produce about 100 bytes each time.
What options do I have in order to:

store such an amount of data (hardware)?
ensure the system can work properly with required autonomy?

What options have you explored? Also, 2KB/s is a lot of data. Are you sure all of it is essential and there are no redundancies?

You need to clarify your needs further: what Arduino board do you use, what kinds of sensors are there, WHERETO do you need to save these 2KB/s? It is important to understand that no Arduino alone will have enough memory to store 2KB/s during days.

@jfp You could use a SD card...

Yes I know, that was actually the idea of my comment to ask that question! But is this an acceptable option for the OP, or would he want direct (e.g. wireless) transmission of data to some other device, e.g. a PC?

@AsheeshR Well, I calculated that all the data coming 20 times per second would be about that (2KB/s), well yes, it is, because since It will be some pretty hard to do activity recognition, the Arduino probably won't have such computation power, so I need to do that later, on a computer.

@jfpoilpret Right now I don't know exactly, because I need enough power to constantly read the data coming from the sensors at an high rate but I would to have a very low power consumption. Yes I know, that why I am asking your help... ;)

@AnnonomusPerson I thought to this option but I am wondering if the write speed will be high enough and we told me that it takes a lot of power.

An important question is related to your sensors, about which you mentioned nothing interesting so far: do they provide these 2KB/s in a continuous way of they act only once per second and produce 2KB everytime (or something in between)? That aspect is highly important in order to find out: the consumption of your circuit, the possibilities to use a low-power mode of the Arduino...

SD card is probably a good option (the only one?) for your storage needs; however, current consumption during write operations is totally dependent on each brand and model.

SD cards are all over the place with current consumption. 5mA whilst writing is the lowest I have seen, 100mA the highest, but the spec allows for 200mA. Typical is maybe 30-50mA. They use quite a lot of power when using the SPI interface.

I think it's critical to answer the question hinted at by jfpoilpret, which is:
What is the data you're storing? Is there any way to consume just the minimum amount of compute cycles on the Arduino in order to pack this data a bit more compactly. 2kB/s is a fair amount of data for a microcontroller to collect and send to storage.
And yes, for data logging, SD cards are pretty much the best option, if only for the fact that the card can be physically moved off to a computer for proper data analysis.

There are two constraints here, and I think it might back you into a corner. Size and then power.
2Kbyte/s is 2*60*60*24/1024 = 168.75Mbyte/day. This is a lot. The only readily available technology that can be used with a small microprocessor that can store this volume of data is an SD card. There are no serial EEPROM or flash chips this large, and the Arduino, as far as I know, can't deal with the NAND flash used in USB sticks and SD cards.
However, SD cards can be relatively power hungry. They draw between 5mA and 100mA when writing, typically around 30-50mA. The SD spec says the maximum is 200mA. Writing is also quite lengthy as they operate on blocks of data rather than individual cells. I've never done a full analysis of how much power they use, but it is not insignificant and much, much more than serial EEPROM or flash.
So your only choice, if you have to store that much, is to go with SD cards.
I would investigate compressing the data. Even very basic schemes can make a huge difference.

Thank you for your answer ! What do you think about saving the data on a small low power flash memory (like this one : http://www.adafruit.com/products/1564) and then, when this memory is full, saving it on the SD card ? Wouldn't it save power ?

Yes, there is potential to save power. It is much better to write to the SD card in large blocks because even if you change a single byte, it has to update the whole block. How big that block is, I don't recall.

Actually, I think that an Arduino probably can deal with a bare NAND flash (at least if few of the pins are already used, or one is willing to add an external latch for as a demultiplexer), but one would have to consult data sheets to see if the power consumption would be lower than a carefully selected SD card.

This would be possible with a standard SD card.
Capacity
Using some simple calculations, I was able to find that writing at 2kB/s for 5 days would only consume 0.8GB. You could probably get by with a 1 or 2 GB card.
Speed
I found this benchmark, which says it is possible to write SD card data from an Arduino at 192 kB/s, which should be more than enough for your needs.
There are a lot of great tutorials and examples out there for using an SD card with an Arduino. The official documentation is always a good place to start.


text:
What are the steps involved in porting an Arduino library?
I want to use the Adafruit CC3000 and its Arduino libraries on another platform. In this case it's the Arduino pin compatible PSOC4 Pioneer Kit. This is an ARM Cortex M0 based platform.
My question is: How would I go about porting a library like this? What are the steps, key files etc?
One obvious issue is that PSOC Creator does not readily support C++.
One positive might be that the Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU.
NOTE: If you think this question is off topic; please head over to this question on Arduino Meta to voice your opinion on whether questions on Arduino Compatible devices are appropriate for this list.

Are you asking how to port a Lib written in C++ to C?

Not really. Because I've seen that limited C++ support can be made to work in PSOC Creator. It's more the process of library porting I'm interested in. Particularly to an ARM Cortex based Arduino Compatible device.

ahh, Okay well then I am not quite sure how to do that, I thought you just wanted the library in C instead of C++

I did essentially the same thing with getting the Adafruit ST7735 library working in chipKIT. I started a support thread here which can lead you through my process.
I tackled it the same way I do general programming:
1-» Copy over Libraries, get it so your compiler can actually SEE them.
2-» Start trying to compile and then triage errors from the "top level" down:
3-» Look for stlib functions you recognize as should be working and fix those.
4-» Look for AVR specific code and comment those out. I normally also add my initials and a comment: ckck - bitbanging SPI, so I can search for these later.
Repeat 3 and 4 until it works or you quit. :)
Reach out to the forums for your target; they might have been there done that -- or like in my case, you introduce them to something that they want, so they dive in and help.


text:
Which voltage regulator should I use?
A friend and I are working on building a smartwatch on a budget, so it’s a (very) low power project, but we are currently having a problem with the power supplying.
We already chose this board, because of its size and the BLE chip: RFduino BLE SMT
For now on, we are planning to use this battery 500 mAh LiPo battery (approx. 4V at full charge) with this voltage regulator Micrel MIC5209-3.6YS (the board supports 3.6V max.).
But the problem is that the Voltage Regulator will apparently drain by itself too much energy from the battery (by heating), reducing drastically the autonomy.
So we would like to know if you guys can help us, if you can tell us exactly what (type of) regulator would be the best or if we need to find another battery.

Duplicate: http://electronics.stackexchange.com/questions/107827/which-voltage-regulator-to-use

What does this have to do with Arduino?

@sachleen the OP mentioned he is using an Arduino clone, so I guess that's OK for arduino.SE (although I admit this may be borderline)

I don't see any reason to close this question as off-topic. The OP is asking us about dimensioning a battery power supply for an Arduino clone. That's pretty on-topic to me. Just the cross-posting with EE.SE that is not ok.

I've created a meta post to discuss this topic. Please post your opinions in that thread.

IGND which is mentioned on page 4 of the datasheet is apparently proportional to the output current. This accounts for about 2-5% of the total current drawn by the regulator, depending on its load. With the maximum voltage drop of 4 - 3.6 = 400mV, a switching regulator will make no real difference. I think your only option is to find another regulator that has better efficiency.

Hi,
Thank you for your fast answer. I just thought : we can't use a linear regulator because it won't let the current pass through below 3.6V, right ? (the chip works down to 1.9V) So, maybe a switching regulator would be better after all. Perhaps you know a reference of one that would fit our needs ?


text:
Reducing lag between the arduino and a processing sketch on my computer
I'm currently on project #14 of the Arduino project book.
I'm trying to control a processing sketch on my laptop using my Arduino. This is accomplished by using a potentiometer to control the background of an image.
Arduino code:
void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.write(analogRead(A0)/4);
}

Processing:
//imports serial library
import processing.serial.*;
//setups the serial object
Serial myPort;
//creates an object for the image
PImage logo;
//variable to store background color
int bgcolor = 0;

void setup(){
  colorMode(HSB,255);
  logo = loadImage("http://arduino.cc/logo.png");
  size(logo.width,logo.height);
  println("Available serial ports");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
}
//equivalent of arduino's loop function
void draw(){
  if(myPort.available() > 0)
  {
    bgcolor = myPort.read();
    println(bgcolor);
  }

  background(bgcolor,255,255);
  image(logo,0,0);
}

Now, while the code works, and the background color changes as i turn the potentiometer, there is a huge lag between turning the potentiometer and seeing the background change color, and the values from the Arduino/potentiometer change on the processing's serial monitor.
What I've tried:

Changing the speed of Serial communication

I've noticed that when I decrease the speed of Serial communication, e.g. around 100, the delay between turning the potentiometer and seeing it change on my laptop decreases to about 1 second. However, when I decrease the speed of Serial communication even further, e.g. a value of 1, the delay increases again.
On the flip side, at the standard speed of 9600, the delay is huge, roughly 5sec ++ before the changes in the potentiometer show up on the laptop/processing.
Why does decreasing the communication speed (up to a certain point) decrease the time lag, and increasing it increase the time lag? Also, is there anyway I can make it near instantaneous?

You're outputting a reading every single time round the Arduino loop(). It's quite possible that your Processing program isn't running fast enough to keep up with it. Try putting a delay into the loop() in your Arduino code to slow it down; e.g. delay(50).

Hi peter, thanks for the prompt answer, adding a small delay really did solve my problem. Just another small question though, is there any way i can determine the speed of my processing program in the future so as to prevent this from happening again, or does getting a better laptop/processing speed solve the issue? Also, why does entering a communication speed of 250 or 300 mess up the readings from the arduino?( the readings i get are alternate between the reading and zero E.g 147,0,147,0)

You're outputting a reading every time round the Arduino loop(), so it seems likely that your Processing program isn't running fast enough to keep up with it. Try putting a delay into the loop() in your Arduino code to slow it down, e.g.:
void loop(){
    Serial.write(analogRead(A0)/4);
    delay(50);
}

As far as I know, Processing aims to run at a consistent framerate, which you can modify using the frameRate() function. By default, it's 60 frames per second, although it may run slower on older systems (or where you're running an intensive program). You can check how fast it's running by reading the frameRate variable.
Introducing a 50 millisecond delay into the Arduino loop means it will be updating a little under 20 times per second. That means it should be fast enough for user interface purposes, but should also be well within the capabilities of your Processing program.
As far as the baud rate (communication speed) is concerned, adjusting it by arbitrary amounts is likely to have unpredictable results. That's because the hardware will only support specific speeds, and trying to use anything else can result in the data appearing garbled on the other end. The Serial.begin() documentation has some more information about supported baud rates.

As already pointed out, your Arduino is saying too much too fast. Adding delay() will slow it down, but still it keeps yelling at Processing. Ideally, you want Processing to ask for the value when it's convenient, and then receive one answer from your Arduino.
Enter SerialEvent().
As opposed to loop() on your Arduino and draw() in Processing, everything inside serialEvent() only excutes when there is something new in the serial buffer. So instead of Processing asking questions as fast as possible and your Arduino yelling back even faster, they can have a nice, polite (asynchronous) conversation.
Both Processing and Arduino have a serialEvent. This is serialEvent() on the Arduino and this is serialEvent() in Processing. Using serialEvent on both sides, this is what would happen:

Processing sends a character to the serial connection. This could be any character, but if we predetermine one we can filter out any unwanted requests caused by e.g. a noisy signal. For this example, let's send a V every time we want a new reading of your potmeter. After the character is sent, we continue our business as usual. Not waiting around for an answer here!
On the Arduino side nothing is happening, until it receives data in the serial buffer. It checks whether the incoming character is a V, and lucky us, it is. The Arduino reads the potmeter's value once, outputs that value to serial once, and goes back to chilling out, maxing relaxing all cool. Protip: terminate the value with a character (* in our case). This will help you in the next step.
Processing is doing its regular interfacey pixel business when all of a sudden there's a disturbance in the force new data in the serial buffer. It switches to serialEvent(), and starts reading the serial data, until our terminating * is encountered. Knowing for sure this was the last character worth reading, we can now store the incoming value in a variable that stores the Arduino's reading.
That's it. Processing now knows the new sensor value and carries on with whatever we tell it to do. Meanwhile, your Arduino is enjoying the weather or contemplating its existence until there is incoming serial data.

And while you're at it, put a capacitor in parallel with your potmeter. This smooths out little changes in your DAC's input, possibly preventing jittery motion in Processing.

Thank you for this nice (and kinda anthropomorphic) answer!

Actually, asking questions over USB can be a idea.  This is because USB has a lot more latency than a serial port, so asking a question and waiting for a response is a more time consuming operation than it would otherwise be, especially compared to what could be done at high baud rates.  Letting the Arduino run a little faster is fine (though it should not saturate the serial portion of the link); the catch is that the processing sketch should drain the Arduino data as it becomes available, and hold onto the last complete value to use when it needs one.

Your polling loop runs at full speed of your processor,
and writes to the serial port in each round.
This way, you're writing way more often to the serial port than it can handle.
The port writes out data as fast as you configured it, and buffer data that is comming in from your program too fast, to write it out as soon as possible.
It the buffer is full, it just drops new data.
What's important here is that it will keep the order of the values: It is a FIFO buffer, working in First In/First Out order.
What happens is:
The loop fills the port buffer, and keeps it 100% full.
If you turn the potentiometer, the changed value get's written to the end of the buffer, the port works as fast as it can to write out all elements in the buffer, that have still the old value.
And finally the value you are interested in. The most current value we wanted to see immediately was at the end of the FIFO, and first in/ first out also means last in/last out. The opposite of what we want.
The maximum frequency it makes sense to read your data, is the frequency you can write it out, so you should use at least a delay that is long enough to write out the bytes at the current port speed.

As another, independent measure to prevent this kind of delay in general,
 you could additionally set the write buffer of the port to a minimum.
That would cause data to be dropped much earlier, instead of buffering a lot first.
Of course, in many applications that is not what you need; With bad luck, it could work anyway in the beginning, and get unstable in some situations when the timing changes based on things like processor load, and there are only some random data samples that get dropped. A large buffer generally behaves much more deterministic, so do use a large buffer by default.

Right idea, but not quite right on the statement "It the buffer is full, it just drops new data.".  Once the buffer is filled, data is not dropped, rather the writes block until there is space in the outgoing buffer.   This means that the input and output soon end up flowing at the same average rate, but that there's a buffer's worth of latency in between them.

Instead of constantly sending serial data, only send data when the value of the potentiometer has changed over a certain threshold.
int oldValue = 0;
const int threshold = 5;

void setup()
{
  Serial.begin(9600);
  pinMode(A0, INPUT)
}

void loop()
{
  if(oldValue >= analogRead(A0)+threshold || oldValue <= analogRead(A0)-threshold)
  {
    Serial.println(analogRead(A0));
    oldValue = analogRead(A0);
  }
}

That loop() is not filling the output buffer with equal samples, that's good. But it still runs at full speed of the processor, which may be 100 times as fast as it's needed. That means it can still fill the buffer to the limit quickly if the input changes frequently, eg from noise above threshold, or a continuous change in high resolution (which is not the case in the example application here)

Two simple solutions that are guaranteed to work for anyone who is still looking:-

Increase the delay to 50 to 100 milliseconds.
Add this after the Serial.begin(9600) in setup();
Serial.setTimeout(50);

Step two is the most important. It worked for me only after I added the above code. This is not mentioned very often in many other forums that I have looked when I had the exact same problem.

This is somewhat mistaken.  The setTimeout() method applies to input, not output - see the documentation at https://www.arduino.cc/en/Serial/SetTimeout


text:
Can anyone tell me the best books for studying UAV?
It's kind of hard to get full guide from the internet. I just wanna buy a book for UAV guide. I gotta make DIY drones. I'd appreciat it if you recommend good books.

Welcome to Arduino SE! I'm going to close this question because this isn't based on fact, more on opinion. Feel free to edit the question if you can make this more specific. Thanks!

oh. I'm sorry. I made a mistake.
I'm gonna upload more useful information next time.
Thanks ;)

that's fine, everyone gets a question or two closed once in a while. On a side note: Related meta discussion

Not a book, but try the following course from EdX, the online MOOC:
https://www.edx.org/course/tumx/tumx-autonavx-autonomous-navigation-1658

wow. that's the great website.
I appreciate for your help.
have a good day.


text:
AT+CSTT throws an error
I am getting an error on
AT+CSTT="TATA.DOCOMO.INTERNET","",""

What am I missing here?
Code
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.println("Goodnight moon!");
  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
  delay(3000);
  Serial.println("AT+CGATT=1");
  delay(500);
  Serial.println("AT+CGDCONT=1,\"IP\",\"TATA.DOCOMO.INTERNET\"");
  delay(500);
  Serial.println("AT+CDNSCFG=\"4.4.4.4\",\"8.8.8.8\"");
  delay(1000);
  Serial.println("AT+CSTT=\"TATA.DOCOMO.INTERNET\",\"\",\"\"");
  delay(2000);
  Serial.println("AT+CIICR");
  delay(5000);
  Serial.println("AT+CIFSR");
  delay(500);
  Serial.println("AT+CIPSTATUS");
  delay(500);
  Serial.println("AT+CDNSORIP=1");
  delay(500);
  Serial.println("AT+CIPSTART=\"TCP\",\"www.google.com\",\"80\"");
  delay(500);
  Serial.println("AT+CIPSEND");
  delay(500);
  Serial.println("AT");
}

void loop() {
  // run over and over
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Result
AT+CGATT=1

OK
AT+CGDCONT=1,"IP","TATA.DOCOMO.INTERNET"

OK
AT+CDNSCFG="4.4.4.4","8.8.8.8"

OK
AT+CSTT="TATA.DOCOMO.INTERNET","",""

ERROR
AT+CIICR

ERROR
AT+CIFSR

ERROR
AT+CIPSTATUS

OK

STATE: IP IND
AT+CDNSORIP=1

OK
AT+CIPSTART="TCP","www.google.com","80"

ERROR
AT+CIPSEND

ERROR
AT

OK

Edit
SoftwareSerial mySerial(10, 11); // RX, TX

Could you please explain what is mySerial and what circuit it is connected to? Just a part of the code will not provide enough information to analyse your problem.

For others who reach here by search results
Before this applying AT+CSTT command check if the modem is attached to GPRS using the AT+CGATT=? command. If the result is +CGATT: 0 this means the modem is not attached so attach the modem using AT+CGATT=1 command.
This will solve the issue as it was in my case. Even applying AT+CIPCLOSE=0 and AT+CIPSHUT didn't help until I checked that that the result of AT+CGATT=? was returning +CGATT: 0 and applied AT+CGATT=1.

AT+CGATT? , not AT+CGATT=?

Sorry for late Siddharth,
try to get response of only at+cstt=?
Its return a exec  syntax and by following it you can make your frame of at+cstt
some below point may it will help

//TCP connection profile AT+CSTT?
+CSTT: "CMNET","",""
OK APN->"CMNET"
USER->""
PASSWORD->""

and

AT+CSTT="CMNET"
OK
at+cstt=?
+CSTT: "APN","USER","PWD"
OK

It may help you
regards

Have gone past that project long back. Will report back after I try. Thanks for your input.

In most cases the problem is in low balance and account settings.
As I see, you doing all right.
AT+CGATT=1
AT+CSTT="TATA.DOCOMO.INTERNET","",""

Also, check login/password! It's unusual to have blank credential here, in my country.

Try AT+CSTT="TATA.DOCOMO.INTERNET"

tried, did not work\

What does at+cstt=? return?

Just a ERROR, as mentioned in the question above.

I mean what does the exact line AT+CSTT=? return? Also, what does AT+CSTT? return?

Sorry, AT+CSTT="TATA.DOCOMO.INTERNET","",""

Ummm, what is the response to AT+CGDCONT? and AT+CGACT?. Could try adding AT+CGACT=1,1 after AT+CGDCONT=...


text:
How to use readLine from JSSC
When I use JSSC and call serialPort.readLine(event.getEventValue()) from public void serialEvent(SerialPortEvent event) I've got fragments, not all string. What I must do to get all string from begin to "\r\n"? What I must do to get all string from my start marker (like "[start]") to my stop marker (like "[stop]")? What to modify in this code:
private static class PortReader implements SerialPortEventListener {
    public void serialEvent(SerialPortEvent event) {
        if(event.isRXCHAR() && event.getEventValue() > 0){
            try {
                String data = serialPort.readString(event.getEventValue());
                serialPort.writeByte((byte) 1);
            }
            catch (SerialPortException ex) {
                System.out.println(ex);
            }
        }
    }
}

What is the relationship to Arduino. Your question is about Java!

Anyone who uses jSSC (the most common Java serial library) to interface with the Arduino will have to implement this, so I'll answer it.

Indeed, this is a problem that will be faced by those trying to use Arduino (or similar) with a larger system.  It should either be open as an appropriate question here, or sent to stackoverflow.  Probably it is more useful here - there it may simply get lost (though if it had not been answered here, sending it there in search of more eyeballs could have made sense)

@ChrisStratton since this is more of a Java question, this doesn't belong here. I'll see if SO will take it.

The event gets fired when a single character is received, not the whole string. You have to build the string up until you get to \r\n and then process it. This is my code for a similar project. It uses a protocol where > signifies the start of a message and \r signifies the end. processMessage is a function to process the entire message and update GUI elements etc. It is invoked using runLater because the serialEvent function will be on a different thread to the GUI thread.
StringBuilder message = new StringBuilder();
Boolean receivingMessage = false;
public void serialEvent(SerialPortEvent event) {
    if(event.isRXCHAR() && event.getEventValue() > 0){
        try {
            byte buffer[] = serialPort.readBytes();
            for (byte b: buffer) {
                if (b == '>') {
                    receivingMessage = true;
                    message.setLength(0);
                }
                else if (receivingMessage == true) {
                    if (b == '\r') {
                        receivingMessage = false;
                        String toProcess = message.toString();
                        Platform.runLater(new Runnable() {
                            @Override public void run() {
                                processMessage(toProcess);
                           }
                        });
                    }
                    else {
                        message.append((char)b);
                    }
                }
            }
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
            System.out.println("serialEvent");
        }
    }
}

A simpler version for you might be the following. processMessage is called whenever a \r or \n is received and there are some bytes in the message.
StringBuilder message = new StringBuilder();
public void serialEvent(SerialPortEvent event) {
    if(event.isRXCHAR() && event.getEventValue() > 0){
        try {
            byte buffer[] = serialPort.readBytes();
            for (byte b: buffer) {
                    if ( (b == '\r' || b == '\n') && message.length() > 0) {
                        String toProcess = message.toString();
                        Platform.runLater(new Runnable() {
                            @Override public void run() {
                                processMessage(toProcess);
                           }
                        });
                        message.setLength(0);
                    }
                    else {
                        message.append((char)b);
                    }
            }
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
            System.out.println("serialEvent");
        }
    }
}

Edit:
Two things fixed:  1. Using StringBuilder instead of String to save making a lot objects every time the message is incremented. 2. Make a copy of the message string before passing to runLater otherwise when it does run it will use the up to date version of the string, which could have new characters, and thus cause problems.
Edt 2:
On Windows I found it needed if(event.isRXCHAR() && event.getEventValue() > 0) as the event would sometimes be fired with 0 bytes causing a null point exception in for (byte b: buffer)

Thak you very much. Maybe it will be better to add your answer to FAQ or something else.

@oventarb I hope you get this message - please see the updated code, there was a big error in the initial one. I had been using the erroneous code for a while myself and only just fixed it.


text:
While using Arduino Ethernet shield, do we need to explicitly select/Deselect SD and W5100 in our code?
It has been mentioned here http://arduino.cc/en/Main/ArduinoEthernetShield that corresponding libraries take care of chip select between SD and W5100 in Arduino Ethernet shield. Does it take care properly all the time? What happens if the Chipselect is not properly managed by libraries? Does that cause blocking of code?

Without the Chip Select the SPI device will just ignore all date on the SPI lines. I think you can trust most libraries to properly handle the CS pins.

Here we have a nice example of a single Shield requiring TWO libraries. The Ethernet.h and SD.h where the later appears as an after thought and is not demonstrated by the Example. As it is done so in the SD examples. However, their styles are slightly different.
The Ethernet libary as mentioned (provided within) the IDE is hardcoded to implement the Chip Select for the W5100 on corresponding pin. When using the typical purchased Ethernet Shield, there is no need to configure it. Unlike the SD library, which requires the pin to configured using the SD.begin(4) member function.
if (!SD.begin(4)) {
  Serial.println("initialization failed!");
  return;
}

Where again on the typical Ethernet shield the SD card is at pin D4.
Note being hardcode that the Ethernet library selects the matching pin to corresponding shield.
private:
#if defined(ARDUINO_ARCH_AVR)
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  inline static void initSS()    { DDRB  |=  _BV(4); };
  inline static void setSS()     { PORTB &= ~_BV(4); };
  inline static void resetSS()   { PORTB |=  _BV(4); };
#elif defined(__AVR_ATmega32U4__)
  inline static void initSS()    { DDRB  |=  _BV(6); };
  inline static void setSS()     { PORTB &= ~_BV(6); };
  inline static void resetSS()   { PORTB |=  _BV(6); };
#elif defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB162__)
  inline static void initSS()    { DDRB  |=  _BV(0); };
  inline static void setSS()     { PORTB &= ~_BV(0); };
  inline static void resetSS()   { PORTB |=  _BV(0); };
#else
  inline static void initSS()    { DDRB  |=  _BV(2); };
  inline static void setSS()     { PORTB &= ~_BV(2); };
  inline static void resetSS()   { PORTB |=  _BV(2); };
#endif
#endif // ARDUINO_ARCH_AVR

And in the case of the UNO (or the else case) Port B Bit 2 is D10.

worth noting that SD library has an alternate method of initializing and using the SD card
if (!card.init(SPI_HALF_SPEED, chipSelect)) {
  Serial.println("initialization failed. Things to check:");

where chipSelect would be D10 in this case.


text:
Arduino Mega 2560 RFID Serial Communication
I have an RFID reader: http://img.tradeindia.com/fp/1/641/264.jpg
Something like above along with ITEAD TFT shield & GSM Modem. The RFID reader has an RS-232 port as well as GND, TX and 5V pins. I am using an Arduino Mega 2560 board. I have connected the TX, GND of RFID reader to RX3 pin 15 / GND (pin) of Arduino. Note I am supplying 12 V to RFID via an adapter.
Note the ITEAD TFT shield consumes the TX0, RX0 pins—so I cannot make use of the RX0 and TX0 pins. Though I have not written the code for GSM modem.
Now while running the program below, I am getting junk output both in my TFT display as well as the serial monitor:
#define __AVR__
#include <UTFT.h>

// Declare which fonts we will be using
extern uint8_t SmallFont[];
extern uint8_t BigFont[];
extern uint8_t SevenSegNumFont[];
UTFT myGLCD(ITDB24,59,58,57,56);
String myString = "";

void setup() {
   Serial3.begin(9600);
   myGLCD.InitLCD();
   myGLCD.clrScr();
}

void loop() {
  myGLCD.setFont(BigFont);
  if (Serial3.available()) {
    int inByte = Serial3.read();
     myString += String(inByte);
    }
    if(myString.length() == 10)
      myGLCD.print(myString, CENTER, 0);
}

TFT Screen output:
1310494848
Serial Monitor Output: non printable junk character.
The value is incorrect, I am pretty sure, what am I doing wrong?
I found that the ITEAD shield is sending or rather using RX0/TX0 pins very frequently—some data is going through.
BTW what is the functionality of http://arduino.cc/en/Tutorial/SoftwareSerialExample?
How can I use 3 different Serial I/Os individually at the same time without disturbing any other I/O?

First of all, try testing 1 functionality at a time to isolate the issue.
Now you do not know if the LCD is not working correctly, or if the serial communication with the RFID module is not working correctly. Connect it to a computer and test both independently.
When getting gibberish from a serial line, usually it means the baudrate doesn't match. Both devices have to send the same amount of bits per seconds in order to communicate with each other.
This is the Arduino example to test 2 serial lines (for Arduino Mega) at the same time: http://arduino.cc/en/Tutorial/MultiSerialMega

i think the RFID is a other baud rate e.g 115200.. i dont know the device, i dont know if this is the problem, but test it :)


text:
Arduino - Finite State Machine does not start in the initial state
I'm building a state machine using 6 flip-flopsD, and an G input coming from an infrared sensor. This circuit should count from 0-35.
The problem is that it always starts in state 111111. That is, after it passes through Flip-flop D A, B, C, D, E, F = 1;
Here's my code:
#include "flipflopD.h"

boolean a1,b1,c1,d1,e1,g1;//display 1
boolean a2,b2,c2,d2,e2,f2,g2;//display 2
boolean Aa=false;
boolean Bb=false;
boolean Cc=false;
boolean Dd=false;
boolean Ee=false;
boolean Ff=false;
boolean A=false;
boolean B=false;
boolean C=false;
boolean D=false;
boolean E=false;
boolean F=false;
boolean G=false;//receiver

void setup() {

    //DISPLAYS
    pinMode(A0, OUTPUT);
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(12, OUTPUT);
    pinMode(13, OUTPUT);

    pinMode(A2, INPUT);// IR RECEIVER
}

void loop() {
    //  Counter
    G = digitalRead(A2);
    Aa = flipflopD((A||!B||!C||!D && !A||B||C||D||E||F||G), A, G);
    Bb = flipflopD((!A||B||!C||G && !A||B||F||!G && !A||B||E||!F && !A||B||D||!E && !A||B||C||!D && !A||!B||C||D||E||F||G), B, G);
    Cc = flipflopD((!A||C||!D && !A||C||!E && !A||C||!F && !A||C||!G && !A||!C||D||E||F||G), C,G);
    Dd = flipflopD((!A||D||!E && !A||D||!F && !A||D||!G && !A||!B||!C||D && !A||!D||E||F||G && !A||!B||C||!E||!F||!G), D, G);
    Ee = flipflopD((!A||E||!F && !A||E||!G && !A||!E||F||G && A||!B||!C||!D||E && !B||!C||!D||!E||F||G), E, G);
    Ff = flipflopD((!A||!F||G && !A||F||!G && !B||!C||!D||!F||G && !B||!C||!D||F||!G && A||!B||!C||!D||E||G), F, G);

    A=Aa;
    B=Bb;
    C=Cc;
    D=Dd;
    E=Ee;
    F=Ff;

    //   ABCDEF TO 7 Segments
    a1 = !A||B||D && !A||B||C & A||!B||!C||!D;
    b1 = !A||B && !A||C||E && !A||C||D && A||!B||!C||!D;
    c1 = !A||!B||C||E && !A||!B||C||D && !A||C||D||E && !A||B||!C||!D + A||!B||!C||!D;
    d1 = !A||B||D && !A||B||C && A||!B||!C||!D;
    e1 = !A||B||!C||D && !A||B||D||!E && !A||B||C||!D;
    g1 = !A||B||D && !A||B||C & A||!B||!C||!D;

    a2 = (!A||!C||E  &&  !A||!B||!D||!F  &&  !A||!B||D||F && !A||!B||C||!E && !A||C||D||!E && !A||B||!C||!F && !A||B||!D||F && !A||B||E||!F && !B||!C||!D||E||F && A||!B||!C||!D||!E);
    b2 = (!A||B||D && !B||!C||!D||!E && !B||!C||!D||!F && !A||!B||!E||!F && !A||!C||!D||F && !A||!C||!D||E && !A||!C||E||F && !A||!D||E||F && !A||!B||C||!E && !A||!B||C||!F && !A||C||!E||!F);
    c2 = (!A||F && !A||!D||!E && !A||C||E && !A||B||!D && !A||B||!E && !B||!C||!D||F && !A||!B||!C||D && A||!B||!C||!D||E);
    d2 = (!A||!B||!C||!D||!F && !A||!B||!C||E||!F && !B||!C||!D||E||F && !A||!C||D||!E||F && !A||!B||C||!D||!E && !A||!B||C||!E||!F && !A||C||!D||!E||!F && !A||!B||C||E||F && !A||C||!D||E||F && !A||C||D||E||!F && !A||B||!C||!E||F && !A||B||!D||E||!F && !A||B||!C||D||!E && !A||B||!C||D||F && !A||B||D||!E||F && A||!B||!C||!D||!E);
    e2 = (!A||!C||!D||!F && !A||!C||E||!F && !A||!D||E||!F && !A||B||D||!F && !B||!C||!D||!E||!F && !A||!B||C||!E||!F);
    f2 = (!A||!C||!E||!F && !A||C||!D||!E && !A||C||E||!F && !A||B||C||!E && !A||!B||!C||D||!E && !A||!B||!C||D||!F && !A||!B||C||D||E && !A||B||!C||!D||E && A||!B||!C||!D||E);
    g2 = (!A||C||!E && !A||!C||!D||E && !A||!C||E||!F && !A||!B||D||!E && !A||!B||C||D && !A||B||!D||!F && !A||B||!C||E && A||!B||!C||!D);

    // OUTPUTS

    //DISPLAY 2
    digitalWrite(A0,a2);
    digitalWrite(2,b2);
    digitalWrite(3,c2);
    digitalWrite(4,d2);
    digitalWrite(5,e2);
    digitalWrite(6,f2);
    digitalWrite(7,g2);

    //DISPLAY 1
    digitalWrite(8,a1);
    digitalWrite(9,b1);
    digitalWrite(10,c1);
    digitalWrite(11,d1);
    digitalWrite(12,e1);
    digitalWrite(13,g1);
}

Here's my Flip-FlopD:
boolean flipflopD(boolean D, boolean Q, boolean CLK){
  boolean Qo=false;
    if (CLK=true) {
      Qo=D;
    } else {
  Qo=Q;
  }
  return Qo;
}

Can someone tell me what's wrong?

One potential error source: In your D-Flip-Flop code, you have
boolean flipflopD(boolean D, boolean Q, boolean CLK){
  boolean Qo=false;
    if (CLK=true) {
      Qo=D;
    } else {
  Qo=Q;
  }
  return Qo;
}

You probably want to do a comparison with double == instead of an assignment with = in the line
if(CLK=true)

This causes the if to always evaluate to true and set Qo=D.
Also, I am not really sure if this is what you want:
a1 = !A||B||D && !A||B||C & A||!B||!C||!D;

First, you're mixing && (logical-and) with the bitwise & here. Next, C++ operator precedence dictates that the &&has a higher priority than ||. This looks like a conjunctive-normal-form of some boolean function, thus I would group the AND terms in parenthesis, like
a1 = (!A||B||D) && (!A||B||C) && (A||!B||!C||!D);

In the c1 expression you are also suddenly using the + operator in a chain of logical expressions, which looks wrong.
Overall I don't quite get how this should work. If you have an IR receiver connected to A2, from which you read the "CLK" input, it will get some 39kHz input wave when you point a IR remote at it and press a button. And you want that on each CLK rise/fall the Arduino reacts to it by calculating the output for a seven-segment display? Your Arduino Uno/Nano with its 16MHz will take some time to execute each of the statements in the loop, sequentally. So what you're doing is actually sampling the A2 input every now and then -- how often exactly, I don't know, maybe with a few kilohertz. Your Arduino might sample the input at the wrong time or not fast enough to react the way you expect. digitalRead and digitalWrite are notoriously slow, maybe try direct port access or an interrupt-based approach. Of course, calculating all these AND, OR and NOT expressions will take some processing time, too.
This sort of combinational logic is more suited for an FPGA implementation, not for an Arduino.


text:
Wrong conversion of time_t to char
I have a simple sample of code that i want to convent a time_t to char array in order to concatenate it after, in an other array.
Code:
time_t unixt;
char exm [40];

unixt = RTC.get();
Serial.println(unixt);
dtostrf(unixt, 10, 0, exm);
Serial.println(exm);

The problem that i face is that, the console is printing different the second one every time like this:
1548258220
1548258200

I tried also with unsigned long with no result either. Can someone point me what's wrong or an other way of doing this?

Use ultoa() instead of dtostrf(). The former is meant to serialize
unsigned long integers, while the later is for floating point numbers.
By using dtostrf(), you are implicitly converting unixt to a
floating point number. The Arduino Mega only supports single precision
floating point, so this conversion incurs some loss of precision, hence
the result you see.

Thanks a lot! That was exactly what i needed.


text:
Help with code for pushbutton connected to adafruit motorshield v2
can anybody assist me with a code? I am using arduino uno with adafruit v2 motor shield stacked on top. I am using a pushbutton and one DC motor and I want the state of the push button to change after it has been pushed for a few seconds. That is I want the motor to stop running even though the push button is still pushed down.
Here is the code I'm using:
    /*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438
*/

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);

// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 4;

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);

}

void loop() {
  uint8_t i;

    // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(0);        // delay in between reads for stability

  if (buttonState==1){
     delay(1000);

  myMotor->run(FORWARD);
    myMotor->setSpeed(150);
    delay(1000);

 }

 else if (buttonState==0){
  myMotor->run(FORWARD);
    myMotor->setSpeed(0);

  }

}

stop thinking I want the state of the push button to change after it has been pushed for a few seconds ........ start thinking I want the state of a variable to change when the push button is pressed and I want the state of the variable to remain the same for a few seconds

You need to do various things:
You need to change your logic not to use delay. Search on "Arduino Blink Without Delay" to find examples of doing timed actions with millis() instead of using delay.
Then you need to adjust your logic to start running the motor when the user presses a button, and stop running the motor when either the user releases the button or enough time elapses.


text:
How to download files from a user/password protected web server (user:passw@ip:port)
I need to do a GET request in the form: user:passw@ip:port/streaming/channels/1/picture  to capture a still frame from an Ip camera.
Is there a way to do this with the ESP8266HTTPClient.h library?
The samples show a GET request as: http.begin(host,port,url);
What I need to do is get the user:passw@ put in before the host:url

use the http.setAuthorization(user, passw) method.

It would depend whether it's digest or basic authentication.
If former, you have a nice example here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino
and if it's the latter, you can just do something like this: http.begin("http://user:password@example.com/test.html");


text:
How to send an email with Arduino and a WiFi shield?
I want to make my Arduino connect via WiFi and then send an email. The idea is very simple, but the problem is that I've never worked with those protocols and other things before. I just wanted something that's already premade, so I would just change the information.
Is there a library or a function that sends the email?
If someone could help me to understand, so I can make it myself, that would be the best.

Email might be too much for something that runs on a 16 MHz. Timeout would probably prevent this from happening. What board are you using?

But this is fairly simple with an external service as temboo or similar services, and perfectly possible with an arduino. If the user posted some code using a library for one of such services, would it be an adequate question? So the problem is that it is not adequate to recommend SW solutions due to SO policies?

@drodri I don't quite understand your last few sentences... are you asking if it would be on topic if using a service like that? If so, then it could be considered to answer the question. I'm not aware of any SE policies that don't allow recommending software solutions... do you mean no shopping questions? If so, that's a completely different topic.

It is certainly possible and I use it with small text alerts. Look up the Ethernet library - the WiFi version should work in a similar way. Essentially you open a connection to port 25 (or applicable port at your mail server) and negotiate the HELO with println() and send the email. Lookup "telnet to send email" as it is essentially the syntax you will need. Note that most email providers will block such attempts to send email (to restrict spam-bots), so be sure it is permitted before trying it.

What you're looking for is a SMTP (Simple Mail Transport Protocol) library. A Google search finds 2 for the Arduino:

SMTPClient
This seems to be a minimal-capability SMTP-only library that piggybacks on top of a connection library.

FullIP
This seems to be a full IP package for the Arduino that works with select network devices which includes SMTP capability.

I am facing the same problem, but concerned about the security. If using e.g. my gmail account, I would have to provide my gmail passwd to the smtp connection, which is not very secure. I have tried external services, as temboo, which allows to store my gmail credentials, and I connect to the service (http) via service credentials, which are safe either, but at least seems an extre level of indirection. Which approach would you recommend? Does this concern deserve its own question?

GMail can use SSMTP, which is SMTP secured with SSL. I'm not sure if there are any SSMTP libraries for Arduino though, or even if it has enough power for it. You may need something like the Due or Yun (or something bigger, like a RPi or BB) which can provide a bit more oomph.

@drodri For the first library listed, it only uses an unauthenticated SMTP server... no passwords. There was some mention about implementing that later, but I don't know if it would use SSMTP or not.

You actually present 2 issues here, which can be handled separately:

You are concerned about having a WiFi, not an Ethernet shield. This doesnt affect at all for sending emails or any other network stuff. When you have internet connection, it is almost transparent from the programming side. So I recommend first to try your wifi shield connection and configuration as a separate problem, with a more simple task, as a simple HTTP_GET to a known web page. A function like this might help, assuming that you have an instance of WiFiClient (which is a Client), that has been connected (with connect) to the URL and port 80:
void http_get(Client& www, char website[], char webpage[], int timeout, Stream& stream) {
    if (www.connected()) {
        int n = www.print("GET ");
        www.print(webpage);
        www.print(" HTTP/1.1\r\n");
        www.print("Host: ");
        www.print(website);
        www.print("\r\n");
        www.print("\r\n");
    } else {
        stream.println(F("Connection failed get"));
        return;
    }

    /* Read data until either the connection is closed, or the idle timeout is reached. */
    unsigned long lastRead = millis();
    while (www.connected() && (millis() - lastRead < timeout)) {
        while (www.available()) {
            char c = www.read();
            stream.print(c);
            lastRead = millis();
        }
    }
}

The second problem is that you want to send an email. One you have a connection, it doesnt matter if it is wifi or wired. The above recommended libraries (SMTPClient, FullIP) will directly connect to your provider (e.g. gmail) and will request your gmail password, something that is not secure over non secure connections (and those libraries do not seem to provide secure layer), so personally I am not comfortable with that option. I have been using the temboo service, that allows to send emails, and I have found it to be quite convenient and simple. Furthermore, they also have many other services. The service stores your gmail or whatever provider credentials, and you access the service via a Secret Key and App Password they provide. While this keys might not be fully secure to be sent via non secure layers, at least it only compromises your app in the cloud application, which you might simply manage, and not your full email account. (Disclaimer: I have no relation with temboo, and there might be other similar services for this task, e.g. Carriots, I simply say that I have used them with success for this task and feel it is relatively simple). Your code using temboo, could be something like:
TembooChoreo choreo(client); // your WiFiClient object

// Set Temboo account credentials
choreo.setAccountName(temboo_account);
choreo.setAppKeyName(temboo_app);
choreo.setAppKey(temboo_app_key);

// credential is the name of your gmail profile in temboo
choreo.setCredential(credential);
choreo.addInput("MessageBody", body);
choreo.addInput("Subject", subject);
choreo.addInput("ToAddress", address);

//Identify the Choreo to run
choreo.setChoreo("/Library/Google/Gmail/SendEmail");

choreo.run();
choreo.close();

Cheers for that! You and @Ignacio Vazquez-Abrams Helped me ALOT! really! But, if i use SMTP/FUllIp instead of those more secures connections, would it be easier/simple to code? My project doesn't need security because it's just an automation for myself and i'll create a mailing email for that

If you don't need that security, and you are fine with just sending emails with a dedicated email account, the SMTPClient is indeed very simple to code, as you can see in the README of https://github.com/gregington/SMTPClient, I would say difficulty of code and setup is the same, but the SMTPClient will not require to configure your temboo service, which is also easy but will take you some time more. So you can stick with the SMTP, while considering external services as temboo for more complicated tasks, for example if your service (twiter, dropbox?) requires secure or more complex connection

There may be a problem with sending Email from Arduino, but not where you are expecting it. SMTP protocol is super simple, even Arduino can handle it. But you will need SMTP server somewhere that will talk to your Arduino. SSL connections (as on Gmail) are out of consideration (code to handle the encryption would be too much for Arduino) so you'd have to find mail provider that provides plain SMTP - and there aren't many. If you will set up one yourself, say on your home PC with static IP address, it would be an invitation for spammers and a guaranteed way to get your IP blacklisted by Spamhaus. My advice would be to have Python, PHP or Perl script hosted somewhere that will handle HTTP POST requests from your Arduino and do Email sending. It is safer and simpler.

Actually many ISPs (here in the US at least) provide non-SSL mail servers that only allow incoming connections from their customers' IP ranges; if your Arduino is going to be on a fixed connection (e.g. your home WiFi), you could use the ISP's SMTP server.

Sending gmail via SMTP from an Arduino is completely feasible. I am doing it from an Arduino MKR WIFI 1010 using the WIFINina library. I'm  pretty sure that my solution will work on any of the SAMD based Arduinos.
There is a bit o "setting up" to do, but it's not hard.
Check out my solution on my gitlab repo.
Be sure to do the config BEFORE trying to execute the code...
Good luck!
GF

The simplest way to send email from Arduino is to make HTTP request to IFTTT. See Arduino - IFTTT


text:
Sense distance with Bare Conductive's Touch Board
How can I sense distance with Bare Conductive's Touch Board, like they suggest in their product video?
I know how I can set the touch and release thresholds, so my Touch Board is more sensitive and triggers before I touch a sensor. What I want to do is get the information how near I am. Not in centimeters or so, but a simple value telling me when I'm nearer to or farther from the sensor like in the video.

As a member of the Bare Conductive team, I can tell you that looking at the grapher will be helpful to you. The grapher is a processing sketch that requires the Touch Board to be running the Datastream code. Datastream will give you the sort of raw electrode data that you're looking for.


text:
My counting function is not working with the text on my lcd
I want the bottom row of my LCD to display the counting function and include text:
lcd.setCursor(0, 1);
lcd.print("Launch in"millis()/1000);

But it comes out with an error, what part is wrong?

The last line in the code you provided won't compile.
The lcd.print() function expects a char, byte, int, long or string (taken from the LiquidCrystal docs) and you're trying to combine a string and an int which the compiler isn't going to understand.
The easiest way to print both would be to have two lcd.print statements:
lcd.print("launch in ");
lcd.print(millis()/1000);

Most of this is taken from quickly googling displaying time on an lcd screen.
Check out this forum post, it seems similar to what you want to do: click me!

Change the last line to:
lcd.print("Launch in " + (millis() / 1000));

The + concatenates the string Launch in with the number that results from millis() / 1000.

lcd.setCursor(0, 1);
lcd.print("Launch in ");
lcd.print(millis()/1000);

Can you add why the original code didn't work? Answers are best if they have some explanation, not just code.